Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(api): order same-second messages by arrival on SQLite
Yudhi Armyndharis8a412c74dbdf
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 10d4946d7..0887a316c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1241,7 +1241,7 @@ Get persisted message history for a session from the local DB (paginated, filter}```-Each `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from, to, body (string|null), type, direction ('incoming'|'outgoing'), timestamp (number|null), metadata (object|null), status ('pending'|'sent'|'delivered'|'read'|'failed'), createdAt (ISO date) }`. Ordered by `createdAt` DESC, then `id` DESC. The tiebreaker matters: `createdAt` is not unique (SQLite stores whole seconds, a PostgreSQL bulk write ties every row it inserts, and a history backfill carries WhatsApp's own second-resolution timestamp), and without a total order two pages of one walk can repeat a row and omit another. Note that `offset` still addresses a position by count, so a list taking concurrent writes can shift under a walk: a message arriving mid-walk pushes every older row down one, and the next page re-serves a row the previous one already returned. Pass `after` instead to walk a live chat safely; it anchors on the last row you received, which an arriving message cannot move. The response is the raw service object (no envelope). Unlike the live `IncomingMessage` shape below, this persisted `Message` does **not** carry `kind` — re-derive the chat kind from `chatId` (see `ChatKind` / `chatKind()`) if needed.+Each `Message`: `{ id (uuid), sessionId, waMessageId (string|null), chatId, from, to, body (string|null), type, direction ('incoming'|'outgoing'), timestamp (number|null), metadata (object|null), status ('pending'|'sent'|'delivered'|'read'|'failed'), createdAt (ISO date) }`. Ordered by `createdAt` DESC, then by a dialect-dependent second key. The tiebreaker matters: `createdAt` is not unique (SQLite stores whole seconds, a PostgreSQL bulk write ties every row it inserts, and a history backfill carries WhatsApp's own second-resolution timestamp), and without a total order two pages of one walk can repeat a row and omit another. On SQLite the second key is `rowid`, the stored insertion sequence, so messages sharing a second come back in the order they arrived. PostgreSQL has no equivalent (`ctid` moves on every ack update), so it keeps `id`, a random uuid: the walk is equally correct there, but a same-second group is not in arrival order. Note that `offset` still addresses a position by count, so a list taking concurrent writes can shift under a walk: a message arriving mid-walk pushes every older row down one, and the next page re-serves a row the previous one already returned. Pass `after` instead to walk a live chat safely; it anchors on the last row you received, which an arriving message cannot move. The response is the raw service object (no envelope). Unlike the live `IncomingMessage` shape below, this persisted `Message` does **not** carry `kind` — re-derive the chat kind from `chatId` (see `ChatKind` / `chatKind()`) if needed.> **Inline media is carried up to a budget, then omitted.** `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one response may hold across its rows. A row is not a bounded object — `limit` is clamped to `[1,100]` but each row can carry its base64 in `metadata.media.data`, so a page of media rows could otherwise reach hundreds of megabytes and fail the read outright. The budget is spent newest-first, matching the `createdAt` DESC order above, so a page that cannot carry everything keeps the most recent media. Past it a payload is replaced with `{ mimetype, filename?, omitted: true, sizeBytes }` — the same marker the engine emits for inbound media over `MEDIA_DOWNLOAD_MAX_BYTES` — and the bytes remain available from [`GET /messages/:chatId/:messageId/media`](#get-apisessionssessionidmessageschatidmessageidmedia). Two rules bound the edges: the newest payload is always inlined even when it alone exceeds the budget (otherwise a single large photo would be permanently unreadable through this route), and a budget of `0` means "never inline" and grants no such allowance. The knob is validated at boot — `8MiB` would parse to 8 bytes — and is forwarded by both compose files. The MCP `MessageList` tool shares this path and the same budget.diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 89e1f1d14..a089fa95b 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -216,7 +216,8 @@ describe('MessageService', () => {expect(qb.skip).not.toHaveBeenCalled();expect(qb.getManyAndCount).not.toHaveBeenCalled();const [clause, params] = qb.andWhere.mock.calls[0] as [string, Record<string, unknown>];- expect(clause).toContain('(message.createdAt, message.id) <');+ // rowid, not id: the stub repository carries no manager, which reads as "not postgres".+ expect(clause).toContain('(message.createdAt, message.rowid) <');// The anchor's sort key is resolved in SQL; only the id crosses the JS boundary.expect(clause).toContain('FROM messages anchor');expect(params).toEqual({ after: 'm-1', sessionId: 'sess-1' });@@ -224,6 +225,39 @@ describe('MessageService', () => {expect(result.total).toBe(7);});+ /**+ * The dialect split, pinned on the default test job rather than only in the postgres-gated+ * suite: a typo in the accessor would otherwise ship a `rowid` term to PostgreSQL, where the+ * column does not exist and every message list would 500.+ */+ it('keeps id as the tiebreak on postgres, where there is no rowid', async () => {+ const qb = makeCursorQb([{ id: 'm-2' } as Message]);+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);+ (repository as unknown as { manager: unknown }).manager = {+ connection: { options: { type: 'postgres' } },+ };++ await service.getMessages('sess-1', { after: 'm-1' });++ const [clause] = qb.andWhere.mock.calls[0] as [string];+ expect(clause).toContain('(message.createdAt, message.id) <');+ expect(clause).toContain('anchor."id"');+ expect(clause).not.toContain('rowid');+ expect(qb.addOrderBy).toHaveBeenCalledWith('message.id', 'DESC');++ delete (repository as unknown as { manager?: unknown }).manager;+ });++ it('orders by rowid on sqlite, which is the arrival order and needs no sort', async () => {+ const qb = makeCursorQb([{ id: 'm-2' } as Message]);+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);++ await service.getMessages('sess-1', { after: 'm-1' });++ // The order term is applied before the cursor branch, so the cursor harness pins it too.+ expect(qb.addOrderBy).toHaveBeenCalledWith('message.rowid', 'DESC');+ });+it('rejects a cursor that names no row in this session rather than reading as end-of-history', async () => {const qb = makeCursorQb([]);(repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 2922c52c1..9ade97427 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -147,6 +147,29 @@ export class MessageService implements PluginMessagePort {private readonly storageService?: StorageService,) {}+ /**+ * Second sort key for the message list: what makes the page order TOTAL without scrambling the+ * order the messages actually arrived in.+ *+ * A tiebreaker is required, because `createdAt` is not unique. But `id` is a random v4 uuid, so+ * it orders a tie group at random: five same-second messages came back shuffled, and the+ * dashboard renders whatever the server sends. It is also in no index, so SQLite sorted the whole+ * result into a temp b-tree to apply it.+ *+ * SQLite already stores the insertion sequence as `rowid`, the implicit trailing column of every+ * index, so `(createdAt DESC, rowid DESC)` is a plain backward scan of `(sessionId, createdAt)`:+ * arrival order restored, and the temp b-tree gone with it. Measured on the pinned better-sqlite3+ * with the shipped index set.+ *+ * PostgreSQL has no equivalent. `ctid` is physical position and moves on every ack UPDATE, so it+ * cannot order anything, and a monotonic column would need a table rewrite on the hottest table+ * with no recoverable insertion order to backfill from. It keeps `id`: the walk stays correct,+ * and a same-second group keeps its uuid order there.+ */+ private get orderTiebreak(): 'rowid' | 'id' {+ return this.messageRepository.manager?.connection?.options?.type === 'postgres' ? 'id' : 'rowid';+ }+// ========== Outbound sends (delegated) ==========//// The send family lives on MessageSendService; these pass-throughs keep the MessageService@@ -244,6 +267,8 @@ export class MessageService implements PluginMessagePort {typeof rawLimit === 'number' && Number.isFinite(rawLimit) ? Math.min(Math.max(Math.trunc(rawLimit), 1), 100) : 50;const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) ? Math.max(Math.trunc(rawOffset), 0) : 0;+ const tiebreak = this.orderTiebreak;+const query = this.messageRepository.createQueryBuilder('message').where('message.sessionId = :sessionId', { sessionId })@@ -252,9 +277,8 @@ export class MessageService implements PluginMessagePort {// so a bulk write ties every row, and a history backfill stamps WhatsApp's own second-resolution// timestamp. Without a tiebreaker the tie group's order is whatever the plan produces, and// Postgres sorts it differently between two statements, so a page walk repeats some rows and- // never returns others. `id` is random, not chronological, but it is unique and stable, which- // is all a total order needs.- .addOrderBy('message.id', 'DESC')+ // never returns others. See `orderTiebreak` for why the key differs by dialect.+ .addOrderBy(`message.${tiebreak}`, 'DESC').take(limit);// `after` replaces the offset rather than adding to it: mixing a row anchor with a count is@@ -302,8 +326,8 @@ export class MessageService implements PluginMessagePort {// microseconds to a millisecond Date. Both mis-seek silently, which is the very failure this// cursor exists to remove.query.andWhere(- '(message.createdAt, message.id) < ' +- '(SELECT anchor."createdAt", anchor."id" FROM messages anchor ' ++ `(message.createdAt, message.${tiebreak}) < ` ++ `(SELECT anchor."createdAt", anchor."${tiebreak}" FROM messages anchor ` +'WHERE anchor."id" = :after AND anchor."sessionId" = :sessionId)',{ after, sessionId },);