Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): advertise all 14 migration tables, and reconcile the docs with the code

Yudhi Armyndharis409ccec9d368
diff --git a/.env.example b/.env.example
index ea70da14a..2fae65b89 100644
--- a/.env.example
+++ b/.env.example
@@ -367,8 +367,10 @@ WEBHOOK_SSRF_PROTECT=true
# Server-side media size/time limits:
# MEDIA_DOWNLOAD_ENABLED=true # Set to false to skip downloading inbound media entirely
# # (no decryption, no memory allocation, no storage).
-# # NOTE: disabling also makes hasMedia report false and removes the
-# # media field from webhooks and the dashboard.
+# # NOTE: the media FIELD is not removed — it arrives as the omitted
+# # marker { mimetype, filename?, omitted: true, sizeBytes }, the
+# # same shape an oversized payload gets. hasMedia still reports
+# # true: it mirrors the engine's own flag, not this setting.
# # Accepts true/false/1/0/yes/no; anything else fails the boot,
# # because an unrecognised value silently means ENABLED.
# EXPORT_INLINE_MEDIA_BUDGET_BYTES=8388608
@@ -379,9 +381,9 @@ WEBHOOK_SSRF_PROTECT=true
# # unbounded export produces a backup the import refuses with 413
# # (it rides BODY_SIZE_LIMIT, 25mb by default). Spent newest-first
# # within each table, so a budget that cannot hold everything
-# # keeps the most recent media. A URL-referenced
-# # payload is never counted or dropped — it is a pointer, not
-# # bytes, whatever the case of its scheme. 0 omits every payload.
+# # keeps the most recent media. An http/https payload is never
+# # counted or dropped — it is a pointer, not bytes, whatever the
+# # case of its scheme. 0 omits every payload.
# STORE_EPHEMERAL_MESSAGES=true # Set to false to skip persisting and dispatching incoming
# # WhatsApp disappearing messages (ephemeralDuration > 0).
# # Default: true (backward compatible — store everything).
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1d9b4cd6a..3b5d93d2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,7 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **A WhatsApp-initiated unlink now clears a session's stored credentials once rather than twice** — whatsapp-web.js can raise the logout event more than once for a single unlink and nothing deduplicated it, so the repeats raced each other and a still-open browser into the `ENOTEMPTY` failure the removal now carries the retry budget to survive.
- **A reaction to a message the gateway never stored no longer vanishes** — the `message.reaction` webhook and the dashboard stream were both gated on the stored row, so a reaction to an ephemeral message, or to one that arrived before the session went live, was dropped with no error and no log.
- **`MEDIA_DOWNLOAD_ENABLED` is now validated at boot** — it is read as "anything that is not `false`/`0`/`no`", so a typo left inbound media being decrypted and base64-inlined into every message row instead of disabling it. Only `true`/`false`/`1`/`0`/`yes`/`no` are accepted now, so a spelling like `on` that used to work will fail startup until it is changed.
-- **A data export now bounds the inline media it carries** — base64 inflates a single 50 MiB attachment to 66 MiB, past the import's own 25mb request-body limit, so a backup could export cleanly and then be refused with `413` on restore. `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB by default) caps the total across messages and bulk batches, spending it on the newest media first, and an over-budget message payload exports as the omitted marker while a bulk-batch entry simply loses its `base64`; a URL-referenced payload is never dropped whatever the case of its scheme, and a large enough text-only history can still exceed the limit.
+- **A data export now bounds the inline media it carries** — base64 inflates a single 50 MiB attachment to 66 MiB, past the import's own 25mb request-body limit, so a backup could export cleanly and then be refused with `413` on restore. `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB by default) caps the total across messages and bulk batches, spending it newest-first within each table and serving messages before batches, and an over-budget message payload exports as the omitted marker while a bulk-batch entry simply loses its `base64`; a URL-referenced payload is never dropped whatever the case of its scheme, and a large enough text-only history can still exceed the limit.
- **A data import now carries each session's ownership lease by its remaining time instead of its original deadline** — a restore re-applied the deadline unchanged, so one that ran longer than a claim had left committed that claim as expired, including claims held by other nodes whose engines never stopped.
- **A refused data import no longer offers a retry that stops live engines** — the one refusal whose retry is destructive now carries `IMPORT_WOULD_ORPHAN_ENGINES` and the dashboard matches it positively, so a refusal that only asks the operator to wait can no longer present a confirm whose OK re-runs the replace-all with `stopOrphans=true`.
- **A data import is refused with `409` when another transaction holds the connection** — on SQLite it would otherwise nest inside that transaction and commit into it rather than to disk, so a restore reported as successful could vanish with that transaction's rollback.
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 0a43396d9..0c55f920c 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -1071,6 +1071,9 @@ export const infraApi = {
dataDbType: string;
tables: Record<string, unknown[]>;
counts: Record<string, number>;
+ // Optional tables absent from an older schema. Always present in the response; a non-empty
+ // list means the backup is partial, not that those tables were empty.
+ skippedTables: string[];
}>('/infra/export-data'),
// 200 contract includes the orphan-engine reconciliation result (restartRequired / notices /
// stopped+failed ids). 409 has several causes and the error's `code` distinguishes them:
diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.md
index 286e350bc..3937d1854 100644
--- a/docs/03-system-architecture.md
+++ b/docs/03-system-architecture.md
@@ -239,7 +239,8 @@ connections**:
- **`data`** — the pluggable user-data connection: `sqlite` (default) or `postgres`, selected by
`DATABASE_TYPE`. Owns the session/webhook/message/template/engine entities, plus the
integration-fabric (`plugin_instances`, `ingress_events`, `conversation_mappings`,
- `integration_delivery_failures`) and status-store (`status_updates`) entities.
+ `integration_delivery_failures`), status-store (`status_updates`) and automation
+ (`automation_rules`) entities.
The engine is provided by `EngineModule` as the `EngineFactory` **class** (a normal injectable, not a
string token). Storage and cache are provided as the `StorageService` and `CacheService` classes by
@@ -384,7 +385,7 @@ flowchart TB
### NestJS Module Organization
-Trimmed to the load-bearing directories — `src/modules/` holds 27 feature modules. Only `*.module.ts`
+Trimmed to the load-bearing directories — `src/modules/` holds 31 feature modules. Only `*.module.ts`
is common to all of them; the rest of the shape varies. Most pair a `*.controller.ts` with a
`*.service.ts`, but `events/` is a WebSocket gateway, `mcp/` an MCP server and `queue/` pure BullMQ
wiring (none of the three has either); `docker/` and `status-store/` are service-only; `health/`,
@@ -428,6 +429,9 @@ src/
│ ├── auth/ # API-key auth: auth.service.ts, guards/, decorators/, entities/
│ ├── queue/ # BullMQ wiring + processors/
│ ├── integration/ # Integration fabric (plugin instances, ingress, mappings)
+│ ├── automation/ # Autoreply rules (automation_rules, the 14th migration table)
+│ ├── media/ chat-media/ # Inbound media handling + the optional chat-media archive
+│ ├── takeover/
│ └── plugins/ mcp/ events/ infra/ docker/ settings/ metrics/ audit/ health/
│
└── database/ # data-source.ts / data-source-main.ts
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 88dd52833..f697d53ed 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -188,6 +188,10 @@ erDiagram
varchar proxyType
timestamp connectedAt
timestamp lastActiveAt
+ varchar nodeId
+ timestamp claimedAt
+ varchar nodeUrl
+ timestamp leaseExpiresAt
timestamp createdAt
timestamp updatedAt
}
@@ -837,7 +841,7 @@ export class AddMessagesWaMessageIdUnique1781300000000 implements MigrationInter
### Retention Policies
-Five tables have an automated _time-based_ retention job, across four services: **`audit_logs`**, **`status_updates`**, **`webhook_delivery_failures`**, **`ingress_events`** and **`integration_delivery_failures`**. Separately, **`baileys_stored_messages`** is capped per session rather than by age — each write keeps the newest `BAILEYS_MESSAGE_STORE_LIMIT` rows (default 5000) for that session and deletes the rest. Everything else is kept indefinitely (sessions, webhooks, batches, templates, conversation mappings, plugin instances) and is removed only by user action (e.g. deleting a session) or operational backup/restore — the `messages` history table in particular has no auto-purge and grows without bound.
+Five tables have an automated _time-based_ retention job, across four services: **`audit_logs`**, **`status_updates`**, **`webhook_delivery_failures`**, **`ingress_events`** and **`integration_delivery_failures`**. Separately, **`baileys_stored_messages`** is capped per session rather than by age — each write keeps the newest `BAILEYS_MESSAGE_STORE_LIMIT` rows (default 5000) for that session and deletes the rest. Everything else is kept indefinitely (api keys, sessions, webhooks, batches, templates, conversation mappings, plugin instances, lid mappings, automation rules) and is removed only by user action (e.g. deleting a session) or operational backup/restore — the `messages` history table in particular has no auto-purge and grows without bound.
| Data Type | Default Retention | Configurable |
| ----------------------------- | ----------------- | --------------------------------------------------------------- |
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 5e16ee0d6..b918f48da 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1237,12 +1237,12 @@ Get the processing status and progress of a bulk batch.
### Send pacing (opt-in, `429 SEND_PACING_LIMITED`)
Every outbound message send — the `messages/send-*` routes, `messages/edit`, `messages/forward`,
-bulk batches, status posts and `messages/send-product` — passes an optional pacing governor before
+bulk batches, status posts and both catalog sends (`messages/send-product`, `messages/send-catalog`) — passes an optional pacing governor before
it reaches WhatsApp. Actions on existing messages (react, vote, pin, star) are not sends and are
not paced. It is **off by default**: unless `SEND_PACING_ENABLED=true`, nothing is refused and no
extra work is done.
-When enabled, two rules can refuse a send:
+When enabled, three rules can refuse a send:
| Rule | What it means |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -5002,7 +5002,7 @@ Export every row of the 14 migration tables from the Data DB as JSON. Read-only,
> **Inline media is carried up to a budget, then omitted.** `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one export may hold, counted across both `messages` and `messageBatches`. Within each of those tables it is spent newest-first — messages by `timestamp`, batches by `created_at` — so an export that cannot carry everything keeps the most recent media rather than whatever the database happened to return first. Messages are served before batches, so a long history can exhaust the budget before any batch is reached. An over-budget payload on a `messages` row arrives as the omitted marker — `{ mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits when an inbound payload exceeds `MEDIA_DOWNLOAD_MAX_BYTES` — so those messages restore without their pictures. A `messageBatches` entry carries no marker: it simply loses its `base64` and keeps `url`, `mimetype` and `caption`, which is the shape a batch already has once it reaches a terminal state. Without the bound, one 50 MiB attachment becomes 66 MiB of base64 and exceeds the import's own request-body limit (`BODY_SIZE_LIMIT`, 25mb by default), producing a backup this gateway refuses to restore with `413`.
>
-> A **URL-referenced** payload is never counted or dropped: `metadata.media.data` holds either base64 or the URL a send was given, and a URL is a pointer worth a few dozen bytes. The scheme is matched case-insensitively, as both engine adapters do when they fetch it.
+> An **http/https** payload is never counted or dropped: `metadata.media.data` holds either base64 or the URL a send was given, and such a URL is a pointer worth a few dozen bytes. The scheme is matched case-insensitively, as both engine adapters do when they fetch it; a URL with any other scheme is treated as bytes.
>
> This bounds the media, not the export — a large enough text-only history still exceeds the import limit, because every row costs a few hundred bytes of scaffolding whatever was said. For a backup that keeps everything, use `scripts/backup.sh`: it snapshots the database file itself (and `pg_dump`s Postgres), so inline media rides along regardless of this budget.
@@ -5160,7 +5160,7 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
}
```
-`warnings` are per-row import failures — they force a **rollback** and `imported:false`. `notices` are non-fatal operator messages (orphan-engine reconciliation detail) and never roll anything back. `restartRequired` is `true` when engines were left pointing at sessions the restore removed (`force`) or when an orphan teardown failed. `orphanedEngines` lists the session ids with a live engine the restored data no longer contains; `stoppedOrphanEngines`/`failedOrphanEngines` report how `stopOrphans` went.
+`warnings` are per-row import failures — they force a **rollback** and `imported:false`. `notices` are non-fatal operator messages (orphan-engine reconciliation detail) and never roll anything back. `restartRequired` is `true` from any of three causes: engines left pointing at sessions the restore removed (`force`), an orphan teardown that failed, or sessions running on another node, which this request has no channel to stop. `orphanedEngines` lists the session ids with a live engine the restored data no longer contains; `stoppedOrphanEngines`/`failedOrphanEngines` report how `stopOrphans` went.
**Orphan-engine pre-flight.** Before the transaction opens, any running engine whose session id is absent from `tables.sessions` is an orphan (the replace would delete its DB row, leaving an unstoppable engine writing into freshly restored tables). Default behaviour is to refuse with `409` listing those ids; `stopOrphans: true` stops them in-request and proceeds; `force: true` proceeds and leaves them running until restart.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 807e6fcee..7d1d66370 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -1303,7 +1303,7 @@ curl -X POST "$BASE/api/infra/import-data" \
-H "Content-Type: application/json" \
-d '{
"tables": {
- "sessions": [ { "id": "s1", "name": "main", "status": "READY", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
+ "sessions": [ { "id": "s1", "name": "main", "status": "ready", "phone": "15551234567", "pushName": "Me", "config": {}, "proxyUrl": null, "proxyType": null, "connectedAt": "2026-06-25T00:00:00.000Z", "lastActiveAt": "2026-06-25T00:00:00.000Z", "createdAt": "2026-06-25T00:00:00.000Z", "updatedAt": "2026-06-25T00:00:00.000Z" } ],
"webhooks": [], "messages": [], "messageBatches": [], "templates": [], "baileysStoredMessages": [],
"lidMappings": [], "pluginInstances": [], "conversationMappings": [], "ingressEvents": [],
"webhookDeliveryFailures": [], "integrationDeliveryFailures": [], "statusUpdates": [], "automationRules": []
diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.md
index 4dc5ce935..ec913d097 100644
--- a/docs/14-migration-guide.md
+++ b/docs/14-migration-guide.md
@@ -113,6 +113,13 @@ curl -X POST 'http://localhost:2785/api/infra/import-data' \
-d @data-backup.json
```
+> [!IMPORTANT]
+> Post the whole exported file, as the `-d @data-backup.json` above does. The import empties all 14
+> migration tables before repopulating, so a hand-built body carrying only some keys restores the rest
+> **empty**. The export also bounds the inline media it carries
+> (`EXPORT_INLINE_MEDIA_BUDGET_BYTES`, 8 MiB by default); for a byte-exact copy including media, use
+> `scripts/backup.sh`, which snapshots the database file itself.
+
> [!NOTE]
> **Dual-Database Architecture**
>
diff --git a/docs/16-risk-management.md b/docs/16-risk-management.md
index df4484b75..aa44cdf50 100644
--- a/docs/16-risk-management.md
+++ b/docs/16-risk-management.md
@@ -122,9 +122,16 @@ Alongside that:
- A single bulk request carries at most 100 messages (`@ArrayMaxSize(100)` on
`SendBulkMessageDto.messages`); a 101st entry is rejected by the global `ValidationPipe` with HTTP 400.
-Not implemented: there are no per-minute / per-hour / per-day send caps, no media-specific delay and
-no new-number warmup enforcement. The guidelines below are operator discipline, not something the
-gateway enforces.
+Opt-in: `SEND_PACING_ENABLED=true` adds a per-UTC-day send cap whose allowance grows with the
+session's age (`SEND_PACING_WARMUP_SCHEDULE`), a separate cap on new conversations
+(`SEND_PACING_COLD_DAILY_CAP`) and a consecutive-failure breaker — see
+[06 §Send pacing](./06-api-specification.md). It is **off by default**, and it counts only sends that
+write a `messages` row, so status posts, catalog sends and message edits are checked against the cap
+without counting into it.
+
+Still not implemented: there are no per-minute or per-hour caps and no media-specific delay. With
+pacing off — the default — the guidelines below are operator discipline, not something the gateway
+enforces.
**User Guidelines:**
@@ -544,9 +551,10 @@ The gateway enforces HTTP request throttling (`@nestjs/throttler`, registered gl
| `SIMULATE_TYPING` / `SIMULATE_TYPING_MAX_MS` | on / 5000 ms | Typing pause, text sends only (`send-text` / `send-template`) |
These bound API traffic and bulk pacing — they are **not** per-session WhatsApp send caps. The
-gateway does not count messages per minute, hour or day per session, so staying inside WhatsApp's
-undocumented limits remains the operator's responsibility. The thresholds below are targets for
-operator-side monitoring, not values the gateway enforces.
+gateway counts no messages per minute or hour, and counts per UTC day only when
+`SEND_PACING_ENABLED=true`, which is off by default; with it off, staying inside WhatsApp's
+undocumented limits remains entirely the operator's responsibility. The thresholds below are targets
+for operator-side monitoring, not values the gateway enforces.
**Monitoring Metrics:**
diff --git a/openapi.json b/openapi.json
index acb38ee36..b9d368317 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3382,6 +3382,7 @@
},
"tables": {
"type": "object",
+ "description": "Every one of the 14 migration tables is emptied before the restore runs, so a key omitted here is restored EMPTY rather than left untouched. Post the whole GET /api/infra/export-data payload, not a hand-built subset.",
"properties": {
"sessions": {
"type": "array"
@@ -3395,8 +3396,35 @@
"messageBatches": {
"type": "array"
},
+ "templates": {
+ "type": "array"
+ },
+ "baileysStoredMessages": {
+ "type": "array"
+ },
+ "lidMappings": {
+ "type": "array"
+ },
+ "pluginInstances": {
+ "type": "array"
+ },
+ "conversationMappings": {
+ "type": "array"
+ },
+ "ingressEvents": {
+ "type": "array"
+ },
+ "webhookDeliveryFailures": {
+ "type": "array"
+ },
+ "integrationDeliveryFailures": {
+ "type": "array"
+ },
"statusUpdates": {
"type": "array"
+ },
+ "automationRules": {
+ "type": "array"
}
}
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index cb32c1ed5..2e1266d43 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1816,7 +1816,7 @@ describe('BaileysAdapter inbound fan-out', () => {
}
});
- it('inbound media: skips download and omits media field when MEDIA_DOWNLOAD_ENABLED=false', async () => {
+ it('inbound media: skips download and emits the omitted marker when MEDIA_DOWNLOAD_ENABLED=false', async () => {
const prev = process.env.MEDIA_DOWNLOAD_ENABLED;
process.env.MEDIA_DOWNLOAD_ENABLED = 'false';
try {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index f95e82c64..5a5151734 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2511,7 +2511,7 @@ describe('WhatsAppWebJsAdapter inbound media (MEDIA_DOWNLOAD_ENABLED=false)', ()
else process.env[ENV] = orig;
});
- it('skips media download and omits the media field when disabled', async () => {
+ it('skips the media download and emits the omitted marker when disabled', async () => {
process.env[ENV] = 'false';
const adapter = new WhatsAppWebJsAdapter({
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 0891804c9..e087e14bc 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -134,7 +134,7 @@ const SHARED_CONNECTION_DIALECTS = new Set(['better-sqlite3', 'sqlite']);
/**
* Aggregate budget for the inline base64 media ONE export may carry, counted in the encoded bytes
* that actually land in the JSON body. Override with EXPORT_INLINE_MEDIA_BUDGET_BYTES; 0 omits every
- * payload, and a garbage value falls back to the default.
+ * payload, and anything that is not a non-negative decimal integer falls back to the default.
*
* The export is bounded by nothing while the import rides the global request body limit (25mb by
* default, `resolveBodyLimit`), so unbounded inline media produces a backup this gateway then refuses
@@ -360,8 +360,8 @@ export class InfraDataController {
}
};
- // One budget shared by both tables that can carry inline media, so the total is what is bounded
- // rather than each table separately.
+ // One budget shared by the two tables that carry a full inline payload — `messages` and
+ // `message_batches` — so the total is what is bounded rather than each table separately.
const exceedsBudget = createInlineMediaBudget();
const messages = await queryOptionalTable<MessageRow>('messages');
@@ -462,12 +462,23 @@ export class InfraDataController {
},
tables: {
type: 'object',
+ description:
+ 'Every one of the 14 migration tables is emptied before the restore runs, so a key omitted here is restored EMPTY rather than left untouched. Post the whole GET /api/infra/export-data payload, not a hand-built subset.',
properties: {
sessions: { type: 'array' },
webhooks: { type: 'array' },
messages: { type: 'array' },
messageBatches: { type: 'array' },
+ templates: { type: 'array' },
+ baileysStoredMessages: { type: 'array' },
+ lidMappings: { type: 'array' },
+ pluginInstances: { type: 'array' },
+ conversationMappings: { type: 'array' },
+ ingressEvents: { type: 'array' },
+ webhookDeliveryFailures: { type: 'array' },
+ integrationDeliveryFailures: { type: 'array' },
statusUpdates: { type: 'array' },
+ automationRules: { type: 'array' },
},
},
},
@@ -502,7 +513,11 @@ export class InfraDataController {
* warnings: notices never cause a rollback, while warnings make the replace-rollback gate fire.
*/
notices: string[];
- /** True when live engines were left pointing at sessions this restore removed — restart to stop them. */
+ /**
+ * True when an engine may still be writing into the restored tables, from any of three causes:
+ * orphans deliberately left running (`force`), a `stopOrphans` teardown that failed, or sessions
+ * held by another node, which this request has no channel to stop. Restart to reconcile.
+ */
restartRequired: boolean;
/** Session ids with a running engine that the restored data no longer contains. */
orphanedEngines: string[];
@@ -849,8 +864,9 @@ export class InfraDataController {
// only the per-table counts.
await this.auditService?.logInfo(AuditAction.INFRA_DATA_IMPORTED, { metadata: { counts } });
- // restartRequired was computed in the pre-flight: true only when orphans were left running
- // (force=true legacy path) or when stopOrphans teardown failed for at least one engine.
+ // restartRequired was computed in the pre-flight, from three independent causes: orphans left
+ // running (force=true legacy path), a stopOrphans teardown that failed for at least one
+ // engine, and sessions held by another node, which this request cannot reach to stop.
return {
imported: true,
counts,
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
index 0970ee7c7..06c98ea7b 100644
--- a/src/modules/message/send-pacing.service.ts
+++ b/src/modules/message/send-pacing.service.ts
@@ -94,9 +94,12 @@ const MAX_REFUSAL_KEYS = 1000;
* already the durable record of every chat send — bulk included, which persists through the same
* `saveOutgoingMessage` — and it already carries the `(sessionId, createdAt)` index the count needs.
* So the cap survives restarts with no table and no migration. The trade is that it counts only what
- * writes a row. Three paths clear this check without ever adding to it: a status post
- * (status.service.ts), a Baileys product send (catalog.service.ts), and a message edit — which is
- * gated here via applySendingGate but only UPDATEs the existing row, never inserts. A session using
+ * writes a row. Three kinds of path clear this check without ever adding to it: a status post
+ * (status.service.ts), both Baileys catalog sends (catalog.service.ts `sendProduct` and
+ * `sendCatalog`), and a message edit — which is gated here via applySendingGate but only UPDATEs the
+ * existing row, never inserts. A bulk item the engine refuses is a fourth: bulk persists its row only
+ * after the send succeeds, so a failed item is checked against the cap but never counted into it,
+ * unlike a failed single send whose PENDING row is kept as FAILED. A session using
* them can exceed its stated allowance. Deliberate, and documented in .env.example and docs/06 so
* the number an operator reads is the number they get.
* The breaker, by contrast, is in memory on purpose: it describes live conditions, and a restart