Skip to content

The open alternative to Salesforce, designed for AI.

Fix stack overflow when importing a large Gmail folder (#24883)

neo77381c915553c74
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-process-folder-actions.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-process-folder-actions.service.ts
index 91aba266f71..7956f213dd9 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-process-folder-actions.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-process-folder-actions.service.ts
@@ -49,7 +49,7 @@ export class MessagingProcessFolderActionsService {
`WorkspaceId: ${workspaceId}, MessageChannelId: ${messageChannel.id} - Processing ${foldersWithPendingActions.length} folders with pending actions`,
);
- const messageExternalIdsToImport: string[] = [];
+ const messageExternalIdsToImport = new Set<string>();
const folderIdsToDelete: string[] = [];
const processedFolderIds: string[] = [];
const failedFolderIds: Array<{ folderId: string; error: Error }> = [];
@@ -82,9 +82,9 @@ export class MessagingProcessFolderActionsService {
folder,
);
- messageExternalIdsToImport.push(
- ...folderMessageExternalIdsToImport,
- );
+ for (const messageExternalId of folderMessageExternalIdsToImport) {
+ messageExternalIdsToImport.add(messageExternalId);
+ }
this.logger.debug(
`WorkspaceId: ${workspaceId}, MessageChannelId: ${messageChannel.id}, FolderId: ${folder.id} - Completed FOLDER_IMPORT action`,
@@ -142,7 +142,7 @@ export class MessagingProcessFolderActionsService {
}
return {
- messageExternalIdsToImport: [...new Set(messageExternalIdsToImport)],
+ messageExternalIdsToImport: [...messageExternalIdsToImport],
};
}
}
diff --git a/packages/twenty-server/test/integration/google/messaging/folder-import-actions.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/folder-import-actions.integration-spec.ts
new file mode 100644
index 00000000000..8ad727cff42
--- /dev/null
+++ b/packages/twenty-server/test/integration/google/messaging/folder-import-actions.integration-spec.ts
@@ -0,0 +1,98 @@
+import {
+ ConnectedAccountProvider,
+ MessageFolderPendingSyncAction,
+} from 'twenty-shared/types';
+
+import { getGmailMessageSubject } from 'test/integration/google/mocks/gmail-message-subject.util';
+import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';
+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { findImportedMessageSubjects } from 'test/integration/utils/find-imported-records.util';
+import {
+ type MessageFolderDto,
+ queryMessageFolders,
+} from 'test/integration/utils/query-messaging.util';
+import {
+ FOLDER_ACTION_NAMES,
+ MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT,
+ runFolderActions,
+ runFolderActionsWithoutPendingActions,
+} from 'test/integration/utils/run-folder-actions.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+const DELETED_FOLDER_NAME = 'INBOX';
+
+describe('Gmail folder actions (integration)', () => {
+ const inbox = [gmailMessage()];
+ const importedSubject = getGmailMessageSubject(inbox[0]);
+
+ setupGoogleMock({ handle: HANDLE, inbox });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+ let messageExternalIdsToImport: string[];
+ let messageExternalIdsWithoutPendingActions: string[];
+ let folders: MessageFolderDto[];
+ let subjectsBeforeFolderDeletion: string[];
+ let subjectsAfterFolderDeletion: string[];
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.GOOGLE,
+ handle: HANDLE,
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ subjectsBeforeFolderDeletion = await findImportedMessageSubjects([
+ importedSubject,
+ ]);
+
+ messageExternalIdsToImport = await runFolderActions({
+ messageChannelId: channel.channelId,
+ folderNameToDelete: DELETED_FOLDER_NAME,
+ });
+
+ subjectsAfterFolderDeletion = await findImportedMessageSubjects([
+ importedSubject,
+ ]);
+ folders = await queryMessageFolders(channel.channelId);
+
+ messageExternalIdsWithoutPendingActions =
+ await runFolderActionsWithoutPendingActions(channel.channelId);
+ }, 180000);
+
+ afterAll(async () => {
+ jest.restoreAllMocks();
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('imports every message id of a folder larger than the spread-argument limit, deduplicated', () => {
+ expect(messageExternalIdsToImport).toHaveLength(
+ MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT,
+ );
+ });
+
+ it('clears the pending action it processed, keeps the one it failed on, and drops the deleted folder', () => {
+ expect(
+ Object.fromEntries(
+ folders.map((folder) => [folder.name, folder.pendingSyncAction]),
+ ),
+ ).toEqual({
+ SENT: MessageFolderPendingSyncAction.NONE,
+ [FOLDER_ACTION_NAMES.imported]: MessageFolderPendingSyncAction.NONE,
+ [FOLDER_ACTION_NAMES.failing]:
+ MessageFolderPendingSyncAction.FOLDER_IMPORT,
+ [FOLDER_ACTION_NAMES.untouched]: MessageFolderPendingSyncAction.NONE,
+ });
+ });
+
+ it('deletes the messages of the folder marked for deletion', () => {
+ expect(subjectsBeforeFolderDeletion).toEqual([importedSubject]);
+ expect(subjectsAfterFolderDeletion).toEqual([]);
+ });
+
+ it('imports nothing when no folder carries a pending action', () => {
+ expect(messageExternalIdsWithoutPendingActions).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.ts
new file mode 100644
index 00000000000..5ef0d79ab7d
--- /dev/null
+++ b/packages/twenty-server/test/integration/imap/suites/imap-folder-import-actions.integration-spec.ts
@@ -0,0 +1,124 @@
+import { randomUUID } from 'node:crypto';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { MessageFolderPendingSyncAction } from 'twenty-shared/types';
+
+import { deleteConnectedAccount } from 'test/integration/metadata/suites/connected-account/utils/delete-connected-account.util';
+import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';
+import { appendMessageOverImap } from 'test/integration/utils/append-message-over-imap.util';
+import { connectDovecotImapAccount } from 'test/integration/utils/connect-dovecot-imap-account.util';
+import { findImportedMessageSubjects } from 'test/integration/utils/find-imported-records.util';
+import {
+ type MessageFolderDto,
+ queryMessageFolders,
+} from 'test/integration/utils/query-messaging.util';
+import {
+ FOLDER_ACTION_NAMES,
+ MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT,
+ runFolderActions,
+ runFolderActionsWithoutPendingActions,
+} from 'test/integration/utils/run-folder-actions.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+import { type DovecotServer } from 'test/integration/utils/start-dovecot-container.util';
+
+const PASSWORD = 'dovecot-password';
+const HANDLE = `imap-folder-actions-${randomUUID()}@acme.test`;
+const DELETED_FOLDER_NAME = 'INBOX';
+const IMPORTED_SUBJECT = `IMAP inbox message ${randomUUID()}`;
+
+describe('IMAP folder actions (integration)', () => {
+ let dovecot: DovecotServer;
+ let connectedAccountId: string;
+ let messageExternalIdsToImport: string[];
+ let messageExternalIdsWithoutPendingActions: string[];
+ let folders: MessageFolderDto[];
+ let subjectsBeforeFolderDeletion: string[];
+ let subjectsAfterFolderDeletion: string[];
+
+ beforeAll(async () => {
+ const account = await connectDovecotImapAccount({
+ handle: HANDLE,
+ password: PASSWORD,
+ });
+
+ dovecot = account.dovecot;
+ connectedAccountId = account.connectedAccountId;
+
+ await appendMessageOverImap({
+ host: dovecot.host,
+ port: dovecot.imapPort,
+ username: HANDLE,
+ password: PASSWORD,
+ folder: 'INBOX',
+ from: `sender-${randomUUID()}@external.test`,
+ to: HANDLE,
+ subject: IMPORTED_SUBJECT,
+ });
+
+ await runMessageChannelSync(account.messageChannelId);
+
+ subjectsBeforeFolderDeletion = await findImportedMessageSubjects([
+ IMPORTED_SUBJECT,
+ ]);
+
+ messageExternalIdsToImport = await runFolderActions({
+ messageChannelId: account.messageChannelId,
+ folderNameToDelete: DELETED_FOLDER_NAME,
+ });
+
+ subjectsAfterFolderDeletion = await findImportedMessageSubjects([
+ IMPORTED_SUBJECT,
+ ]);
+ folders = await queryMessageFolders(account.messageChannelId);
+
+ messageExternalIdsWithoutPendingActions =
+ await runFolderActionsWithoutPendingActions(account.messageChannelId);
+ }, 300000);
+
+ afterAll(async () => {
+ jest.restoreAllMocks();
+
+ await updateConfigVariable({
+ input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },
+ }).catch(() => undefined);
+
+ if (isNonEmptyString(connectedAccountId)) {
+ await deleteConnectedAccount({
+ id: connectedAccountId,
+ expectToFail: false,
+ }).catch(() => undefined);
+ }
+
+ await dovecot?.stop().catch(() => undefined);
+ });
+
+ it('imports every message id of a folder larger than the spread-argument limit, deduplicated', () => {
+ expect(messageExternalIdsToImport).toHaveLength(
+ MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT,
+ );
+ });
+
+ it('clears the pending action it processed, keeps the one it failed on, and drops the deleted folder', () => {
+ expect(
+ Object.fromEntries(
+ folders.map((folder) => [folder.name, folder.pendingSyncAction]),
+ ),
+ ).toEqual({
+ Sent: MessageFolderPendingSyncAction.NONE,
+ Drafts: MessageFolderPendingSyncAction.NONE,
+ [FOLDER_ACTION_NAMES.imported]: MessageFolderPendingSyncAction.NONE,
+ [FOLDER_ACTION_NAMES.failing]:
+ MessageFolderPendingSyncAction.FOLDER_IMPORT,
+ [FOLDER_ACTION_NAMES.untouched]: MessageFolderPendingSyncAction.NONE,
+ });
+ });
+
+ it('deletes the messages of the folder marked for deletion', () => {
+ expect(subjectsBeforeFolderDeletion).toEqual([IMPORTED_SUBJECT]);
+ expect(subjectsAfterFolderDeletion).toEqual([]);
+ });
+
+ it('imports nothing when no folder carries a pending action', () => {
+ expect(messageExternalIdsWithoutPendingActions).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/microsoft/messaging/folder-import-actions.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/messaging/folder-import-actions.integration-spec.ts
new file mode 100644
index 00000000000..aea5041dcb1
--- /dev/null
+++ b/packages/twenty-server/test/integration/microsoft/messaging/folder-import-actions.integration-spec.ts
@@ -0,0 +1,109 @@
+import { randomUUID } from 'node:crypto';
+
+import {
+ ConnectedAccountProvider,
+ MessageFolderPendingSyncAction,
+} from 'twenty-shared/types';
+
+import { setupMicrosoftMock } from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';
+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';
+import { findImportedMessageSubjects } from 'test/integration/utils/find-imported-records.util';
+import {
+ type MessageFolderDto,
+ queryMessageFolders,
+} from 'test/integration/utils/query-messaging.util';
+import {
+ FOLDER_ACTION_NAMES,
+ MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT,
+ runFolderActions,
+ runFolderActionsWithoutPendingActions,
+} from 'test/integration/utils/run-folder-actions.util';
+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';
+
+const HANDLE = '[email protected]';
+const DELETED_FOLDER_NAME = 'Inbox';
+const IMPORTED_SUBJECT = `Microsoft inbox message ${randomUUID()}`;
+
+const INBOX_MESSAGE = {
+ id: 'microsoft-folder-actions-message',
+ subject: IMPORTED_SUBJECT,
+ body: { contentType: 'text', content: 'Microsoft inbox body' },
+ receivedDateTime: '2026-08-13T00:00:00.000Z',
+ internetMessageId: '<[email protected]>',
+ conversationId: 'microsoft-folder-actions-conversation',
+ parentFolderId: 'inbox',
+ isDraft: false,
+ from: { emailAddress: { address: '[email protected]' } },
+ toRecipients: [{ emailAddress: { address: HANDLE } }],
+};
+
+describe('Microsoft folder actions (integration)', () => {
+ setupMicrosoftMock({ handle: HANDLE, messages: [INBOX_MESSAGE] });
+
+ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;
+ let messageExternalIdsToImport: string[];
+ let messageExternalIdsWithoutPendingActions: string[];
+ let folders: MessageFolderDto[];
+ let subjectsBeforeFolderDeletion: string[];
+ let subjectsAfterFolderDeletion: string[];
+
+ beforeAll(async () => {
+ channel = await connectMessagingAccount({
+ provider: ConnectedAccountProvider.MICROSOFT,
+ handle: HANDLE,
+ });
+
+ await runMessageChannelSync(channel.channelId);
+
+ subjectsBeforeFolderDeletion = await findImportedMessageSubjects([
+ IMPORTED_SUBJECT,
+ ]);
+
+ messageExternalIdsToImport = await runFolderActions({
+ messageChannelId: channel.channelId,
+ folderNameToDelete: DELETED_FOLDER_NAME,
+ });
+
+ subjectsAfterFolderDeletion = await findImportedMessageSubjects([
+ IMPORTED_SUBJECT,
+ ]);
+ folders = await queryMessageFolders(channel.channelId);
+
+ messageExternalIdsWithoutPendingActions =
+ await runFolderActionsWithoutPendingActions(channel.channelId);
+ }, 180000);
+
+ afterAll(async () => {
+ jest.restoreAllMocks();
+ await channel?.cleanup().catch(() => undefined);
+ });
+
+ it('imports every message id of a folder larger than the spread-argument limit, deduplicated', () => {
+ expect(messageExternalIdsToImport).toHaveLength(
+ MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT,
+ );
+ });
+
+ it('clears the pending action it processed, keeps the one it failed on, and drops the deleted folder', () => {
+ expect(
+ Object.fromEntries(
+ folders.map((folder) => [folder.name, folder.pendingSyncAction]),
+ ),
+ ).toEqual({
+ 'Sent Items': MessageFolderPendingSyncAction.NONE,
+ [FOLDER_ACTION_NAMES.imported]: MessageFolderPendingSyncAction.NONE,
+ [FOLDER_ACTION_NAMES.failing]:
+ MessageFolderPendingSyncAction.FOLDER_IMPORT,
+ [FOLDER_ACTION_NAMES.untouched]: MessageFolderPendingSyncAction.NONE,
+ });
+ });
+
+ it('deletes the messages of the folder marked for deletion', () => {
+ expect(subjectsBeforeFolderDeletion).toEqual([IMPORTED_SUBJECT]);
+ expect(subjectsAfterFolderDeletion).toEqual([]);
+ });
+
+ it('imports nothing when no folder carries a pending action', () => {
+ expect(messageExternalIdsWithoutPendingActions).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/test/integration/utils/query-messaging.util.ts b/packages/twenty-server/test/integration/utils/query-messaging.util.ts
index 9160cf53c15..2af1b1e844b 100644
--- a/packages/twenty-server/test/integration/utils/query-messaging.util.ts
+++ b/packages/twenty-server/test/integration/utils/query-messaging.util.ts
@@ -31,7 +31,7 @@ export const getDataOrThrow = (response: MetadataAPIResponse) => {
export type MessageFolderDto = Pick<
MessageFolderDTO,
- 'id' | 'name' | 'isSynced' | 'isSentFolder'
+ 'id' | 'name' | 'isSynced' | 'isSentFolder' | 'pendingSyncAction'
>;
export type MessageChannelDto = Pick<
@@ -148,6 +148,7 @@ export const queryMessageFolders = async (
name
isSynced
isSentFolder
+ pendingSyncAction
}
}
`,
diff --git a/packages/twenty-server/test/integration/utils/run-folder-actions.util.ts b/packages/twenty-server/test/integration/utils/run-folder-actions.util.ts
new file mode 100644
index 00000000000..7ba8ab6232b
--- /dev/null
+++ b/packages/twenty-server/test/integration/utils/run-folder-actions.util.ts
@@ -0,0 +1,136 @@
+import { MessageFolderPendingSyncAction } from 'twenty-shared/types';
+
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';
+import { type MessagingImportFolderMessagesService } from 'src/modules/messaging/message-import-manager/services/messaging-import-folder-messages.service';
+import { type MessagingProcessFolderActionsService } from 'src/modules/messaging/message-import-manager/services/messaging-process-folder-actions.service';
+
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';
+
+export const MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT = 200000;
+
+export const FOLDER_ACTION_NAMES = {
+ imported: 'Large import folder',
+ failing: 'Failing import folder',
+ untouched: 'Untouched folder',
+};
+
+const MESSAGE_EXTERNAL_IDS = Array.from(
+ { length: MESSAGE_COUNT_ABOVE_V8_SPREAD_ARGUMENT_LIMIT },
+ (_, index) => `large-folder-message-${index}`,
+);
+
+const getMessageFolderRepository = () =>
+ getCoreRepository<MessageFolderEntity>(MessageFolderEntity);
+
+const getMessageChannel = (messageChannelId: string) =>
+ getCoreRepository<MessageChannelEntity>(MessageChannelEntity).findOneByOrFail(
+ { id: messageChannelId },
+ );
+
+const processFolderActions = (
+ messageChannel: MessageChannelEntity,
+ messageFolders: MessageFolderEntity[],
+) =>
+ getAppProviderByClassName<MessagingProcessFolderActionsService>(
+ 'MessagingProcessFolderActionsService',
+ ).processFolderActions(
+ messageChannel,
+ messageFolders,
+ messageChannel.workspaceId,
+ );
+
+export const runFolderActions = async ({
+ messageChannelId,
+ folderNameToDelete,
+}: {
+ messageChannelId: string;
+ folderNameToDelete: string;
+}): Promise<string[]> => {
+ const messageChannel = await getMessageChannel(messageChannelId);
+ const messageFolderRepository = getMessageFolderRepository();
+
+ const buildFolder = (
+ name: string,
+ pendingSyncAction: MessageFolderPendingSyncAction,
+ ) => ({
+ messageChannelId,
+ workspaceId: messageChannel.workspaceId,
+ name,
+ externalId: `${name}-external-id`,
+ isSentFolder: false,
+ isSynced: true,
+ pendingSyncAction,
+ });
+
+ await messageFolderRepository.save([
+ buildFolder(
+ FOLDER_ACTION_NAMES.imported,
+ MessageFolderPendingSyncAction.FOLDER_IMPORT,
+ ),
+ buildFolder(
+ FOLDER_ACTION_NAMES.failing,
+ MessageFolderPendingSyncAction.FOLDER_IMPORT,
+ ),
+ buildFolder(
+ FOLDER_ACTION_NAMES.untouched,
+ MessageFolderPendingSyncAction.NONE,
+ ),
+ ]);
+
+ const folderToDelete = await messageFolderRepository.findOneByOrFail({
+ messageChannelId,
+ name: folderNameToDelete,
+ });
+
+ await messageFolderRepository.update(
+ { id: folderToDelete.id },
+ { pendingSyncAction: MessageFolderPendingSyncAction.FOLDER_DELETION },
+ );
+
+ const failingFolder = await messageFolderRepository.findOneByOrFail({
+ messageChannelId,
+ name: FOLDER_ACTION_NAMES.failing,
+ });
+
+ jest
+ .spyOn(
+ getAppProviderByClassName<MessagingImportFolderMessagesService>(
+ 'MessagingImportFolderMessagesService',
+ ),
+ 'getFolderMessageIdsToImport',
+ )
+ .mockImplementation(async (_messageChannel, messageFolder) => {
+ if (messageFolder.id === failingFolder.id) {
+ throw new Error('Folder import failed');
+ }
+
+ return [...MESSAGE_EXTERNAL_IDS, MESSAGE_EXTERNAL_IDS[0]];
+ });
+
+ const { messageExternalIdsToImport } = await processFolderActions(
+ messageChannel,
+ await messageFolderRepository.findBy({ messageChannelId }),
+ );
+
+ return messageExternalIdsToImport;
+};
+
+export const runFolderActionsWithoutPendingActions = async (
+ messageChannelId: string,
+): Promise<string[]> => {
+ const messageChannel = await getMessageChannel(messageChannelId);
+
+ const untouchedFolder = await getMessageFolderRepository().findOneByOrFail({
+ messageChannelId,
+ name: FOLDER_ACTION_NAMES.untouched,
+ });
+
+ const { messageExternalIdsToImport } = await processFolderActions(
+ messageChannel,
+ [untouchedFolder],
+ );
+
+ return messageExternalIdsToImport;
+};