Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🐇 refactor: Decouple Meilisearch From Document Saves (#15109)

Danny Avila10f95c0ce975
diff --git a/api/db/indexSync.js b/api/db/indexSync.js
index 54b2861723..85a5524a76 100644
--- a/api/db/indexSync.js
+++ b/api/db/indexSync.js
@@ -243,10 +243,16 @@ async function performSync(flowManager, flowId, flowType) {
const messageCount = messageProgress.totalDocuments;
const messagesIndexed = messageProgress.totalProcessed;
const unindexedMessages = messageCount - messagesIndexed;
+ const messagesPendingIndexing = messageProgress.pendingIndexing ?? 0;
const messagesPendingCleanup = messageProgress.pendingCleanup ?? 0;
const noneIndexed = messagesIndexed === 0 && unindexedMessages > 0;
- if (settingsUpdated || noneIndexed || unindexedMessages > syncThreshold) {
+ if (
+ settingsUpdated ||
+ noneIndexed ||
+ messagesPendingIndexing > 0 ||
+ unindexedMessages > syncThreshold
+ ) {
if (noneIndexed && !settingsUpdated) {
logger.info('[indexSync] No messages marked as indexed, forcing full sync');
}
@@ -291,10 +297,16 @@ async function performSync(flowManager, flowId, flowType) {
const convoCount = convoProgress.totalDocuments;
const convosIndexed = convoProgress.totalProcessed;
const unindexedConvos = convoCount - convosIndexed;
+ const convosPendingIndexing = convoProgress.pendingIndexing ?? 0;
const convosPendingCleanup = convoProgress.pendingCleanup ?? 0;
const noneConvosIndexed = convosIndexed === 0 && unindexedConvos > 0;
- if (settingsUpdated || noneConvosIndexed || unindexedConvos > syncThreshold) {
+ if (
+ settingsUpdated ||
+ noneConvosIndexed ||
+ convosPendingIndexing > 0 ||
+ unindexedConvos > syncThreshold
+ ) {
if (noneConvosIndexed && !settingsUpdated) {
logger.info('[indexSync] No conversations marked as indexed, forcing full sync');
}
diff --git a/api/db/indexSync.spec.js b/api/db/indexSync.spec.js
index a1a23db64d..c76091d52d 100644
--- a/api/db/indexSync.spec.js
+++ b/api/db/indexSync.spec.js
@@ -195,6 +195,33 @@ describe('performSync() - syncThreshold logic', () => {
expect(Conversation.syncWithMeili).not.toHaveBeenCalled();
});
+ test('reconciles attempted indexing failures below syncThreshold', async () => {
+ Message.getSyncProgress.mockResolvedValue({
+ totalProcessed: 100,
+ totalDocuments: 101,
+ pendingIndexing: 1,
+ isComplete: false,
+ });
+ Conversation.getSyncProgress.mockResolvedValue({
+ totalProcessed: 50,
+ totalDocuments: 51,
+ pendingIndexing: 1,
+ isComplete: false,
+ });
+ Message.syncWithMeili.mockResolvedValue(undefined);
+ Conversation.syncWithMeili.mockResolvedValue(undefined);
+
+ process.env.MEILI_SYNC_THRESHOLD = '1000';
+
+ const indexSync = require('./indexSync');
+ await indexSync();
+
+ expect(Message.syncWithMeili).toHaveBeenCalledTimes(1);
+ expect(Conversation.syncWithMeili).toHaveBeenCalledTimes(1);
+ expect(mockLogger.info).toHaveBeenCalledWith('[indexSync] Starting message sync (1 unindexed)');
+ expect(mockLogger.info).toHaveBeenCalledWith('[indexSync] Starting convos sync (1 unindexed)');
+ });
+
test('respects syncThreshold at boundary (exactly at threshold)', async () => {
// Arrange: 1000 unindexed messages = 1000 threshold (NOT greater than)
Message.getSyncProgress.mockResolvedValue({
diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts b/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts
index 4b9b38ca03..b49b5620c5 100644
--- a/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts
+++ b/packages/data-schemas/src/models/plugins/mongoMeili.findOneAndUpdate.spec.ts
@@ -35,6 +35,7 @@ const waitForMock = async (mock: jest.Mock, timeoutMs = 2000): Promise<void> =>
const mockAddDocuments = jest.fn();
const mockUpdateDocuments = jest.fn();
const mockDeleteDocument = jest.fn();
+const mockWaitForTask = jest.fn();
const mockGetDocument = jest.fn();
const mockIndex = jest.fn().mockReturnValue({
getRawInfo: jest.fn(),
@@ -48,7 +49,10 @@ const mockIndex = jest.fn().mockReturnValue({
getDocuments: jest.fn().mockReturnValue({ results: [] }),
});
jest.mock('meilisearch', () => ({
- MeiliSearch: jest.fn().mockImplementation(() => ({ index: mockIndex })),
+ MeiliSearch: jest.fn().mockImplementation(() => ({
+ index: mockIndex,
+ waitForTask: mockWaitForTask,
+ })),
}));
describe('mongoMeili findOneAndUpdate with includeResultMetadata (saveConvo path)', () => {
@@ -84,9 +88,10 @@ describe('mongoMeili findOneAndUpdate with includeResultMetadata (saveConvo path
beforeEach(async () => {
await conversationModel.deleteMany({});
- mockAddDocuments.mockClear();
- mockUpdateDocuments.mockClear();
- mockDeleteDocument.mockClear();
+ mockAddDocuments.mockReset().mockResolvedValue({ taskUid: 1 });
+ mockUpdateDocuments.mockReset().mockResolvedValue({ taskUid: 1 });
+ mockDeleteDocument.mockReset().mockResolvedValue({ taskUid: 1 });
+ mockWaitForTask.mockReset().mockResolvedValue({ status: 'succeeded' });
mockGetDocument.mockClear();
mockGetDocument.mockReset();
});
@@ -98,6 +103,20 @@ describe('mongoMeili findOneAndUpdate with includeResultMetadata (saveConvo path
{ new: true, upsert: true, includeResultMetadata: true },
);
+ const waitForIndexAcknowledgment = async (
+ conversationId: string,
+ timeoutMs = 2000,
+ ): Promise<void> => {
+ const start = Date.now();
+ while (Date.now() - start <= timeoutMs) {
+ const storedDoc = await conversationModel.collection.findOne({ conversationId });
+ if (storedDoc?._meiliIndex === true) {
+ return;
+ }
+ await wait(10);
+ }
+ };
+
test('re-indexes the updated title when the raw result wrapper is returned', async () => {
const conversationId = new mongoose.Types.ObjectId().toString();
const user = new mongoose.Types.ObjectId().toString();
@@ -107,6 +126,7 @@ describe('mongoMeili findOneAndUpdate with includeResultMetadata (saveConvo path
title: 'Original Title',
endpoint: EModelEndpoint.openAI,
});
+ await waitForIndexAcknowledgment(conversationId);
mockAddDocuments.mockClear();
const result = await updateTitle(conversationId, user, 'Renamed Title');
@@ -150,26 +170,92 @@ describe('mongoMeili findOneAndUpdate with includeResultMetadata (saveConvo path
expect(storedDoc?._meiliIndex).toBe(true);
});
- test('skips re-indexing when the title already matches the MeiliSearch document', async () => {
+ test('does not wait for Meilisearch writes before settling the MongoDB update', async () => {
const conversationId = new mongoose.Types.ObjectId().toString();
const user = new mongoose.Types.ObjectId().toString();
+ let resolveMeiliWrite: ((result: { taskUid: number }) => void) | undefined;
+
await conversationModel.create({
conversationId,
user,
- title: 'Same Title',
+ title: 'Original Title',
endpoint: EModelEndpoint.openAI,
});
+ await waitForMock(mockAddDocuments);
+ await waitForIndexAcknowledgment(conversationId);
mockAddDocuments.mockClear();
- mockGetDocument.mockResolvedValueOnce({ conversationId, title: 'Same Title' });
+ mockAddDocuments.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveMeiliWrite = resolve;
+ }),
+ );
+
+ const result = await updateTitle(conversationId, user, 'Renamed Title');
+ expect((result as unknown as { value: unknown }).value).toBeTruthy();
+ await waitForMock(mockAddDocuments);
+ expect(resolveMeiliWrite).toBeDefined();
+ expect(mockAddDocuments).toHaveBeenCalledTimes(1);
+ expect((await conversationModel.collection.findOne({ conversationId }))?._meiliIndex).toBe(
+ false,
+ );
+
+ resolveMeiliWrite!({ taskUid: 1 });
+ await waitForIndexAcknowledgment(conversationId);
+ expect(mockAddDocuments).toHaveBeenCalledTimes(1);
+ });
+
+ test('re-indexes even when the title matches so every changed field stays current', async () => {
+ const conversationId = new mongoose.Types.ObjectId().toString();
+ const user = new mongoose.Types.ObjectId().toString();
+ await conversationModel.create({
+ conversationId,
+ user,
+ title: 'Same Title',
+ endpoint: EModelEndpoint.openAI,
+ });
+ await waitForIndexAcknowledgment(conversationId);
+ mockAddDocuments.mockClear();
await updateTitle(conversationId, user, 'Same Title');
- await wait(50);
- expect(mockGetDocument).toHaveBeenCalledWith(conversationId);
- expect(mockAddDocuments).not.toHaveBeenCalled();
+ await waitForMock(mockAddDocuments);
+ expect(mockGetDocument).not.toHaveBeenCalled();
+ expect(mockAddDocuments).toHaveBeenCalledWith(
+ [expect.objectContaining({ conversationId, title: 'Same Title' })],
+ { primaryKey: 'conversationId' },
+ );
expect(mockUpdateDocuments).not.toHaveBeenCalled();
});
+ test('persists the pending marker in the original findOneAndUpdate write', async () => {
+ const conversationId = new mongoose.Types.ObjectId().toString();
+ const user = new mongoose.Types.ObjectId().toString();
+ let resolveMeiliWrite: ((result: { taskUid: number }) => void) | undefined;
+ const modelUpdateOne = jest
+ .spyOn(conversationModel, 'updateOne')
+ .mockRejectedValue(new Error('follow-up marker writes must not be required'));
+ mockAddDocuments.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveMeiliWrite = resolve;
+ }),
+ );
+
+ await expect(updateTitle(conversationId, user, 'Atomic Pending Marker')).resolves.toBeTruthy();
+
+ const storedDoc = await conversationModel.collection.findOne({ conversationId });
+ expect(storedDoc?._meiliIndex).toBe(false);
+ expect(storedDoc?._meiliIndexAttempted).toBe(true);
+ expect(storedDoc?._meiliIndexVersion).toEqual(expect.any(String));
+ expect(modelUpdateOne).not.toHaveBeenCalled();
+
+ await waitForMock(mockAddDocuments);
+ resolveMeiliWrite!({ taskUid: 1 });
+ await waitForIndexAcknowledgment(conversationId);
+ modelUpdateOne.mockRestore();
+ });
+
test('does NOT index temporary conversations updated via the raw result wrapper', async () => {
const conversationId = new mongoose.Types.ObjectId().toString();
const user = new mongoose.Types.ObjectId().toString();
diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts b/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts
index 302e92876f..ba4520874d 100644
--- a/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts
+++ b/packages/data-schemas/src/models/plugins/mongoMeili.spec.ts
@@ -55,6 +55,24 @@ const createDynamicMeiliModel = (modelName: string): DynamicMeiliModel => {
const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+const waitForMock = async (mock: jest.Mock, timeoutMs = 2000): Promise<void> => {
+ const start = Date.now();
+ while (mock.mock.calls.length === 0 && Date.now() - start <= timeoutMs) {
+ await wait(10);
+ }
+};
+
+const waitForMockCalls = async (
+ mock: jest.Mock,
+ callCount: number,
+ timeoutMs = 2000,
+): Promise<void> => {
+ const start = Date.now();
+ while (mock.mock.calls.length < callCount && Date.now() - start <= timeoutMs) {
+ await wait(10);
+ }
+};
+
const mockAddDocuments = jest.fn();
const mockAddDocumentsInBatches = jest.fn();
const mockUpdateDocuments = jest.fn();
@@ -104,9 +122,9 @@ describe('Meilisearch Mongoose plugin', () => {
});
beforeEach(() => {
- mockAddDocuments.mockClear();
+ mockAddDocuments.mockReset().mockResolvedValue({ taskUid: 1 });
mockAddDocumentsInBatches.mockClear();
- mockUpdateDocuments.mockClear();
+ mockUpdateDocuments.mockReset().mockResolvedValue({ taskUid: 1 });
mockDeleteDocument.mockReset().mockResolvedValue({ taskUid: 2 });
mockDeleteDocuments.mockReset().mockResolvedValue({ taskUid: 1 });
mockGetDocument.mockClear();
@@ -144,6 +162,7 @@ describe('Meilisearch Mongoose plugin', () => {
title: 'Test Conversation',
endpoint: EModelEndpoint.openAI,
});
+ await waitForMock(mockAddDocuments);
expect(mockAddDocuments).toHaveBeenCalledWith(
[expect.objectContaining({ conversationId: expect.anything() })],
{ primaryKey: 'conversationId' },
@@ -158,6 +177,7 @@ describe('Meilisearch Mongoose plugin', () => {
endpoint: EModelEndpoint.openAI,
expiredAt: null,
});
+ await waitForMock(mockAddDocuments);
expect(mockAddDocuments).toHaveBeenCalled();
});
@@ -170,6 +190,7 @@ describe('Meilisearch Mongoose plugin', () => {
isTemporary: false,
expiredAt: new Date(Date.now() + 60 * 60 * 1000),
});
+ await waitForMock(mockAddDocuments);
expect(mockAddDocuments).toHaveBeenCalled();
});
@@ -319,6 +340,7 @@ describe('Meilisearch Mongoose plugin', () => {
user: new mongoose.Types.ObjectId(),
isCreatedByUser: true,
});
+ await waitForMock(mockAddDocuments);
expect(mockAddDocuments).toHaveBeenCalledWith(
[expect.objectContaining({ messageId: expect.anything() })],
{ primaryKey: 'messageId' },
@@ -333,6 +355,7 @@ describe('Meilisearch Mongoose plugin', () => {
isCreatedByUser: true,
expiredAt: null,
});
+ await waitForMock(mockAddDocuments);
expect(mockAddDocuments).toHaveBeenCalled();
});
@@ -345,6 +368,7 @@ describe('Meilisearch Mongoose plugin', () => {
isTemporary: false,
expiredAt: new Date(Date.now() + 60 * 60 * 1000),
});
+ await waitForMock(mockAddDocuments);
expect(mockAddDocuments).toHaveBeenCalled();
});
@@ -388,6 +412,7 @@ describe('Meilisearch Mongoose plugin', () => {
convo.title = 'Updated Title';
await convo.save();
+ await waitForMock(mockUpdateDocuments);
expect(mockUpdateDocuments).toHaveBeenCalledWith(
[expect.objectContaining({ conversationId: expect.anything() })],
{ primaryKey: 'conversationId' },
@@ -408,6 +433,7 @@ describe('Meilisearch Mongoose plugin', () => {
msg.text = 'Updated text';
await msg.save();
+ await waitForMock(mockUpdateDocuments);
expect(mockUpdateDocuments).toHaveBeenCalledWith(
[expect.objectContaining({ messageId: expect.anything() })],
{ primaryKey: 'messageId' },
@@ -451,6 +477,7 @@ describe('Meilisearch Mongoose plugin', () => {
convo.title = 'Updated Pipe Test';
await convo.save();
+ await waitForMock(mockUpdateDocuments);
expect(mockUpdateDocuments).toHaveBeenCalledWith(
[expect.objectContaining({ conversationId: 'abc--def--ghi' })],
{ primaryKey: 'conversationId' },
@@ -576,7 +603,7 @@ describe('Meilisearch Mongoose plugin', () => {
expect(storedDoc?._meiliIndex).toBe(true);
});
- test('does not clear an indexed marker until an update-hook deletion succeeds', async () => {
+ test('retries update-hook deletion before clearing an indexed marker', async () => {
const conversationModel = createConversationModel(
mongoose,
) as unknown as SchemaWithMeiliMethods;
@@ -589,11 +616,24 @@ describe('Meilisearch Mongoose plugin', () => {
title: 'Initially searchable conversation',
endpoint: EModelEndpoint.agents,
});
+ await waitForMock(mockAddDocuments);
+ let indexed = false;
+ const acknowledgmentStart = Date.now();
+ while (!indexed && Date.now() - acknowledgmentStart <= 2000) {
+ indexed =
+ (
+ await conversationModel
+ .findOne({ conversationId })
+ .select('+_meiliIndex +_meiliIndexAttempted')
+ )?._meiliIndex === true;
+ await wait(10);
+ }
const conversation = await conversationModel
.findOne({ conversationId })
.select('+_meiliIndex +_meiliIndexAttempted');
expect(conversation?._meiliIndex).toBe(true);
expect(conversation?._meiliIndexAttempted).toBe(true);
+ mockWaitForTask.mockClear();
conversation!.subagentThread = {
rootConversationId: 'root-conversation',
@@ -606,13 +646,8 @@ describe('Meilisearch Mongoose plugin', () => {
};
mockWaitForTask.mockResolvedValueOnce({ status: 'failed' });
await conversation!.save();
- expect((await conversationModel.collection.findOne({ conversationId }))?._meiliIndex).toBe(
- true,
- );
-
- conversation!.title = 'Retry deletion';
- mockWaitForTask.mockResolvedValueOnce({ status: 'succeeded' });
- await conversation!.save();
+ await waitForMockCalls(mockWaitForTask, 2);
+ await wait(25);
const storedDoc = await conversationModel.collection.findOne({ conversationId });
expect(mockDeleteDocument).toHaveBeenCalledTimes(2);
@@ -1142,30 +1177,127 @@ describe('Meilisearch Mongoose plugin', () => {
});
});
- test('addObjectToMeili retries on failure', async () => {
+ test('a transient document-write failure retries without delaying MongoDB persistence', async () => {
+ const conversationModel = createConversationModel(
+ mongoose,
+ ) as unknown as SchemaWithMeiliMethods;
+ let rejectMeiliWrite: ((reason?: Error) => void) | undefined;
+ await conversationModel.deleteMany({});
+
+ mockAddDocuments.mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ rejectMeiliWrite = reject;
+ }),
+ );
+
+ const conversation = await conversationModel.create({
+ conversationId: new mongoose.Types.ObjectId(),
+ user: new mongoose.Types.ObjectId(),
+ title: 'Detached Write',
+ endpoint: EModelEndpoint.openAI,
+ });
+
+ await waitForMock(mockAddDocuments);
+ expect(rejectMeiliWrite).toBeDefined();
+ expect(mockAddDocuments).toHaveBeenCalledTimes(1);
+
+ rejectMeiliWrite!(new Error('Network error'));
+ await waitForMockCalls(mockAddDocuments, 2);
+ await wait(25);
+
+ const storedConversation = await conversationModel.collection.findOne({
+ _id: conversation._id,
+ });
+ expect(mockAddDocuments).toHaveBeenCalledTimes(2);
+ expect(storedConversation?._meiliIndex).toBe(true);
+ expect(storedConversation?._meiliIndexAttempted).toBe(true);
+ expect(await conversationModel.getSyncProgress()).toMatchObject({ pendingIndexing: 0 });
+ });
+
+ test('a persistently failed document update stays marked for reconciliation', async () => {
const conversationModel = createConversationModel(
mongoose,
) as unknown as SchemaWithMeiliMethods;
+ await conversationModel.deleteMany({});
- // Mock addDocuments to fail twice then succeed
- mockAddDocuments
+ const conversation = await conversationModel.create({
+ conversationId: new mongoose.Types.ObjectId(),
+ user: new mongoose.Types.ObjectId(),
+ title: 'Indexed Conversation',
+ endpoint: EModelEndpoint.openAI,
+ });
+ await waitForMock(mockAddDocuments);
+ await wait(25);
+ mockUpdateDocuments
.mockRejectedValueOnce(new Error('Network error'))
.mockRejectedValueOnce(new Error('Network error'))
- .mockResolvedValueOnce({});
+ .mockRejectedValueOnce(new Error('Network error'));
- // Create a document which triggers addObjectToMeili
- await conversationModel.create({
+ conversation._meiliIndex = true;
+ conversation.title = 'Updated Conversation';
+ await conversation.save();
+
+ expect(
+ (await conversationModel.collection.findOne({ _id: conversation._id }))?._meiliIndex,
+ ).toBe(false);
+ await waitForMockCalls(mockUpdateDocuments, 3);
+ await wait(25);
+
+ const storedConversation = await conversationModel.collection.findOne({
+ _id: conversation._id,
+ });
+ expect(mockUpdateDocuments).toHaveBeenCalledTimes(3);
+ expect(storedConversation?._meiliIndex).toBe(false);
+ expect(storedConversation?._meiliIndexAttempted).toBe(true);
+ });
+
+ test('a stale replica write is followed by the latest MongoDB snapshot', async () => {
+ const conversationModel = createConversationModel(
+ mongoose,
+ ) as unknown as SchemaWithMeiliMethods;
+ let resolveStaleWrite: ((result: { taskUid: number }) => void) | undefined;
+ await conversationModel.deleteMany({});
+ mockAddDocuments.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveStaleWrite = resolve;
+ }),
+ );
+
+ const conversation = await conversationModel.create({
conversationId: new mongoose.Types.ObjectId(),
user: new mongoose.Types.ObjectId(),
- title: 'Test Retry',
+ title: 'Stale Replica Snapshot',
endpoint: EModelEndpoint.openAI,
});
+ await waitForMock(mockAddDocuments);
- // Wait for async operations to complete
- await new Promise((resolve) => setTimeout(resolve, 100));
+ const latestVersion = new mongoose.Types.ObjectId().toString();
+ await conversationModel.collection.updateOne(
+ { _id: conversation._id },
+ {
+ $set: {
+ title: 'Latest Replica Snapshot',
+ _meiliIndex: true,
+ _meiliIndexAttempted: true,
+ _meiliIndexVersion: latestVersion,
+ },
+ },
+ );
+
+ resolveStaleWrite!({ taskUid: 1 });
+ await waitForMockCalls(mockAddDocuments, 2);
+ await wait(25);
- // Verify addDocuments was called multiple times due to retries
- expect(mockAddDocuments).toHaveBeenCalledTimes(3);
+ expect(mockAddDocuments.mock.calls[1]).toEqual([
+ [expect.objectContaining({ title: 'Latest Replica Snapshot' })],
+ { primaryKey: 'conversationId' },
+ ]);
+ expect(await conversationModel.collection.findOne({ _id: conversation._id })).toMatchObject({
+ _meiliIndex: true,
+ _meiliIndexVersion: latestVersion,
+ });
});
test('getSyncProgress returns accurate progress information', async () => {
diff --git a/packages/data-schemas/src/models/plugins/mongoMeili.ts b/packages/data-schemas/src/models/plugins/mongoMeili.ts
index c04f0ddfc6..f1c8ce9c19 100644
--- a/packages/data-schemas/src/models/plugins/mongoMeili.ts
+++ b/packages/data-schemas/src/models/plugins/mongoMeili.ts
@@ -31,6 +31,7 @@ interface MeiliIndexable {
[key: string]: unknown;
_meiliIndex?: boolean;
_meiliIndexAttempted?: boolean;
+ _meiliIndexVersion?: string;
_meiliCleanupVersion?: number;
}
@@ -38,6 +39,7 @@ interface SyncProgress {
lastSyncedId?: string;
totalProcessed: number;
totalDocuments: number;
+ pendingIndexing: number;
pendingCleanup: number;
isComplete: boolean;
}
@@ -45,6 +47,7 @@ interface SyncProgress {
interface _DocumentWithMeiliIndex extends Document {
_meiliIndex?: boolean;
_meiliIndexAttempted?: boolean;
+ _meiliIndexVersion?: string;
_meiliCleanupVersion?: number;
isTemporary?: boolean;
expiredAt?: Date | null;
@@ -52,9 +55,9 @@ interface _DocumentWithMeiliIndex extends Document {
addObjectToMeili?: (next: CallbackWithoutResultAndOptionalError) => Promise<void>;
updateObjectToMeili?: (next: CallbackWithoutResultAndOptionalError) => Promise<void>;
deleteObjectFromMeili?: (next: CallbackWithoutResultAndOptionalError) => Promise<void>;
- postSaveHook?: (next: CallbackWithoutResultAndOptionalError) => void;
- postUpdateHook?: (next: CallbackWithoutResultAndOptionalError) => void;
- postRemoveHook?: (next: CallbackWithoutResultAndOptionalError) => void;
+ postSaveHook?: (next: CallbackWithoutResultAndOptionalError) => Promise<void>;
+ postUpdateHook?: (next: CallbackWithoutResultAndOptionalError) => Promise<void> | void;
+ postRemoveHook?: (next: CallbackWithoutResultAndOptionalError) => Promise<void> | void;
}
export type DocumentWithMeiliIndex = _DocumentWithMeiliIndex & IConversation & Partial<IMessage>;
@@ -105,7 +108,53 @@ const hasSchemaPath = (schema: Schema, path: string): boolean =>
Object.prototype.hasOwnProperty.call(schema.obj, path);
const explicitTemporaryFlagKey = 'meiliExplicitTemporaryFlag';
+const previouslyIndexedFlagKey = 'meiliPreviouslyIndexed';
const meiliCleanupVersion = 1;
+const meiliRequestTimeoutMs = 10_000;
+const meiliWriteMaxAttempts = 3;
+const meiliRetryBaseDelayMs = 250;
+const meiliVersionReconcileMaxAttempts = 3;
+const completeDetachedOperation: CallbackWithoutResultAndOptionalError = () => undefined;
+
+const retryDetachedMeiliWrite = async (
+ operation: () => Promise<unknown>,
+ context: string,
+): Promise<void> => {
+ let lastError: unknown;
+ for (let attempt = 0; attempt < meiliWriteMaxAttempts; attempt++) {
+ try {
+ await operation();
+ return;
+ } catch (error) {
+ lastError = error;
+ if (attempt + 1 < meiliWriteMaxAttempts) {
+ logger.warn(`${context} Retrying detached Meili write`, error);
+ await new Promise((resolve) =>
+ setTimeout(resolve, meiliRetryBaseDelayMs * Math.pow(2, attempt)),
+ );
+ }
+ }
+ }
+ throw lastError;
+};
+
+const createDetachedMeiliRunner = () => {
+ const pendingOperations = new Map<string, Promise<void>>();
+
+ return (key: string, operation: () => Promise<void> | void, context: string): void => {
+ const previousOperation = pendingOperations.get(key) ?? Promise.resolve();
+ const operationPromise = previousOperation.then(operation).catch((error) => {
+ logger.error(context, error);
+ });
+ const trackedOperation = operationPromise.finally(() => {
+ if (pendingOperations.get(key) === trackedOperation) {
+ pendingOperations.delete(key);
+ }
+ });
+
+ pendingOperations.set(key, trackedOperation);
+ };
+};
const buildRetentionIndexableQuery = (schema: Schema): FilterQuery<unknown> => {
if (hasSchemaPath(schema, 'isTemporary')) {
@@ -246,6 +295,116 @@ const createMeiliMongooseModel = ({
}) => {
const syncConfig = { ...getSyncConfig(), ...syncOptions };
+ const loadLatestDocument = async (
+ doc: DocumentWithMeiliIndex,
+ ): Promise<DocumentWithMeiliIndex | null> => {
+ const model = doc.constructor as Model<DocumentWithMeiliIndex>;
+ const selection = [
+ ...attributesToIndex,
+ '+_meiliIndex',
+ '+_meiliIndexAttempted',
+ '+_meiliIndexVersion',
+ 'isTemporary',
+ 'expiredAt',
+ 'unfinished',
+ ...(excludeFromIndexPath == null ? [] : [`+${excludeFromIndexPath}`]),
+ ].join(' ');
+ return await model.findById(doc._id).select(selection).exec();
+ };
+
+ const deleteDocumentAndWait = async (doc: DocumentWithMeiliIndex): Promise<void> => {
+ const deletion = await index.deleteDocument(
+ String(doc[primaryKey as keyof DocumentWithMeiliIndex]),
+ );
+ const deletionTask = await client.waitForTask(deletion.taskUid, {
+ timeOutMs: meiliRequestTimeoutMs,
+ intervalMs: 100,
+ });
+ if (deletionTask.status !== 'succeeded') {
+ throw new Error(`Meili cleanup task ${deletion.taskUid} ended with ${deletionTask.status}`);
+ }
+ };
+
+ /**
+ * Submit a versioned snapshot and acknowledge only the MongoDB write that
+ * produced it. If another replica wins the race, enqueue the latest snapshot
+ * after the stale Meili task so task ordering converges on current Mongo data.
+ */
+ const syncVersionedDocument = async (
+ initialDoc: DocumentWithMeiliIndex,
+ initialMode: 'add' | 'update',
+ ): Promise<void> => {
+ let doc = initialDoc;
+ let mode = initialMode;
+
+ for (let attempt = 0; attempt < meiliVersionReconcileMaxAttempts; attempt++) {
+ const version = doc._meiliIndexVersion;
+ if (!version) {
+ throw new Error('Missing _meiliIndexVersion for detached Meili write');
+ }
+
+ if (!isIndexableDocument(doc, excludeFromIndexPath) || doc.unfinished) {
+ await retryDetachedMeiliWrite(
+ () => deleteDocumentAndWait(doc),
+ '[mongoMeili] Failed to remove a non-indexable document.',
+ );
+ // eslint-disable-next-line no-restricted-syntax -- versioned internal bookkeeping must not re-enter document middleware
+ const cleanup = await doc.collection.updateOne(
+ { _id: doc._id as Types.ObjectId, _meiliIndexVersion: version },
+ {
+ $set: { _meiliCleanupVersion: meiliCleanupVersion },
+ $unset: { _meiliIndex: '', _meiliIndexAttempted: '' },
+ },
+ );
+ if (cleanup.matchedCount > 0) {
+ return;
+ }
+ } else {
+ const object = doc.preprocessObjectForIndex!();
+ await retryDetachedMeiliWrite(async () => {
+ const enqueued =
+ mode === 'update'
+ ? index.updateDocuments([object], { primaryKey })
+ : index.addDocuments([object], { primaryKey });
+ const task = await enqueued;
+ const completedTask = await client.waitForTask(task.taskUid, {
+ timeOutMs: meiliRequestTimeoutMs,
+ intervalMs: 100,
+ });
+ if (completedTask.status !== 'succeeded') {
+ throw new Error(`Meili write task ${task.taskUid} ended with ${completedTask.status}`);
+ }
+ }, '[mongoMeili] Failed to submit a document to Meili.');
+ // eslint-disable-next-line no-restricted-syntax -- versioned internal bookkeeping must not re-enter document middleware
+ const acknowledgement = await doc.collection.updateOne(
+ { _id: doc._id as Types.ObjectId, _meiliIndexVersion: version },
+ { $set: { _meiliIndex: true, _meiliCleanupVersion: meiliCleanupVersion } },
+ );
+ if (acknowledgement.matchedCount > 0) {
+ return;
+ }
+ }
+
+ const latestDoc = await loadLatestDocument(doc);
+ if (!latestDoc) {
+ await retryDetachedMeiliWrite(
+ () => deleteDocumentAndWait(doc),
+ '[mongoMeili] Failed to remove a concurrently deleted document.',
+ );
+ return;
+ }
+ doc = latestDoc;
+ mode = 'add';
+ }
+
+ // eslint-disable-next-line no-restricted-syntax -- versioned internal bookkeeping must not re-enter document middleware
+ await doc.collection.updateOne(
+ { _id: doc._id as Types.ObjectId, _meiliIndexVersion: doc._meiliIndexVersion },
+ { $set: { _meiliIndex: false, _meiliIndexAttempted: true } },
+ );
+ throw new Error('Meili indexing did not converge after concurrent MongoDB writes');
+ };
+
class MeiliMongooseModel {
/**
* Get the current sync progress
@@ -253,20 +412,28 @@ const createMeiliMongooseModel = ({
static async getSyncProgress(this: SchemaWithMeiliMethods): Promise<SyncProgress> {
const indexableQuery = getIndexableQuery();
const excludedIndexedQuery = getExcludedIndexedQuery();
- const [totalDocuments, indexedDocuments, pendingCleanup] = await Promise.all([
- this.countDocuments(indexableQuery),
- this.countDocuments({
- ...indexableQuery,
- _meiliIndex: true,
- }),
- excludedIndexedQuery == null
- ? Promise.resolve(0)
- : this.countDocuments(excludedIndexedQuery),
- ]);
+ const [totalDocuments, indexedDocuments, pendingIndexing, pendingCleanup] = await Promise.all(
+ [
+ this.countDocuments(indexableQuery),
+ this.countDocuments({
+ ...indexableQuery,
+ _meiliIndex: true,
+ }),
+ this.countDocuments({
+ ...indexableQuery,
+ _meiliIndex: { $ne: true },
+ _meiliIndexAttempted: true,
+ }),
+ excludedIndexedQuery == null
+ ? Promise.resolve(0)
+ : this.countDocuments(excludedIndexedQuery),
+ ],
+ );
return {
totalProcessed: indexedDocuments,
totalDocuments,
+ pendingIndexing,
pendingCleanup,
isComplete: indexedDocuments === totalDocuments && pendingCleanup === 0,
};
@@ -595,62 +762,20 @@ const createMeiliMongooseModel = ({
return object;
}
- /**
- * Adds the current document to the MeiliSearch index with retry logic
- */
+ /** Adds the current document to the MeiliSearch index. */
async addObjectToMeili(
this: DocumentWithMeiliIndex,
next: CallbackWithoutResultAndOptionalError,
): Promise<void> {
- if (!isIndexableDocument(this, excludeFromIndexPath)) {
+ if (!this._meiliIndexVersion) {
return next();
}
-
- const object = this.preprocessObjectForIndex!();
- const maxRetries = 3;
- let retryCount = 0;
-
- try {
- // Mark the possible Meili presence before enqueueing the add. If the
- // later Mongo acknowledgement fails, excluded-record cleanup can still
- // distinguish this row from a child that was never submitted to Meili.
- const model = this.constructor as Model<DocumentWithMeiliIndex>;
- await model.updateOne(
- { _id: this._id as Types.ObjectId },
- { $set: { _meiliIndexAttempted: true } },
- { timestamps: false },
- );
- } catch (error) {
- logger.error('[addObjectToMeili] Error marking Meili indexing attempt:', error);
- return next();
- }
-
- while (retryCount < maxRetries) {
- try {
- await index.addDocuments([object], { primaryKey });
- break;
- } catch (error) {
- retryCount++;
- if (retryCount >= maxRetries) {
- logger.error('[addObjectToMeili] Error adding document to Meili after retries:', error);
- return next();
- }
- // Exponential backoff
- await new Promise((resolve) => setTimeout(resolve, Math.pow(2, retryCount) * 1000));
- }
- }
-
try {
- // eslint-disable-next-line no-restricted-syntax -- _meiliIndex is an internal bookkeeping flag, not tenant-scoped data
- await this.collection.updateOne(
- { _id: this._id as Types.ObjectId },
- { $set: { _meiliIndex: true, _meiliCleanupVersion: meiliCleanupVersion } },
- );
+ await syncVersionedDocument(this, 'add');
} catch (error) {
- logger.error('[addObjectToMeili] Error updating _meiliIndex field:', error);
+ logger.error('[addObjectToMeili] Error adding document to Meili:', error);
return next();
}
-
next();
}
@@ -661,33 +786,11 @@ const createMeiliMongooseModel = ({
this: DocumentWithMeiliIndex,
next: CallbackWithoutResultAndOptionalError,
): Promise<void> {
+ if (!this._meiliIndexVersion) {
+ return next();
+ }
try {
- if (!isIndexableDocument(this, excludeFromIndexPath)) {
- const deletion = await index.deleteDocument(
- String(this[primaryKey as keyof DocumentWithMeiliIndex]),
- );
- const deletionTask = await client.waitForTask(deletion.taskUid, {
- timeOutMs: 10000,
- intervalMs: 100,
- });
- if (deletionTask.status !== 'succeeded') {
- throw new Error(
- `Meili cleanup task ${deletion.taskUid} ended with ${deletionTask.status}`,
- );
- }
- const model = this.constructor as Model<DocumentWithMeiliIndex>;
- await model.updateOne(
- { _id: this._id as Types.ObjectId },
- {
- $set: { _meiliCleanupVersion: meiliCleanupVersion },
- $unset: { _meiliIndex: '', _meiliIndexAttempted: '' },
- },
- );
- return next();
- }
-
- const object = this.preprocessObjectForIndex!();
- await index.updateDocuments([object], { primaryKey });
+ await syncVersionedDocument(this, 'update');
next();
} catch (error) {
logger.error('[updateObjectToMeili] Error updating document in Meili:', error);
@@ -719,12 +822,14 @@ const createMeiliMongooseModel = ({
* If the document is already indexed (i.e. `_meiliIndex` is true), it updates it;
* otherwise, it adds the document to the index.
*/
- postSaveHook(this: DocumentWithMeiliIndex, next: CallbackWithoutResultAndOptionalError): void {
- if (this._meiliIndex) {
- this.updateObjectToMeili!(next);
- } else {
- this.addObjectToMeili!(next);
+ postSaveHook(
+ this: DocumentWithMeiliIndex,
+ next: CallbackWithoutResultAndOptionalError,
+ ): Promise<void> {
+ if (this.$locals?.[previouslyIndexedFlagKey] === true || this._meiliIndex) {
+ return this.updateObjectToMeili!(next);
}
+ return this.addObjectToMeili!(next);
}
/**
@@ -802,6 +907,11 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
required: false,
select: false,
},
+ _meiliIndexVersion: {
+ type: String,
+ required: false,
+ select: false,
+ },
_meiliCleanupVersion: {
type: Number,
required: false,
@@ -851,12 +961,16 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
? options.excludeFromIndexPath
: undefined;
const queriesWithInjectedPrivatePath = new WeakSet<object>();
+ const findOneAndUpdateVersions = new WeakMap<object, string>();
const syncOptions = {
batchSize: options.syncBatchSize || getSyncConfig().batchSize,
delayMs: options.syncDelayMs || getSyncConfig().delayMs,
};
- const client = new MeiliSearch({ host, apiKey });
+ const client = new MeiliSearch({ host, apiKey, timeout: meiliRequestTimeoutMs });
+ const runDetachedMeiliOperation = createDetachedMeiliRunner();
+ const getOperationKey = (doc: DocumentWithMeiliIndex): string =>
+ `${indexName}:${String(doc[primaryKey as keyof DocumentWithMeiliIndex] ?? doc._id)}`;
/** Create index only if it doesn't exist */
const index = client.index<MeiliIndexable>(indexName);
@@ -941,16 +1055,45 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
if (hasSchemaPath(schema, 'isTemporary')) {
captureExplicitTemporaryFlag(this);
}
+ this.$locals[previouslyIndexedFlagKey] = this._meiliIndex === true;
+ if (
+ isIndexableDocument(this, options.excludeFromIndexPath) ||
+ this._meiliIndex === true ||
+ this._meiliIndexAttempted === true
+ ) {
+ this._meiliIndexVersion = new mongoose.Types.ObjectId().toString();
+ this._meiliIndex = false;
+ this._meiliIndexAttempted = true;
+ this.markModified('_meiliIndexVersion');
+ this.markModified('_meiliIndex');
+ this.markModified('_meiliIndexAttempted');
+ }
next();
});
schema.post('save', function (doc: DocumentWithMeiliIndex, next) {
- doc.postSaveHook?.(next);
+ next();
+ if (typeof doc.postSaveHook === 'function') {
+ runDetachedMeiliOperation(
+ getOperationKey(doc),
+ () => doc.postSaveHook!(completeDetachedOperation),
+ '[mongoMeili] Detached post-save indexing failed:',
+ );
+ }
});
schema.pre('findOneAndUpdate', function (next) {
+ const query = this as Query<unknown, unknown>;
+ if (meiliEnabled) {
+ const version = new mongoose.Types.ObjectId().toString();
+ query.set({
+ _meiliIndex: false,
+ _meiliIndexAttempted: true,
+ _meiliIndexVersion: version,
+ });
+ findOneAndUpdateVersions.set(query, version);
+ }
if (privateExcludedPath != null) {
- const query = this as Query<unknown, unknown>;
const projection = query.projection() as Record<string, number> | null;
const callerRequestedPrivatePath = Object.entries(projection ?? {}).some(
([path, included]) =>
@@ -968,17 +1111,25 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
});
schema.post('updateOne', function (doc: DocumentWithMeiliIndex, next) {
+ next();
if (typeof doc.postUpdateHook === 'function') {
- return doc.postUpdateHook(next);
+ runDetachedMeiliOperation(
+ getOperationKey(doc),
+ () => doc.postUpdateHook!(completeDetachedOperation),
+ '[mongoMeili] Detached post-update indexing failed:',
+ );
}
- return next();
});
schema.post('deleteOne', function (doc: DocumentWithMeiliIndex, next) {
+ next();
if (typeof doc.postRemoveHook === 'function') {
- return doc.postRemoveHook(next);
+ runDetachedMeiliOperation(
+ getOperationKey(doc),
+ () => doc.postRemoveHook!(completeDetachedOperation),
+ '[mongoMeili] Detached post-remove indexing failed:',
+ );
}
- return next();
});
// Pre-deleteMany hook: remove corresponding documents from MeiliSearch when multiple documents are deleted.
@@ -1039,7 +1190,7 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
// Post-findOneAndUpdate hook
schema.post(
'findOneAndUpdate',
- async function (
+ function (
res: DocumentWithMeiliIndex | { value: DocumentWithMeiliIndex | null } | null,
next: CallbackWithoutResultAndOptionalError,
) {
@@ -1054,55 +1205,41 @@ export default function mongoMeili(schema: Schema, options: MongoMeiliOptions):
} else {
doc = res;
}
- const finish = (error?: Error | null): void => {
- if (
- doc != null &&
- privateExcludedPath != null &&
- queriesWithInjectedPrivatePath.has(this)
- ) {
- if (doc instanceof mongoose.Document) {
- doc.set(privateExcludedPath, undefined);
- } else {
- _.unset(doc, privateExcludedPath);
- }
- }
- next(error ?? undefined);
- };
-
- if (!meiliEnabled) {
- finish();
- return;
- }
-
- if (!doc || doc.unfinished) {
- finish();
- return;
- }
-
- let meiliDoc: Record<string, unknown> | undefined;
- if (doc.messages) {
- try {
- meiliDoc = await client.index('convos').getDocument(doc.conversationId as string);
- } catch (error: unknown) {
- logger.debug(
- '[MeiliMongooseModel.findOneAndUpdate] Convo not found in MeiliSearch and will index ' +
- doc.conversationId,
- error as Record<string, unknown>,
- );
+ if (doc != null && privateExcludedPath != null && queriesWithInjectedPrivatePath.has(this)) {
+ if (doc instanceof mongoose.Document) {
+ doc.set(privateExcludedPath, undefined);
+ } else {
+ _.unset(doc, privateExcludedPath);
}
}
- if (meiliDoc && meiliDoc.title === doc.title) {
- finish();
- return;
- }
-
- if (typeof doc.postSaveHook === 'function') {
- await doc.postSaveHook(finish);
+ const version = findOneAndUpdateVersions.get(this);
+ if (!meiliEnabled || !doc || !version) {
+ next();
return;
}
- finish();
+ const savedDoc = doc;
+ const model = (this as Query<unknown, DocumentWithMeiliIndex>).model;
+ next();
+ runDetachedMeiliOperation(
+ getOperationKey(savedDoc),
+ async () => {
+ const latestDoc = await model
+ .findById(savedDoc._id)
+ .select(
+ [
+ '+_meiliIndex',
+ '+_meiliIndexAttempted',
+ '+_meiliIndexVersion',
+ ...(privateExcludedPath == null ? [] : [`+${privateExcludedPath}`]),
+ ].join(' '),
+ )
+ .exec();
+ await latestDoc?.addObjectToMeili?.(completeDetachedOperation);
+ },
+ '[mongoMeili] Detached findOneAndUpdate indexing failed:',
+ );
},
);
}