Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(api): tiebreak paged lists on id for a total order

Yudhi Armyndharisf7520a28fe72
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 982912bf0..d52c68acb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -233,14 +233,16 @@ jobs:
DATABASE_NAME: openwa
# Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the
- # STORED body_ts tsvector) and the boot-migration advisory lock (two concurrent migrators on
- # one database). Both specs self-skip unless DATABASE_TYPE=postgres, so they are a no-op
- # in the default test job and only execute here against the postgres:16 service.
- - name: Postgres specs (FTS provider + boot-migration lock)
- # --runInBand: both specs issue DDL against the one shared service database, and jest's
+ # STORED body_ts tsvector), the boot-migration advisory lock (two concurrent migrators on one
+ # database), and that a paged message list has a total order (Postgres sorts a tie group
+ # differently between two statements, so an unstable order drops rows from a page walk). All
+ # three self-skip unless DATABASE_TYPE=postgres, so they are a no-op in the default test job
+ # and only execute here against the postgres:16 service.
+ - name: Postgres specs (FTS provider + boot-migration lock + list ordering)
+ # --runInBand: the specs issue DDL against the one shared service database, and jest's
# default file-parallelism races their catalog writes (pg_type duplicate-key). The lock
# spec's own two-migrator race is in-file (Promise.all) and unaffected by runInBand.
- run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts
+ run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts
env:
DATABASE_TYPE: postgres
DATABASE_HOST: localhost
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c840e5336..144e9c4c6 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -215,16 +215,17 @@ jobs:
DATABASE_NAME: openwa
# Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the
- # STORED body_ts tsvector) and the boot-migration advisory lock (two concurrent migrators on
- # one database). Both specs self-skip unless DATABASE_TYPE=postgres, so they are a no-op
- # in the default test job and only execute here against the postgres:16 service.
- - name: Postgres specs (FTS provider + boot-migration lock)
+ # STORED body_ts tsvector), the boot-migration advisory lock (two concurrent migrators on one
+ # database), and that a paged message list has a total order. All three self-skip unless
+ # DATABASE_TYPE=postgres, so they are a no-op in the default test job and only execute here
+ # against the postgres:16 service.
+ - name: Postgres specs (FTS provider + boot-migration lock + list ordering)
# --runInBand: same reason the CI job passes it — both specs issue DDL against the one
# shared service database, and jest's default file-parallelism races their catalog writes
# (the first v0.19.0 tag failed this step on `relation "messages" already exists` over a
# tree CI had passed minutes earlier). The lock spec's own two-migrator race is in-file
# (Promise.all) and unaffected by runInBand.
- run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts
+ run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts
env:
DATABASE_TYPE: postgres
DATABASE_HOST: localhost
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c7ab033fb..73e0c3b6c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Paged lists now tiebreak on `id`, so a walk returns every row exactly once. Neither `createdAt` nor
+ a search relevance score is unique, and on PostgreSQL two identical statements could sort one tie
+ group differently, silently repeating some rows and omitting others: a 5000-row message list lost
+ 23 rows per walk, and an ordinary search repeated a row by the third page. Affects the message,
+ session, webhook and webhook delivery-failure lists and `GET /search`. `offset` still addresses a
+ position by count, so a list taking concurrent writes can still shift under a walk.
+
- `PUT /sessions/{sessionId}/groups/{groupId}/description` no longer fails with a bare `500` on
whatsapp-web.js. `WAWebGroupModifyInfoJob.setGroupDescription` now takes a single options object
and the library still calls it positionally, so `widToGroupJid` threw inside the page. A new
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 22bede2aa..5460d95d0 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1239,7 +1239,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. 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 `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; page promptly and treat a repeated `id` as a duplicate. 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/common/release-gate-parity.spec.ts b/src/common/release-gate-parity.spec.ts
index 551719465..da344a446 100644
--- a/src/common/release-gate-parity.spec.ts
+++ b/src/common/release-gate-parity.spec.ts
@@ -36,7 +36,7 @@ const gateCommands = (file: string, job: string): string[] => {
};
describe('release gate parity (the tag path runs every branch gate)', () => {
- it.each(['lint', 'test'])('%s: every ci.yml gate command also runs in release.yml', job => {
+ it.each(['lint', 'test', 'test-postgres'])('%s: every ci.yml gate command also runs in release.yml', job => {
const ci = gateCommands('ci.yml', job);
const release = gateCommands('release.yml', job);
// Non-vacuity: both parsers must find real gate lanes, or the subset assertion below binds nothing.
@@ -49,5 +49,8 @@ describe('release gate parity (the tag path runs every branch gate)', () => {
it('the two gates this spec was born from still run on the tag path', () => {
expect(gateCommands('release.yml', 'lint')).toContain('npm run check:contract-shapes');
expect(gateCommands('release.yml', 'test')).toContain('npm run test:docs');
+ // The postgres lane names its specs inline, so a spec added to ci.yml alone would otherwise
+ // leave the tag path running a strictly weaker suite than the branch it was cut from.
+ expect(gateCommands('release.yml', 'test-postgres').join(' ')).toContain('message-list-ordering.pg.spec.ts');
});
});
diff --git a/src/modules/message/message-list-ordering.pg.spec.ts b/src/modules/message/message-list-ordering.pg.spec.ts
new file mode 100644
index 000000000..3409835e0
--- /dev/null
+++ b/src/modules/message/message-list-ordering.pg.spec.ts
@@ -0,0 +1,119 @@
+/* istanbul ignore file -- PG-gated: only runs under DATABASE_TYPE=postgres (test-postgres CI job);
+ skipped in the default test job, so its lines would be unread and skew the global coverage gate. */
+import 'reflect-metadata';
+import { randomUUID } from 'crypto';
+import { DataSource, Repository } from 'typeorm';
+import { MessageService } from './message.service';
+import { Message, MessageDirection } from './entities/message.entity';
+import type { EngineRegistry } from '../../engine/engine-registry.service';
+import type { MessageProjector } from '../session/message-projector.service';
+import type { HookManager } from '../../core/hooks';
+import type { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import type { SendPacingService } from './send-pacing.service';
+import type { MessageSendService } from './message-send.service';
+
+/**
+ * `createdAt` is not a unique sort key. On SQLite it is whole seconds; on Postgres `NOW()` is
+ * transaction-scoped, so one bulk write ties every row it inserts; and the history projector stamps
+ * the column from WhatsApp's own second-resolution timestamp on both. A chat therefore routinely
+ * holds many rows sharing one value.
+ *
+ * Postgres plans this list as a Sort over a bitmap heap scan, and that sort is not stable: two
+ * identical statements can return one tie group in two different orders. An offset pager walking
+ * such a table then repeats some rows and never returns others, with no error and no concurrent
+ * write required. Measured on postgres:16 before the tiebreaker existed: a single walk of 5000 tied
+ * rows returned 23 rows twice and 23 rows not at all, reproducibly.
+ *
+ * This suite runs only where the defect lives. SQLite reaches the same rows through an index scan
+ * and happens to be self-consistent, so an in-memory harness cannot fail on it.
+ *
+ * It pins ordering only. Offset paging over a table taking concurrent writes still drifts, because
+ * the window is anchored to a count rather than to a row; closing that needs a cursor.
+ */
+const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';
+
+(POSTGRES_ENABLED ? describe : describe.skip)('message list ordering over tied createdAt (postgres)', () => {
+ const SESSION_ID = 'sess-ordering';
+ const ROWS = 5000;
+ const PAGE = 100;
+
+ let ds: DataSource;
+ let repository: Repository<Message>;
+ let service: MessageService;
+
+ beforeAll(async () => {
+ ds = new DataSource({
+ type: 'postgres',
+ host: process.env.DATABASE_HOST || 'localhost',
+ port: Number(process.env.DATABASE_PORT || 5432),
+ username: process.env.DATABASE_USERNAME || 'openwa',
+ password: process.env.DATABASE_PASSWORD || 'openwa',
+ database: process.env.DATABASE_NAME || 'openwa',
+ entities: [Message],
+ });
+ await ds.initialize();
+
+ // Raw DDL rather than ORM synchronize, like the sibling PG specs: the production shape comes
+ // from the migration chain (varchar id, no uuid extension), and the index that decides this
+ // test, (sessionId, createdAt), has to be the one the deployed schema carries.
+ await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`);
+ await ds.query(
+ `CREATE TABLE "messages" (` +
+ `"id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, "waMessageId" varchar, ` +
+ `"chatId" varchar NOT NULL, "chatName" varchar, "author" varchar, "from" varchar NOT NULL, ` +
+ `"to" varchar NOT NULL, "body" text, "type" varchar NOT NULL DEFAULT 'text', ` +
+ `"direction" varchar NOT NULL DEFAULT 'outgoing', "timestamp" bigint, "metadata" text, ` +
+ `"mediaPath" varchar, "mediaMimetype" varchar, "status" varchar NOT NULL DEFAULT 'sent', ` +
+ `"createdAt" timestamp NOT NULL DEFAULT now())`,
+ );
+ await ds.query(`CREATE INDEX "IDX_sess_created" ON "messages" ("sessionId", "createdAt")`);
+ await ds.query(`CREATE INDEX "IDX_created" ON "messages" ("createdAt")`);
+ await ds.query(`CREATE INDEX "IDX_chat" ON "messages" ("chatId")`);
+ await ds.query(`CREATE INDEX "IDX_status" ON "messages" ("status")`);
+
+ repository = ds.getRepository(Message);
+
+ // getMessages without filters touches nothing but the repository; the rest are inert.
+ service = new MessageService(
+ repository,
+ {} as EngineRegistry,
+ {} as MessageProjector,
+ {} as HookManager,
+ { lidsForPhone: () => [], getCached: () => undefined } as unknown as LidMappingStoreService,
+ {} as SendPacingService,
+ {} as MessageSendService,
+ );
+
+ // One tie group, stamped the way message-history-projector.ts stamps a backfill.
+ await repository.insert(
+ Array.from({ length: ROWS }, (_, i) => ({
+ id: randomUUID(),
+ sessionId: SESSION_ID,
+ chatId: '[email protected]',
+ body: `m${i}`,
+ direction: MessageDirection.INCOMING,
+ createdAt: new Date('2026-01-01T00:00:00.000Z'),
+ })),
+ );
+ });
+
+ afterAll(async () => {
+ if (!ds?.isInitialized) return;
+ await ds.query(`DROP TABLE IF EXISTS "messages" CASCADE`).catch(() => undefined);
+ await ds.destroy();
+ });
+
+ it('serves every row exactly once across a full offset walk of one tie group', async () => {
+ const served: string[] = [];
+ for (let offset = 0; offset < ROWS; offset += PAGE) {
+ const { messages } = await service.getMessages(SESSION_ID, { limit: PAGE, offset });
+ served.push(...messages.map(m => m.id));
+ }
+
+ const distinct = new Set(served);
+ expect(served).toHaveLength(ROWS);
+ expect(distinct.size).toBe(ROWS); // no row repeated, and therefore none missed
+ });
+});
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index f1f5dc679..91d682f0b 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -144,6 +144,7 @@ describe('MessageService', () => {
interface QbMock {
where: jest.Mock;
orderBy: jest.Mock;
+ addOrderBy: jest.Mock;
skip: jest.Mock;
take: jest.Mock;
andWhere: jest.Mock;
@@ -153,6 +154,7 @@ describe('MessageService', () => {
const qb: QbMock = {
where: jest.fn(),
orderBy: jest.fn(),
+ addOrderBy: jest.fn(),
skip: jest.fn(),
take: jest.fn(),
andWhere: jest.fn(),
@@ -160,6 +162,7 @@ describe('MessageService', () => {
};
qb.where.mockReturnValue(qb);
qb.orderBy.mockReturnValue(qb);
+ qb.addOrderBy.mockReturnValue(qb);
qb.skip.mockReturnValue(qb);
qb.take.mockReturnValue(qb);
qb.andWhere.mockReturnValue(qb);
@@ -198,6 +201,7 @@ describe('MessageService', () => {
const qb = {
where: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
+ addOrderBy: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
andWhere: jest
@@ -273,6 +277,7 @@ describe('MessageService', () => {
const qb = {
where: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
+ addOrderBy: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
andWhere: jest
@@ -341,6 +346,7 @@ describe('MessageService', () => {
const qb = {
where: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
+ addOrderBy: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
andWhere: jest
@@ -429,6 +435,7 @@ describe('MessageService', () => {
const qb = {
where: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
+ addOrderBy: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockImplementation((_clause: string, params?: { chatIds?: string[] }) => {
@@ -884,6 +891,7 @@ describe('MessageService', () => {
where: jest.fn().mockReturnThis(),
andWhere: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
+ addOrderBy: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
take: jest.fn().mockReturnThis(),
getManyAndCount: jest.fn().mockResolvedValue([rows, 100]),
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 53df06252..16efb3661 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -236,6 +236,13 @@ export class MessageService implements PluginMessagePort {
.createQueryBuilder('message')
.where('message.sessionId = :sessionId', { sessionId })
.orderBy('message.createdAt', 'DESC')
+ // `createdAt` is not unique: SQLite stores whole seconds, Postgres NOW() is transaction-scoped
+ // 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')
.skip(offset)
.take(limit);
diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.ts
index 84659fddf..29d08b808 100644
--- a/src/modules/search/providers/builtin-fts.provider.ts
+++ b/src/modules/search/providers/builtin-fts.provider.ts
@@ -290,6 +290,13 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
// --- SQLite FTS5 -----------------------------------------------------------
// SQL appearance order: MATCH term -> filters -> LIMIT -> OFFSET. Params pushed in that order.
+ // Both dialects tiebreak on `m."id"`: neither `rank`/`score` nor the whole-second `timestamp` is
+ // unique (a one-word query can score every hit identically), and without a total order a paged
+ // walk repeats some hits and never returns others. Measured on Postgres, which sorts a tie group
+ // differently per LIMIT/OFFSET: an ordinary search repeated a row by the third page. SQLite was
+ // already self-consistent, but it keeps the term so the two dialects page alike; its plan is
+ // unchanged (the ORDER BY already needed a temp b-tree) and the extra column costs about a
+ // millisecond a page.
private buildSqlite(q: SearchQuery, limit: number, offset: number) {
const ph = BuiltInFtsProvider.sqlitePlaceholder;
const params: unknown[] = [];
@@ -297,7 +304,7 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
params.push(BuiltInFtsProvider.toFts5Query(q.q));
this.applyFilters(where, params, q, 'm.', ph);
const cols = `m."id", m."waMessageId" AS wa_message_id, m."sessionId" AS session_id, m."chatId" AS chat_id, m."from" AS "from", m."body", m."timestamp", m."type", m."direction", snippet(messages_fts, 0, '<mark>', '</mark>', '…', ${MAX_SNIPPET_WORDS}) AS snippet, rank AS score`;
- const sql = `SELECT ${cols} FROM messages_fts JOIN messages m ON m."rowid" = messages_fts."rowid" WHERE ${where.join(' AND ')} ORDER BY rank, m."timestamp" DESC LIMIT ${ph()} OFFSET ${ph()}`;
+ const sql = `SELECT ${cols} FROM messages_fts JOIN messages m ON m."rowid" = messages_fts."rowid" WHERE ${where.join(' AND ')} ORDER BY rank, m."timestamp" DESC, m."id" DESC LIMIT ${ph()} OFFSET ${ph()}`;
params.push(limit, offset);
return { sql, params };
}
@@ -317,7 +324,7 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
// StartSel/StopSel are pinned to <mark>/</mark> to match the SQLite FTS5 snippet() output, so the
// SearchHit.snippet contract stays dialect-agnostic (PG's ts_headline defaults to <b>/</b>).
const cols = `m."id", m."waMessageId" AS wa_message_id, m."sessionId" AS session_id, m."chatId" AS chat_id, m."from", m."body", m."timestamp", m."type", m."direction", ts_headline('simple', m."body", q.query, 'MaxFragments=1, MaxWords=${MAX_SNIPPET_WORDS}, StartSel=<mark>, StopSel=</mark>') AS snippet, ts_rank(m.body_ts, q.query) AS score`;
- const sql = `SELECT ${cols} FROM messages m, ${ftsTerm} WHERE ${where.join(' AND ')} ORDER BY score DESC, m."timestamp" DESC LIMIT ${ph()} OFFSET ${ph()}`;
+ const sql = `SELECT ${cols} FROM messages m, ${ftsTerm} WHERE ${where.join(' AND ')} ORDER BY score DESC, m."timestamp" DESC, m."id" DESC LIMIT ${ph()} OFFSET ${ph()}`;
params.push(limit, offset);
return { sql, params };
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 45388b6da..bdd36e410 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -735,7 +735,7 @@ describe('SessionService', () => {
const result = await service.findAll();
expect(result).toHaveLength(2);
- expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC', id: 'DESC' }, take: 1000, skip: 0 });
});
it('scopes results to a session-restricted key', async () => {
@@ -745,7 +745,7 @@ describe('SessionService', () => {
expect(repository.find).toHaveBeenCalledWith({
where: { id: In(['sess-1', 'sess-2']) },
- order: { createdAt: 'DESC' },
+ order: { createdAt: 'DESC', id: 'DESC' },
take: 1000,
skip: 0,
});
@@ -758,8 +758,16 @@ describe('SessionService', () => {
await service.findAll([]);
expect(repository.find).toHaveBeenCalledTimes(2);
- expect(repository.find).toHaveBeenNthCalledWith(1, { order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
- expect(repository.find).toHaveBeenNthCalledWith(2, { order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
+ expect(repository.find).toHaveBeenNthCalledWith(1, {
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
+ expect(repository.find).toHaveBeenNthCalledWith(2, {
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: 1000,
+ skip: 0,
+ });
});
it('applies bounded pagination to the database query', async () => {
@@ -769,7 +777,7 @@ describe('SessionService', () => {
expect(repository.find).toHaveBeenCalledWith({
where: { id: In(['sess-1']) },
- order: { createdAt: 'DESC' },
+ order: { createdAt: 'DESC', id: 'DESC' },
take: 1000,
skip: 0,
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 6bcca6423..c6800c2a4 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -316,7 +316,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// allowlist) lists all — mirroring the ApiKeyGuard allowedSessions model so a scoped key
// cannot enumerate every session through this aggregate route.
const { limit, offset } = resolveListWindow(opts.limit, opts.offset);
- const options: FindManyOptions<Session> = { order: { createdAt: 'DESC' }, take: limit, skip: offset };
+ // `id` tiebreaks the second-resolution `createdAt` so a paged walk has a total order.
+ const options: FindManyOptions<Session> = {
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: limit,
+ skip: offset,
+ };
if (allowedSessions && allowedSessions.length > 0) {
options.where = { id: In(allowedSessions) };
}
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index d0034f5ef..77d70390a 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -336,7 +336,7 @@ describe('WebhookService', () => {
await service.findAll();
- expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC' }, take: 1000, skip: 0 });
+ expect(repository.find).toHaveBeenCalledWith({ order: { createdAt: 'DESC', id: 'DESC' }, take: 1000, skip: 0 });
});
it('applies bounded pagination to cross-session listing', async () => {
@@ -346,7 +346,7 @@ describe('WebhookService', () => {
expect(repository.find).toHaveBeenCalledWith({
where: { sessionId: In(['sess-1']) },
- order: { createdAt: 'DESC' },
+ order: { createdAt: 'DESC', id: 'DESC' },
take: 1000,
skip: 0,
});
@@ -512,7 +512,7 @@ describe('WebhookService', () => {
// sessionId resolves through resolveSessionScope, so the WHERE is an IN over the effective scope
// ([s1] here for an unrestricted key narrowing to one session) — behaviourally the same rows.
expect(failureRepository.find).toHaveBeenCalledWith(
- expect.objectContaining({ where: { sessionId: In(['s1']) }, order: { createdAt: 'DESC' } }),
+ expect.objectContaining({ where: { sessionId: In(['s1']) }, order: { createdAt: 'DESC', id: 'DESC' } }),
);
});
});
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 320be5174..e9448d52a 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -171,7 +171,12 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
// A session-restricted key only sees its own sessions' webhooks; an unrestricted key
// (null/empty allowlist, e.g. ADMIN) sees all — mirroring the ApiKeyGuard allowedSessions model.
const { limit, offset } = resolveListWindow(opts.limit, opts.offset);
- const options: FindManyOptions<Webhook> = { order: { createdAt: 'DESC' }, take: limit, skip: offset };
+ // `id` tiebreaks the second-resolution `createdAt` so a paged walk has a total order.
+ const options: FindManyOptions<Webhook> = {
+ order: { createdAt: 'DESC', id: 'DESC' },
+ take: limit,
+ skip: offset,
+ };
if (allowedSessions && allowedSessions.length > 0) {
options.where = { sessionId: In(allowedSessions) };
}
@@ -195,7 +200,8 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
if (sessionScope !== null && sessionScope.length === 0) return []; // requested session outside the key's scope
return this.failureRepository.find({
where: sessionScope ? { sessionId: In(sessionScope) } : {},
- order: { createdAt: 'DESC' },
+ // A receiver outage writes a burst of failures inside one second; `id` keeps the page order total.
+ order: { createdAt: 'DESC', id: 'DESC' },
take: limit,
skip: offset,
});