The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Pace call recorder recovery jobs to stay under Recall's rate limit (#26418)
nitinf3f0823f9a48
diff --git a/packages/twenty-apps/public/call-recorder/package.json b/packages/twenty-apps/public/call-recorder/package.jsonindex 4f6dfecb630..bda2abd4bb0 100644--- a/packages/twenty-apps/public/call-recorder/package.json+++ b/packages/twenty-apps/public/call-recorder/package.json@@ -1,6 +1,6 @@{"name": "@twentyhq/call-recorder",- "version": "1.14.0",+ "version": "1.14.1","license": "MIT","engines": {"node": "^24.5.0",diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-recovery-calls-per-minute.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-recovery-calls-per-minute.tsnew file mode 100644index 00000000000..b9a60cfd7de--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/constants/recall-recovery-calls-per-minute.ts@@ -0,0 +1,4 @@+// Recall caps GET /bot/{id} at 300/min for the whole account, shared by every+// workspace and by webhook-driven work, so one workspace's recovery takes a slice.+// Job delays are lower bounds, so this paces recovery rather than capping it.+export const RECALL_RECOVERY_CALLS_PER_MINUTE = 60;diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-reconciliations.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-reconciliations.test.tsnew file mode 100644index 00000000000..45e7597fdcd--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/__tests__/enqueue-call-recording-reconciliations.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';+import { MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL } from 'src/logic-functions/constants/max-payloads-per-enqueue-jobs-call';+import { enqueueCallRecordingReconciliations } from 'src/logic-functions/data/enqueue-call-recording-reconciliations.util';++const enqueueJobsMock = vi.hoisted(() => vi.fn());++vi.mock('twenty-sdk/logic-function', () => ({+ enqueueJobs: enqueueJobsMock,+}));++describe('enqueueCallRecordingReconciliations', () => {+ beforeEach(() => {+ enqueueJobsMock.mockReset().mockResolvedValue({ enqueued: true });+ });++ it('enqueues nothing without recordings', async () => {+ await enqueueCallRecordingReconciliations({+ callRecordingIds: [],+ recoveryDate: '2026-06-10',+ });++ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('gives each recording one job id per recovery day', async () => {+ await enqueueCallRecordingReconciliations({+ callRecordingIds: ['recording-1', 'recording-2'],+ recoveryDate: '2026-06-10',+ delayMs: 60_000,+ });++ expect(enqueueJobsMock).toHaveBeenCalledExactlyOnceWith({+ logicFunctionUniversalIdentifier:+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ jobs: [+ {+ jobId: 'call-recorder-recording-1-reconcile-2026-06-10',+ payload: { callRecordingId: 'recording-1' },+ },+ {+ jobId: 'call-recorder-recording-2-reconcile-2026-06-10',+ payload: { callRecordingId: 'recording-2' },+ },+ ],+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ delayMs: 60_000,+ });+ });++ it('splits recordings above the mutation cap into multiple calls', async () => {+ await enqueueCallRecordingReconciliations({+ callRecordingIds: Array.from(+ { length: MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL + 1 },+ (_, index) => `recording-${index}`,+ ),+ recoveryDate: '2026-06-10',+ });++ expect(enqueueJobsMock.mock.calls.map(([{ jobs }]) => jobs.length)).toEqual(+ [MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL, 1],+ );+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.tsindex 6ce06892c69..df51ce4349b 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-artifacts-import.util.ts@@ -12,11 +12,13 @@ export const enqueueCallRecordingArtifactsImport = async ({scopes,trigger = 'recording',requestedAt = new Date().toISOString(),+ delayMs,}: {callRecordingIds: string[];scopes: CallRecordingArtifactImportScope[];trigger?: 'recording' | 'transcript-ready' | 'expired' | 'recovery';requestedAt?: string;+ delayMs?: number;}): Promise<void> => {const isQueueStatusRequired = trigger === 'recovery' || trigger === 'expired';const recoveryDate = requestedAt.slice(0, 10);@@ -104,6 +106,7 @@ export const enqueueCallRecordingArtifactsImport = async ({IMPORT_CALL_RECORDING_ARTIFACTS_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,jobs,retryLimit: scope === 'video' ? 0 : ENQUEUED_JOB_RETRY_LIMIT,+ delayMs,});}}diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-reconciliations.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-reconciliations.util.tsnew file mode 100644index 00000000000..008c6251ba7--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-call-recording-reconciliations.util.ts@@ -0,0 +1,34 @@+import { enqueueJobs } from 'twenty-sdk/logic-function';++import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import { ENQUEUED_JOB_RETRY_LIMIT } from 'src/logic-functions/constants/enqueued-job-retry-limit';+import { MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL } from 'src/logic-functions/constants/max-payloads-per-enqueue-jobs-call';+import { getBatches } from 'src/logic-functions/utils/get-batches.util';++// One job id per recording per recovery day, so an overlapping page or a+// re-run is deduplicated for as long as the queue still retains the first job.+export const enqueueCallRecordingReconciliations = async ({+ callRecordingIds,+ recoveryDate,+ delayMs,+}: {+ callRecordingIds: string[];+ recoveryDate: string;+ delayMs?: number;+}): Promise<void> => {+ for (const recordingIds of getBatches(+ callRecordingIds,+ MAX_PAYLOADS_PER_ENQUEUE_JOBS_CALL,+ )) {+ await enqueueJobs({+ logicFunctionUniversalIdentifier:+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ jobs: recordingIds.map((callRecordingId) => ({+ jobId: `call-recorder-${callRecordingId}-reconcile-${recoveryDate}`,+ payload: { callRecordingId },+ })),+ retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ delayMs,+ });+ }+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.tsindex 2e856953334..29cdd5c8bb4 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/data/enqueue-logic-function-jobs.util.ts@@ -7,9 +7,11 @@ import { getBatches } from 'src/logic-functions/utils/get-batches.util';export const enqueueLogicFunctionJobs = async ({logicFunctionUniversalIdentifier,payloads,+ delayMs,}: {logicFunctionUniversalIdentifier: string;payloads: Record<string, unknown>[];+ delayMs?: number;}): Promise<void> => {for (const payloadChunk of getBatches(payloads,@@ -19,6 +21,7 @@ export const enqueueLogicFunctionJobs = async ({logicFunctionUniversalIdentifier,payloads: payloadChunk,retryLimit: ENQUEUED_JOB_RETRY_LIMIT,+ delayMs,});}};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/group-recovery-work-into-minute-slots.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/group-recovery-work-into-minute-slots.test.tsnew file mode 100644index 00000000000..4ab1aaf905d--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/__tests__/group-recovery-work-into-minute-slots.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { RECALL_RECOVERY_CALLS_PER_MINUTE } from 'src/logic-functions/constants/recall-recovery-calls-per-minute';+import {+ type CallRecordingRecoveryWork,+ groupRecoveryWorkIntoMinuteSlots,+} from 'src/logic-functions/domain/group-recovery-work-into-minute-slots.util';++const buildWork = (+ count: number,+ kind: CallRecordingRecoveryWork['kind'],+ prefix: string = kind,+): CallRecordingRecoveryWork[] =>+ Array.from({ length: count }, (_, index) => ({+ callRecordingId: `${prefix}-${index}`,+ kind,+ }));++describe('groupRecoveryWorkIntoMinuteSlots', () => {+ it('returns no slots when there is no work', () => {+ expect(groupRecoveryWorkIntoMinuteSlots([])).toEqual([]);+ });++ it('fits one reconciliation per Recall call in each minute', () => {+ const slots = groupRecoveryWorkIntoMinuteSlots(+ buildWork(RECALL_RECOVERY_CALLS_PER_MINUTE * 2 + 1, 'reconcile'),+ );++ expect(slots.map((slot) => slot.length)).toEqual([+ RECALL_RECOVERY_CALLS_PER_MINUTE,+ RECALL_RECOVERY_CALLS_PER_MINUTE,+ 1,+ ]);+ });++ it('counts an import as one Recall call per artifact scope', () => {+ const slots = groupRecoveryWorkIntoMinuteSlots(buildWork(25, 'import'));++ expect(slots.map((slot) => slot.length)).toEqual([20, 5]);+ });++ it('moves work that would overflow a minute into the next one, keeping order', () => {+ const recoveryWork = [+ ...buildWork(58, 'reconcile'),+ ...buildWork(1, 'import'),+ ...buildWork(1, 'reconcile', 'late'),+ ];+ const slots = groupRecoveryWorkIntoMinuteSlots(recoveryWork);++ expect(slots.map((slot) => slot.length)).toEqual([58, 2]);+ expect(slots.flat()).toEqual(recoveryWork);+ });+});diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/group-recovery-work-into-minute-slots.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/group-recovery-work-into-minute-slots.util.tsnew file mode 100644index 00000000000..79092bb2621--- /dev/null+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/domain/group-recovery-work-into-minute-slots.util.ts@@ -0,0 +1,41 @@+import { CALL_RECORDING_ARTIFACT_IMPORT_SCOPES } from 'src/logic-functions/constants/call-recording-artifact-import-scopes';+import { RECALL_RECOVERY_CALLS_PER_MINUTE } from 'src/logic-functions/constants/recall-recovery-calls-per-minute';++export type CallRecordingRecoveryWork = {+ callRecordingId: string;+ kind: 'import' | 'reconcile';+};++// Each import scope runs as its own job and may read the bot, so an import+// can cost one Recall call per scope while a reconciliation costs one.+const getMaximumRecallCallCount = ({+ kind,+}: CallRecordingRecoveryWork): number =>+ kind === 'import' ? CALL_RECORDING_ARTIFACT_IMPORT_SCOPES.length : 1;++export const groupRecoveryWorkIntoMinuteSlots = (+ recoveryWork: CallRecordingRecoveryWork[],+): CallRecordingRecoveryWork[][] => {+ const minuteSlots: CallRecordingRecoveryWork[][] = [];+ let currentSlotRecallCallCount = 0;++ for (const work of recoveryWork) {+ const recallCallCount = getMaximumRecallCallCount(work);+ const currentSlot = minuteSlots[minuteSlots.length - 1];++ if (+ currentSlot === undefined ||+ currentSlotRecallCallCount + recallCallCount >+ RECALL_RECOVERY_CALLS_PER_MINUTE+ ) {+ minuteSlots.push([work]);+ currentSlotRecallCallCount = recallCallCount;+ continue;+ }++ currentSlot.push(work);+ currentSlotRecallCallCount += recallCallCount;+ }++ return minuteSlots;+};diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.tsindex d3dff5dcd9f..61419bbd174 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/__tests__/converge-diverged-call-recordings.test.ts@@ -251,6 +251,96 @@ describe('convergeDivergedCallRecordings', () => {]);});+ it('spreads reconciliations over minutes with one job id per recording per day', async () => {+ const client = buildClient(+ Array.from({ length: 100 }, (_, index) => ({+ id: `recording-${index}`,+ status: 'RECORDING',+ })),+ );++ await convergeDivergedCallRecordings({+ client: client as unknown as CoreApiClient,+ now: NOW,+ });++ const reconcileBatches = enqueueJobsMock.mock.calls.map(([batch]) => batch);++ expect(+ reconcileBatches.map(({ jobs, delayMs }) => ({+ jobCount: jobs.length,+ delayMs,+ })),+ ).toEqual([+ { jobCount: 60, delayMs: 0 },+ { jobCount: 40, delayMs: 60_000 },+ ]);+ expect(reconcileBatches[1].jobs[0]).toEqual({+ jobId: 'call-recorder-recording-60-reconcile-2026-06-10',+ payload: { callRecordingId: 'recording-60' },+ });+ });++ it('spreads imports over minutes, counting each artifact scope as a Recall call', async () => {+ const client = buildClient(+ Array.from({ length: 25 }, (_, index) => ({+ id: `recording-${index}`,+ status: 'PROCESSING',+ })),+ );++ await convergeDivergedCallRecordings({+ client: client as unknown as CoreApiClient,+ now: NOW,+ });++ const videoBatches = enqueueJobsMock.mock.calls+ .map(([batch]) => batch)+ .filter(({ jobs }) =>+ jobs.every(+ ({ payload }: { payload: { scope: string } }) =>+ payload.scope === 'video',+ ),+ );++ expect(+ videoBatches.map(({ jobs, delayMs }) => ({+ recordingCount: jobs.length,+ delayMs,+ })),+ ).toEqual([+ { recordingCount: 20, delayMs: 0 },+ { recordingCount: 5, delayMs: 60_000 },+ ]);+ });++ it('starts the next page once the current page has drained', async () => {+ const client = buildClient(+ Array.from({ length: 101 }, (_, index) => ({+ id: `recording-${index}`,+ status: 'PROCESSING',+ })),+ );++ await convergeDivergedCallRecordings({+ client: client as unknown as CoreApiClient,+ now: NOW,+ });++ const nextPageBatch = enqueueJobsMock.mock.calls+ .map(([batch]) => batch)+ .find(+ ({ logicFunctionUniversalIdentifier }) =>+ logicFunctionUniversalIdentifier ===+ STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ );++ expect(nextPageBatch).toMatchObject({+ payloads: [{ after: 'recording-99' }],+ delayMs: 5 * 60_000,+ });+ });+it('propagates enqueue failure instead of silently reporting recovery success', async () => {enqueueJobsMock.mockRejectedValueOnce(new Error('Queue unavailable'));const client = buildClient([{ id: 'recording', status: 'PROCESSING' }]);diff --git a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.tsindex c2fb47b7fcd..cf24565be90 100644--- a/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts+++ b/packages/twenty-apps/public/call-recorder/src/logic-functions/flows/converge-diverged-call-recordings.util.ts@@ -5,11 +5,17 @@ import { STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constanimport { CALL_RECORDING_ARTIFACT_IMPORT_SCOPES } from 'src/logic-functions/constants/call-recording-artifact-import-scopes';import { CallRecordingRequestStatus } from 'src/logic-functions/constants/call-recording-request-status';import { CallRecordingStatus } from 'src/logic-functions/constants/call-recording-status';+import { MILLISECONDS_PER_MINUTE } from 'src/logic-functions/constants/milliseconds-per-minute';import { NON_TERMINAL_CALL_RECORDING_STATUSES } from 'src/logic-functions/constants/non-terminal-call-recording-statuses';import { TWENTY_PAGE_SIZE } from 'src/logic-functions/constants/twenty-page-size';import { enqueueLogicFunctionJobs } from 'src/logic-functions/data/enqueue-logic-function-jobs.util';import { enqueueCallRecordingArtifactsImport } from 'src/logic-functions/data/enqueue-call-recording-artifacts-import.util';+import { enqueueCallRecordingReconciliations } from 'src/logic-functions/data/enqueue-call-recording-reconciliations.util';import { type ConnectionPage } from 'src/logic-functions/data/fetch-all-nodes.util';+import {+ type CallRecordingRecoveryWork,+ groupRecoveryWorkIntoMinuteSlots,+} from 'src/logic-functions/domain/group-recovery-work-into-minute-slots.util';import { type ConvergeDivergedCallRecordingsResult } from 'src/logic-functions/flows/converge-diverged-call-recordings-result.type';import { isNonEmptyString } from 'src/logic-functions/utils/is-non-empty-string.util';@@ -81,13 +87,12 @@ export const convergeDivergedCallRecordings = async ({throw new Error('Call recording recovery returned an invalid next cursor');}- const importCallRecordingIds: string[] = [];- const reconcilePayloads: Record<string, unknown>[] = [];+ const recoveryWork: CallRecordingRecoveryWork[] = [];const enqueuedCallRecordingIds: string[] = [];for (const { node } of page.edges ?? []) {if (node.status === CallRecordingStatus.PROCESSING) {- importCallRecordingIds.push(node.id);+ recoveryWork.push({ callRecordingId: node.id, kind: 'import' });} else {const startsAt = node.calendarEvent?.startsAt;@@ -98,31 +103,48 @@ export const convergeDivergedCallRecordings = async ({continue;}- reconcilePayloads.push({ callRecordingId: node.id });+ recoveryWork.push({ callRecordingId: node.id, kind: 'reconcile' });}enqueuedCallRecordingIds.push(node.id);}- await enqueueCallRecordingArtifactsImport({- callRecordingIds: importCallRecordingIds,- scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,- trigger: 'recovery',- requestedAt: now.toISOString(),- });- await enqueueLogicFunctionJobs({- logicFunctionUniversalIdentifier:- STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- payloads: reconcilePayloads,- });+ const minuteSlots = groupRecoveryWorkIntoMinuteSlots(recoveryWork);++ for (const [slotIndex, slotWork] of minuteSlots.entries()) {+ const delayMs = slotIndex * MILLISECONDS_PER_MINUTE;++ await enqueueCallRecordingArtifactsImport({+ callRecordingIds: getCallRecordingIdsOfKind(slotWork, 'import'),+ scopes: CALL_RECORDING_ARTIFACT_IMPORT_SCOPES,+ trigger: 'recovery',+ requestedAt: now.toISOString(),+ delayMs,+ });+ await enqueueCallRecordingReconciliations({+ callRecordingIds: getCallRecordingIdsOfKind(slotWork, 'reconcile'),+ recoveryDate: now.toISOString().slice(0, 10),+ delayMs,+ });+ }if (isNonEmptyString(nextCursor)) {+ // Start the next page once this page's Recall calls have drained.await enqueueLogicFunctionJobs({logicFunctionUniversalIdentifier:STALE_BOT_STATE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,payloads: [{ after: nextCursor }],+ delayMs: minuteSlots.length * MILLISECONDS_PER_MINUTE,});}return { candidateCount: page.edges?.length ?? 0, enqueuedCallRecordingIds };};++const getCallRecordingIdsOfKind = (+ recoveryWork: CallRecordingRecoveryWork[],+ kind: CallRecordingRecoveryWork['kind'],+): string[] =>+ recoveryWork+ .filter((work) => work.kind === kind)+ .map(({ callRecordingId }) => callRecordingId);