The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(last-contact): add a health check and run the backfill synchronously (1.6.0) (#26526)
martmull2296f9c3b0e2
diff --git a/packages/twenty-apps/public/last-contact/CHANGELOG.md b/packages/twenty-apps/public/last-contact/CHANGELOG.mdindex e916cdad45c..d7b9970583c 100644--- a/packages/twenty-apps/public/last-contact/CHANGELOG.md+++ b/packages/twenty-apps/public/last-contact/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## 1.6.0++- Run the backfill inside the post-install function instead of enqueuing one job per record batch. The batch jobs ran on the logic function queue, which runs many jobs at once, so their API calls competed for the same rate limit. Post-install hooks run on the application lifecycle queue, one at a time, and the backfill now pages through people, then opportunities, then companies, one batch after the other, within a single 900-second run. Upgrading from 1.5.0 or earlier runs it once. The per-batch logic functions and the `LAST_CONTACT_BACKFILL_SLEEP_MS` server variable are removed.+- Add a health check that shows a warning on the app's settings page when the workspace has no synced emails or meetings, with a button to connect an account.+- Enqueue the manual backfill from the settings page with `enqueueJobs` instead of the deprecated `enqueueJob`.+- Replace deprecated SDK usages: the settings page is a front component pointed at by `defineSettingsMenuItem` instead of a `defineSettingsFrontComponent`, and the application uses `logo` and `galleryImages` instead of `logoUrl` and `screenshots`.+- Require Twenty `>=2.42.0` and move `twenty-sdk` and `twenty-client-sdk` to 2.42.0: health checks, settings menu items and the application lifecycle queue only exist from 2.42.+## 1.4.0- Write a whole batch of records in one API call instead of one call per record. The application API rate limit is consumed once per operation and `updateMany` applies a single payload to everything it matches, so writing one timestamp per person, company or opportunity cost one call each: a full 200-event batch spent 435-585 calls against a budget of 500 per minute shared by every workspace on the instance. Reads are batched the same way, and each handler now costs about nine calls. The recency guard that used to be a filter on the update moved into the read that precedes it, and a record the read does not return is left out of the write rather than upserted back.diff --git a/packages/twenty-apps/public/last-contact/package.json b/packages/twenty-apps/public/last-contact/package.jsonindex 3aa666d77b8..aa1b6bd060e 100644--- a/packages/twenty-apps/public/last-contact/package.json+++ b/packages/twenty-apps/public/last-contact/package.json@@ -1,12 +1,12 @@{"name": "@twentyhq/last-contact",- "version": "1.5.0",+ "version": "1.6.0","license": "MIT","engines": {"node": "^24.5.0","npm": "please-use-yarn","yarn": ">=4.0.2",- "twenty": ">=2.40.0"+ "twenty": ">=2.42.0"},"keywords": ["twenty-app"@@ -29,8 +29,8 @@"oxlint": "^0.16.0","react": "^19.0.0","react-dom": "^19.0.0",- "twenty-client-sdk": "2.40.0",- "twenty-sdk": "2.40.0",+ "twenty-client-sdk": "2.42.0",+ "twenty-sdk": "2.42.0","twenty-ui": "^2.41.0","typescript": "^5.9.3","vite-tsconfig-paths": "^4.2.1",diff --git a/packages/twenty-apps/public/last-contact/src/application-config.ts b/packages/twenty-apps/public/last-contact/src/application-config.tsindex ff966bd582f..ccd45c6a4ff 100644--- a/packages/twenty-apps/public/last-contact/src/application-config.ts+++ b/packages/twenty-apps/public/last-contact/src/application-config.ts@@ -2,9 +2,7 @@ import { defineApplication, FieldType } from 'twenty-sdk/define';import {BACKFILL_BATCH_SIZE_ENV_VAR_NAME,- BACKFILL_SLEEP_MS_ENV_VAR_NAME,DEFAULT_BACKFILL_BATCH_SIZE,- DEFAULT_BACKFILL_SLEEP_MS,} from 'src/constants/backfill';import {APP_DESCRIPTION,@@ -14,20 +12,15 @@ import {export default defineApplication({universalIdentifier: APPLICATION_UNIVERSAL_IDENTIFIER,- logoUrl: 'public/logo.png',+ logo: 'public/logo.png',author: 'Twenty',category: 'Productivity',- screenshots: ['public/gallery/cover.png'],+ galleryImages: ['public/gallery/cover.png'],displayName: APP_DISPLAY_NAME,description: APP_DESCRIPTION,serverVariables: {[BACKFILL_BATCH_SIZE_ENV_VAR_NAME]: {- description: `How many records each last-contact backfill job processes. Also sets how many batch jobs are enqueued (record count divided by this). Defaults to ${DEFAULT_BACKFILL_BATCH_SIZE} when unset.`,- isSecret: false,- type: FieldType.NUMBER,- },- [BACKFILL_SLEEP_MS_ENV_VAR_NAME]: {- description: `How many milliseconds to stagger consecutive backfill jobs by, so they do not all run at once and hit the API rate limiting. Defaults to ${DEFAULT_BACKFILL_SLEEP_MS} when unset.`,+ description: `How many records the last-contact backfill reads and writes per batch. Defaults to ${DEFAULT_BACKFILL_BATCH_SIZE} when unset.`,isSecret: false,type: FieldType.NUMBER,},diff --git a/packages/twenty-apps/public/last-contact/src/constants/backfill.ts b/packages/twenty-apps/public/last-contact/src/constants/backfill.tsindex fc22b95f913..c67d1a87c2d 100644--- a/packages/twenty-apps/public/last-contact/src/constants/backfill.ts+++ b/packages/twenty-apps/public/last-contact/src/constants/backfill.ts@@ -1,9 +1,3 @@-import {- BACKFILL_COMPANIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- BACKFILL_OPPORTUNITIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- BACKFILL_PEOPLE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,-} from 'src/constants/universal-identifiers';-export type BackfillPhase = 'people' | 'opportunities' | 'companies';export const BACKFILL_PHASE_ORDER: BackfillPhase[] = [@@ -12,30 +6,8 @@ export const BACKFILL_PHASE_ORDER: BackfillPhase[] = ['companies',];-// GraphQL query field exposing the record connection for each phase.-export const BACKFILL_PHASE_QUERY_FIELD: Record<BackfillPhase, string> = {- people: 'people',- opportunities: 'opportunities',- companies: 'companies',-};--// Logic function each phase's batch jobs are enqueued against.-export const BACKFILL_PHASE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIERS: Record<- BackfillPhase,- string-> = {- people: BACKFILL_PEOPLE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- opportunities: BACKFILL_OPPORTUNITIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- companies: BACKFILL_COMPANIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,-};--// A batch job resolves the records it owns from this index and the batch size.-export type BackfillBatchPayload = { batchId: number };-// Server variables, injected into process.env on every execution.export const BACKFILL_BATCH_SIZE_ENV_VAR_NAME ='LAST_CONTACT_BACKFILL_BATCH_SIZE';-export const BACKFILL_SLEEP_MS_ENV_VAR_NAME = 'LAST_CONTACT_BACKFILL_SLEEP_MS';export const DEFAULT_BACKFILL_BATCH_SIZE = 200;-export const DEFAULT_BACKFILL_SLEEP_MS = 1_000;diff --git a/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts b/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.tsindex ed3dcc76abc..e222fff1a76 100644--- a/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/last-contact/src/constants/universal-identifiers.ts@@ -13,12 +13,6 @@ export const BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER ='c94f671f-b3fa-47a2-8de6-dde94d13f8d1';export const CALENDAR_EVENT_STARTED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER ='c56013d7-208b-46e2-a91f-27f481645591';-export const BACKFILL_PEOPLE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =- 'a1e15917-86d6-49a4-90d5-6a2555abc6f5';-export const BACKFILL_COMPANIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =- '086d247f-28da-41be-8edd-e6c58592d666';-export const BACKFILL_OPPORTUNITIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =- 'af176746-4334-47f8-a017-88a474a03fa3';export const OPPORTUNITY_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER ='6659b54f-2f46-412b-aa7d-03aa9f1c5133';export const OPPORTUNITY_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =@@ -29,6 +23,13 @@ export const PERSON_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER ='cf7460cc-4c48-4412-9a1a-0c30e4960fce';export const PERSON_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER ='a967064f-f440-43cd-bfbe-907c95d4563f';+export const HEALTH_CHECK_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =+ 'd3b03546-95db-4e20-ab18-eff428bef465';++export const SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER =+ 'fc7e3633-efd9-4d58-a642-39b9b86096d3';+export const SETTINGS_MENU_ITEM_UNIVERSAL_IDENTIFIER =+ '7748d374-01e2-47ba-96fc-cc18a6f9e146';export const LAST_CONTACT_BY_FIELD_UNIVERSAL_IDENTIFIER ='cfdee7bd-8d41-41e6-a888-512705e75d7b';diff --git a/packages/twenty-apps/public/last-contact/src/front-components/last-contact-settings.tsx b/packages/twenty-apps/public/last-contact/src/front-components/last-contact-settings.tsxindex b9bb0bb1050..bcce6d5fad0 100644--- a/packages/twenty-apps/public/last-contact/src/front-components/last-contact-settings.tsx+++ b/packages/twenty-apps/public/last-contact/src/front-components/last-contact-settings.tsx@@ -1,13 +1,16 @@import { useState } from 'react';import { MetadataApiClient } from 'twenty-client-sdk/metadata';-import { defineSettingsFrontComponent } from 'twenty-sdk/define';+import { defineFrontComponent } from 'twenty-sdk/define';import { enqueueSnackbar, t } from 'twenty-sdk/front-component';import { MainButton } from 'twenty-ui/components';import { Section } from 'twenty-ui/primitives/layout';import { H2Title } from 'twenty-ui/primitives/typography';import 'twenty-ui/style.css';-import { BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';+import {+ BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';const LastContactSettings = () => {const [isStarting, setIsStarting] = useState(false);@@ -17,13 +20,12 @@ const LastContactSettings = () => {try {await new MetadataApiClient().mutation({- enqueueJob: {+ enqueueJobs: {__args: {input: {logicFunctionUniversalIdentifier:BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- payload: {},- jobId: 'last-contact-backfill',+ jobs: [{ payload: {}, jobId: 'last-contact-backfill' }],},},enqueued: true,@@ -62,8 +64,8 @@ const LastContactSettings = () => {);};-export default defineSettingsFrontComponent({- universalIdentifier: 'fc7e3633-efd9-4d58-a642-39b9b86096d3',+export default defineFrontComponent({+ universalIdentifier: SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,name: 'last-contact-settings',description: 'Backfill last-contact fields from existing emails and meetings.',component: LastContactSettings,diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.tsnew file mode 100644index 00000000000..b52cea82f5f--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/backfill-last-contact.test.ts@@ -0,0 +1,143 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const {+ queryMock,+ backfillPeopleMock,+ backfillOpportunitiesMock,+ backfillCompaniesMock,+} = vi.hoisted(() => ({+ queryMock: vi.fn(),+ backfillPeopleMock: vi.fn(),+ backfillOpportunitiesMock: vi.fn(),+ backfillCompaniesMock: vi.fn(),+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: vi.fn(function () {+ return { query: queryMock };+ }),+}));++vi.mock('src/utils/backfill-settings', () => ({+ getBackfillBatchSize: () => 2,+}));++vi.mock('src/utils/backfill-people-last-contact', () => ({+ backfillPeopleLastContact: backfillPeopleMock,+}));++vi.mock('src/utils/backfill-opportunities-last-contact', () => ({+ backfillOpportunitiesLastContact: backfillOpportunitiesMock,+}));++vi.mock('src/utils/backfill-companies-last-contact', () => ({+ backfillCompaniesLastContact: backfillCompaniesMock,+}));++import backfillLastContact from '../backfill-last-contact';++type ConnectionQuery = Record<+ string,+ { __args: { first: number; after?: string } }+>;++const RECORDS_BY_QUERY_FIELD: Record<string, Record<string, unknown>[]> = {+ people: [{ id: 'person-1' }, { id: 'person-2' }, { id: 'person-3' }],+ opportunities: [{ id: 'opportunity-1', pointOfContactId: 'person-1' }],+ companies: [],+};++const handler = backfillLastContact.config.handler as (+ payload: object,+) => Promise<object>;++let events: string[] = [];++const recordBatch =+ (phase: string) =>+ async (_client: unknown, records: (string | { id: string })[]) => {+ await Promise.resolve();+ events.push(+ `backfilled ${phase} ${records+ .map((record) => (typeof record === 'string' ? record : record.id))+ .join(',')}`,+ );+ };++beforeEach(() => {+ events = [];++ queryMock.mockReset();+ queryMock.mockImplementation(async (query: ConnectionQuery) => {+ const [queryField] = Object.keys(query);+ const { first, after } = query[queryField].__args;+ const records = RECORDS_BY_QUERY_FIELD[queryField];+ const start = after === undefined ? 0 : Number(after);+ const page = records.slice(start, start + first);+ const end = start + page.length;++ events.push(`read ${queryField} from ${start}`);++ return {+ [queryField]: {+ edges: page.map((node) => ({ node })),+ pageInfo: { hasNextPage: end < records.length, endCursor: `${end}` },+ },+ };+ });++ backfillPeopleMock.mockReset();+ backfillPeopleMock.mockImplementation(recordBatch('people'));+ backfillOpportunitiesMock.mockReset();+ backfillOpportunitiesMock.mockImplementation(recordBatch('opportunities'));+ backfillCompaniesMock.mockReset();+ backfillCompaniesMock.mockImplementation(recordBatch('companies'));+});++describe('backfill-last-contact', () => {+ it('should backfill every batch within the run, one after the other', async () => {+ await expect(handler({ newVersion: '1.6.0' })).resolves.toEqual({+ outcome: 'completed',+ phases: [+ { phase: 'people', count: 3 },+ { phase: 'opportunities', count: 1 },+ { phase: 'companies', count: 0 },+ ],+ });++ expect(events).toEqual([+ 'read people from 0',+ 'backfilled people person-1,person-2',+ 'read people from 2',+ 'backfilled people person-3',+ 'read opportunities from 0',+ 'backfilled opportunities opportunity-1',+ 'read companies from 0',+ ]);+ });++ it('should hand each opportunity to its batch with its point of contact', async () => {+ await handler({ newVersion: '1.6.0' });++ expect(backfillOpportunitiesMock).toHaveBeenCalledWith(expect.anything(), [+ { id: 'opportunity-1', pointOfContactId: 'person-1' },+ ]);+ });++ it.each(['1.4.1', '1.5.0'])(+ 'should backfill on an upgrade from %s to 1.6.0',+ async (previousVersion) => {+ await expect(+ handler({ previousVersion, newVersion: '1.6.0' }),+ ).resolves.toMatchObject({ outcome: 'completed' });+ },+ );++ it('should skip the backfill on an upgrade from 1.6.0', async () => {+ await expect(+ handler({ previousVersion: '1.6.0', newVersion: '1.6.1' }),+ ).resolves.toEqual({});++ expect(queryMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/health-check.test.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/health-check.test.tsnew file mode 100644index 00000000000..691389c811b--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/__tests__/health-check.test.ts@@ -0,0 +1,90 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { queryMock } = vi.hoisted(() => ({+ queryMock: vi.fn(),+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: vi.fn(function () {+ return { query: queryMock };+ }),+}));++import healthCheck from '../health-check';++const buildConnection = (ids: string[]) => ({+ edges: ids.map((id) => ({ node: { id } })),+});++const mockParticipants = ({+ messageParticipantIds,+ calendarEventParticipantIds,+}: {+ messageParticipantIds: string[];+ calendarEventParticipantIds: string[];+}) =>+ queryMock.mockResolvedValue({+ messageParticipants: buildConnection(messageParticipantIds),+ calendarEventParticipants: buildConnection(calendarEventParticipantIds),+ });++beforeEach(() => {+ queryMock.mockReset();+});++describe('health-check', () => {+ it('should be a valid health check', () => {+ expect(healthCheck.success).toBe(true);+ });++ it('should report nothing once emails are synced', async () => {+ mockParticipants({+ messageParticipantIds: ['message-participant-1'],+ calendarEventParticipantIds: [],+ });++ await expect(healthCheck.config.handler()).resolves.toEqual({+ status: 'OK',+ });+ });++ it('should report nothing once meetings are synced', async () => {+ mockParticipants({+ messageParticipantIds: [],+ calendarEventParticipantIds: ['calendar-event-participant-1'],+ });++ await expect(healthCheck.config.handler()).resolves.toEqual({+ status: 'OK',+ });+ });++ it('should ask to connect an account when nothing is synced', async () => {+ mockParticipants({+ messageParticipantIds: [],+ calendarEventParticipantIds: [],+ });++ await expect(healthCheck.config.handler()).resolves.toEqual({+ status: 'WARNING',+ title: 'No synced emails or meetings yet',+ description: expect.stringContaining('Connect a mailbox or calendar'),+ action: { label: 'Connect an account', location: '/settings/accounts' },+ });+ });++ it('should read a single participant of each kind', async () => {+ mockParticipants({+ messageParticipantIds: [],+ calendarEventParticipantIds: [],+ });++ await healthCheck.config.handler();++ expect(queryMock).toHaveBeenCalledTimes(1);+ expect(queryMock.mock.calls[0][0]).toMatchObject({+ messageParticipants: { __args: { first: 1 } },+ calendarEventParticipants: { __args: { first: 1 } },+ });+ });+});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.tsdeleted file mode 100644index 531f9b24201..00000000000--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-companies-last-contact.ts+++ /dev/null@@ -1,73 +0,0 @@-import { CoreApiClient } from 'twenty-client-sdk/core';-import { defineLogicFunction } from 'twenty-sdk/define';--import { type BackfillBatchPayload } from 'src/constants/backfill';-import { BACKFILL_COMPANIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { buildBackfillBatchArgs } from 'src/utils/backfill-batch-args';-import { getBackfillBatchSize } from 'src/utils/backfill-settings';-import { collectPeopleByCompany } from 'src/utils/collect-people-by-company';-import { executeWithRetry } from 'src/utils/execute-with-retry';-import {- buildRelatedUpdateData,- buildPersonAggregates,- pickLatestLastContact,- pickPersonLastContact,-} from 'src/utils/person-last-contact-aggregation';-import {- type RecordUpsert,- upsertRecordsInBatches,-} from 'src/utils/upsert-records-in-batches';--const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {- const client = new CoreApiClient();-- const { companies } = await executeWithRetry(() =>- client.query({- companies: {- __args: buildBackfillBatchArgs(batchId, getBackfillBatchSize()),- edges: { node: { id: true } },- },- }),- );-- const companyIds = (companies?.edges ?? [])- .map((edge: { node: { id: string } }) => edge.node.id)- .filter(Boolean);-- if (companyIds.length === 0) {- return { batchId, count: 0 };- }-- const peopleByCompanyId = await collectPeopleByCompany(client, companyIds);- const personIds = [...new Set([...peopleByCompanyId.values()].flat())];- const aggByPersonId = await buildPersonAggregates(client, personIds);-- const upserts: RecordUpsert[] = [];-- for (const companyId of companyIds) {- const lastContact = pickLatestLastContact(- (peopleByCompanyId.get(companyId) ?? [])- .map((personId) => pickPersonLastContact(aggByPersonId.get(personId)))- .filter((contact) => contact !== undefined),- );-- if (!lastContact) {- continue;- }-- upserts.push({ id: companyId, ...buildRelatedUpdateData(lastContact) });- }-- await upsertRecordsInBatches(client, 'createCompanies', upserts);-- return { batchId, count: companyIds.length };-};--export default defineLogicFunction({- universalIdentifier: BACKFILL_COMPANIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- name: 'backfill-companies-last-contact',- description:- 'Backfills last-contact fields for one batch of companies from the most recent contact of their people, resolved from the batch id in its payload.',- timeoutSeconds: 120,- handler,-});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.tsindex 2771882920c..0aab74536ca 100644--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-last-contact.ts@@ -3,11 +3,8 @@ import { definePostInstallLogicFunction, type InstallPayload } from 'twenty-sdk/import { compare } from 'semver'import { BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import {- getBackfillBatchSize,- getBackfillSleepMs,-} from 'src/utils/backfill-settings';-import { enqueueBackfillJobs } from 'src/utils/enqueue-backfill-jobs';+import { getBackfillBatchSize } from 'src/utils/backfill-settings';+import { runLastContactBackfill } from 'src/utils/run-last-contact-backfill';import { isDefined } from 'twenty-sdk/utils';const shouldRunPostInstall = ({@@ -18,7 +15,7 @@ const shouldRunPostInstall = ({return true;}- if (compare(previousVersion, "1.4.1") <= 0 && compare(newVersion, "1.5.0") >= 1) { // Rate limitation fix+ if (compare(previousVersion, "1.5.0") <= 0 && compare(newVersion, "1.6.0") >= 0) { // Rate limitation fixreturn true;}@@ -40,23 +37,20 @@ const handler = async ({console.log('Backfill params',- JSON.stringify({- batchSize: getBackfillBatchSize(),- sleepMs: getBackfillSleepMs(),- }),+ JSON.stringify({ batchSize: getBackfillBatchSize() }),);- const plans = await enqueueBackfillJobs(new CoreApiClient());+ const phases = await runLastContactBackfill(new CoreApiClient());- return { outcome: 'enqueued', plans };+ return { outcome: 'completed', phases };};export default definePostInstallLogicFunction({universalIdentifier: BACKFILL_POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,name: 'backfill-last-contact',description:- 'Counts people, opportunities and companies after installation and enqueues one backfill job per record batch.',- timeoutSeconds: 300,+ 'Backfills last-contact fields on people, then opportunities, then companies after installation, one batch of records at a time within this run.',+ timeoutSeconds: 900,shouldRunOnVersionUpgrade: true,handler,});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.tsdeleted file mode 100644index 77e0adf48fe..00000000000--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-opportunities-last-contact.ts+++ /dev/null@@ -1,77 +0,0 @@-import { CoreApiClient } from 'twenty-client-sdk/core';-import { defineLogicFunction } from 'twenty-sdk/define';--import { type BackfillBatchPayload } from 'src/constants/backfill';-import { BACKFILL_OPPORTUNITIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { buildBackfillBatchArgs } from 'src/utils/backfill-batch-args';-import { getBackfillBatchSize } from 'src/utils/backfill-settings';-import { executeWithRetry } from 'src/utils/execute-with-retry';-import {- buildRelatedUpdateData,- buildPersonAggregates,- pickPersonLastContact,-} from 'src/utils/person-last-contact-aggregation';-import {- type RecordUpsert,- upsertRecordsInBatches,-} from 'src/utils/upsert-records-in-batches';--type OpportunityNode = { id: string; pointOfContactId: string | null };--const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {- const client = new CoreApiClient();-- const { opportunities } = await executeWithRetry(() =>- client.query({- opportunities: {- __args: buildBackfillBatchArgs(batchId, getBackfillBatchSize()),- edges: { node: { id: true, pointOfContactId: true } },- },- }),- );-- const nodes: OpportunityNode[] = (opportunities?.edges ?? [])- .map((edge: { node: OpportunityNode }) => edge.node)- .filter((node: OpportunityNode) => Boolean(node.id));-- if (nodes.length === 0) {- return { batchId, count: 0 };- }-- const personIds = [- ...new Set(- nodes- .map((node) => node.pointOfContactId)- .filter((id): id is string => Boolean(id)),- ),- ];- const aggByPersonId = await buildPersonAggregates(client, personIds);-- const upserts: RecordUpsert[] = [];-- for (const node of nodes) {- const lastContact = node.pointOfContactId- ? pickPersonLastContact(aggByPersonId.get(node.pointOfContactId))- : undefined;-- if (!lastContact) {- continue;- }-- upserts.push({ id: node.id, ...buildRelatedUpdateData(lastContact) });- }-- await upsertRecordsInBatches(client, 'createOpportunities', upserts);-- return { batchId, count: nodes.length };-};--export default defineLogicFunction({- universalIdentifier:- BACKFILL_OPPORTUNITIES_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- name: 'backfill-opportunities-last-contact',- description:- 'Backfills last-contact fields for one batch of opportunities from their point of contact, resolved from the batch id in its payload.',- timeoutSeconds: 120,- handler,-});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.tsdeleted file mode 100644index ba773a0496b..00000000000--- a/packages/twenty-apps/public/last-contact/src/logic-functions/backfill-people-last-contact.ts+++ /dev/null@@ -1,64 +0,0 @@-import { CoreApiClient } from 'twenty-client-sdk/core';-import { defineLogicFunction } from 'twenty-sdk/define';--import { type BackfillBatchPayload } from 'src/constants/backfill';-import { BACKFILL_PEOPLE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';-import { buildBackfillBatchArgs } from 'src/utils/backfill-batch-args';-import { getBackfillBatchSize } from 'src/utils/backfill-settings';-import { executeWithRetry } from 'src/utils/execute-with-retry';-import {- buildPersonAggregates,- buildPersonUpdateData,-} from 'src/utils/person-last-contact-aggregation';-import {- type RecordUpsert,- upsertRecordsInBatches,-} from 'src/utils/upsert-records-in-batches';--const handler = async ({ batchId }: BackfillBatchPayload): Promise<object> => {- const client = new CoreApiClient();-- const { people } = await executeWithRetry(() =>- client.query({- people: {- __args: buildBackfillBatchArgs(batchId, getBackfillBatchSize()),- edges: { node: { id: true } },- },- }),- );-- const personIds = (people?.edges ?? [])- .map((edge: { node: { id: string } }) => edge.node.id)- .filter(Boolean);-- if (personIds.length === 0) {- return { batchId, count: 0 };- }-- const aggByPersonId = await buildPersonAggregates(client, personIds);- const upserts: RecordUpsert[] = [];-- for (const personId of personIds) {- const agg = aggByPersonId.get(personId);- const data = agg ? buildPersonUpdateData(agg) : {};-- if (Object.keys(data).length === 0) {- continue;- }-- upserts.push({ id: personId, ...data });- }-- await upsertRecordsInBatches(client, 'createPeople', upserts);-- return { batchId, count: personIds.length };-};--export default defineLogicFunction({- universalIdentifier: BACKFILL_PEOPLE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,- name: 'backfill-people-last-contact',- description:- 'Backfills last-contact fields for one batch of people, resolved from the batch id in its payload.',- timeoutSeconds: 120,- handler,-});diff --git a/packages/twenty-apps/public/last-contact/src/logic-functions/health-check.ts b/packages/twenty-apps/public/last-contact/src/logic-functions/health-check.tsnew file mode 100644index 00000000000..780aef09b7b--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/logic-functions/health-check.ts@@ -0,0 +1,45 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import {+ type ApplicationHealthCheckResult,+ defineHealthCheck,+} from 'twenty-sdk/define';++import { HEALTH_CHECK_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';++const handler = async (): Promise<ApplicationHealthCheckResult> => {+ const { messageParticipants, calendarEventParticipants } =+ await new CoreApiClient().query({+ messageParticipants: {+ __args: { first: 1 },+ edges: { node: { id: true } },+ },+ calendarEventParticipants: {+ __args: { first: 1 },+ edges: { node: { id: true } },+ },+ });++ if (+ (messageParticipants?.edges ?? []).length > 0 ||+ (calendarEventParticipants?.edges ?? []).length > 0+ ) {+ return { status: 'OK' };+ }++ return {+ status: 'WARNING',+ title: 'No synced emails or meetings yet',+ description:+ 'Last contact is computed from synced emails and meetings. Connect a mailbox or calendar to start tracking it.',+ action: { label: 'Connect an account', location: '/settings/accounts' },+ };+};++export default defineHealthCheck({+ universalIdentifier: HEALTH_CHECK_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,+ name: 'health-check',+ description:+ 'Warns on the app settings page when the workspace has no synced emails or meetings, since every last-contact field is computed from them.',+ timeoutSeconds: 30,+ handler,+});diff --git a/packages/twenty-apps/public/last-contact/src/settings-menu-items/last-contact-settings.ts b/packages/twenty-apps/public/last-contact/src/settings-menu-items/last-contact-settings.tsnew file mode 100644index 00000000000..633fe355c81--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/settings-menu-items/last-contact-settings.ts@@ -0,0 +1,14 @@+import { defineSettingsMenuItem } from 'twenty-sdk/define';++import {+ SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ SETTINGS_MENU_ITEM_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';++export default defineSettingsMenuItem({+ universalIdentifier: SETTINGS_MENU_ITEM_UNIVERSAL_IDENTIFIER,+ frontComponentUniversalIdentifier:+ SETTINGS_FRONT_COMPONENT_UNIVERSAL_IDENTIFIER,+ title: 'Settings',+ icon: 'IconAdjustments',+});diff --git a/packages/twenty-apps/public/last-contact/src/utils/__tests__/enqueue-backfill-jobs.test.ts b/packages/twenty-apps/public/last-contact/src/utils/__tests__/enqueue-backfill-jobs.test.tsdeleted file mode 100644index cd05898d442..00000000000--- a/packages/twenty-apps/public/last-contact/src/utils/__tests__/enqueue-backfill-jobs.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import { expect, it, vi } from 'vitest';--const { queryMock, enqueueJobMock } = vi.hoisted(() => ({- queryMock: vi.fn(),- enqueueJobMock: vi.fn().mockResolvedValue({ enqueued: true }),-}));--vi.mock('twenty-client-sdk/core', () => ({- CoreApiClient: vi.fn(function () {- return { query: queryMock };- }),-}));--vi.mock('twenty-sdk/logic-function', () => ({- enqueueJob: enqueueJobMock,-}));--vi.mock('src/utils/backfill-settings', () => ({- getBackfillBatchSize: () => 200,- getBackfillSleepMs: () => 1_000,-}));--import backfillLastContact from 'src/logic-functions/backfill-last-contact';--it('allows a manual backfill and reuses distinct job IDs for each phase and batch', async () => {- queryMock.mockImplementation(async (query) => ({- [Object.keys(query)[0]]: { totalCount: 201 },- }));-- const handler = backfillLastContact.config.handler as (- payload: object,- ) => Promise<object>;-- await handler({});-- const firstRunJobs = enqueueJobMock.mock.calls.map(([job]) => job);-- expect(firstRunJobs.map((job) => job.jobId)).toEqual([- 'last-contact-backfill-people-200-0',- 'last-contact-backfill-people-200-1',- 'last-contact-backfill-opportunities-200-0',- 'last-contact-backfill-opportunities-200-1',- 'last-contact-backfill-companies-200-0',- 'last-contact-backfill-companies-200-1',- ]);-- enqueueJobMock.mockClear();- await handler({});-- expect(enqueueJobMock.mock.calls.map(([job]) => job)).toEqual(firstRunJobs);-});diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-batch-args.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-batch-args.tsdeleted file mode 100644index c7f6a840e68..00000000000--- a/packages/twenty-apps/public/last-contact/src/utils/backfill-batch-args.ts+++ /dev/null@@ -1,17 +0,0 @@-// A total order over createdAt then id keeps offset windows stable while the-// backfill runs: newly created records sort to the tail, so the batch each job-// owns does not shift under it.-const BACKFILL_ORDER_BY = [- { createdAt: 'AscNullsFirst' },- { id: 'AscNullsFirst' },-];--// Query args selecting the record window a batch job owns.-export const buildBackfillBatchArgs = (- batchId: number,- batchSize: number,-): { first: number; offset: number; orderBy: typeof BACKFILL_ORDER_BY } => ({- first: batchSize,- offset: batchId * batchSize,- orderBy: BACKFILL_ORDER_BY,-});diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-companies-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-companies-last-contact.tsnew file mode 100644index 00000000000..f481506a5ba--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/backfill-companies-last-contact.ts@@ -0,0 +1,40 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { collectPeopleByCompany } from 'src/utils/collect-people-by-company';+import {+ buildRelatedUpdateData,+ buildPersonAggregates,+ pickLatestLastContact,+ pickPersonLastContact,+} from 'src/utils/person-last-contact-aggregation';+import {+ type RecordUpsert,+ upsertRecordsInBatches,+} from 'src/utils/upsert-records-in-batches';++export const backfillCompaniesLastContact = async (+ client: CoreApiClient,+ companyIds: string[],+): Promise<void> => {+ const peopleByCompanyId = await collectPeopleByCompany(client, companyIds);+ const personIds = [...new Set([...peopleByCompanyId.values()].flat())];+ const aggByPersonId = await buildPersonAggregates(client, personIds);++ const upserts: RecordUpsert[] = [];++ for (const companyId of companyIds) {+ const lastContact = pickLatestLastContact(+ (peopleByCompanyId.get(companyId) ?? [])+ .map((personId) => pickPersonLastContact(aggByPersonId.get(personId)))+ .filter((contact) => contact !== undefined),+ );++ if (!lastContact) {+ continue;+ }++ upserts.push({ id: companyId, ...buildRelatedUpdateData(lastContact) });+ }++ await upsertRecordsInBatches(client, 'createCompanies', upserts);+};diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-opportunities-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-opportunities-last-contact.tsnew file mode 100644index 00000000000..89ec7046987--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/backfill-opportunities-last-contact.ts@@ -0,0 +1,43 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import {+ buildRelatedUpdateData,+ buildPersonAggregates,+ pickPersonLastContact,+} from 'src/utils/person-last-contact-aggregation';+import {+ type RecordUpsert,+ upsertRecordsInBatches,+} from 'src/utils/upsert-records-in-batches';++export type OpportunityNode = { id: string; pointOfContactId: string | null };++export const backfillOpportunitiesLastContact = async (+ client: CoreApiClient,+ nodes: OpportunityNode[],+): Promise<void> => {+ const personIds = [+ ...new Set(+ nodes+ .map((node) => node.pointOfContactId)+ .filter((id): id is string => Boolean(id)),+ ),+ ];+ const aggByPersonId = await buildPersonAggregates(client, personIds);++ const upserts: RecordUpsert[] = [];++ for (const node of nodes) {+ const lastContact = node.pointOfContactId+ ? pickPersonLastContact(aggByPersonId.get(node.pointOfContactId))+ : undefined;++ if (!lastContact) {+ continue;+ }++ upserts.push({ id: node.id, ...buildRelatedUpdateData(lastContact) });+ }++ await upsertRecordsInBatches(client, 'createOpportunities', upserts);+};diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.tsnew file mode 100644index 00000000000..076e446f074--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/backfill-people-last-contact.ts@@ -0,0 +1,31 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import {+ buildPersonAggregates,+ buildPersonUpdateData,+} from 'src/utils/person-last-contact-aggregation';+import {+ type RecordUpsert,+ upsertRecordsInBatches,+} from 'src/utils/upsert-records-in-batches';++export const backfillPeopleLastContact = async (+ client: CoreApiClient,+ personIds: string[],+): Promise<void> => {+ const aggByPersonId = await buildPersonAggregates(client, personIds);+ const upserts: RecordUpsert[] = [];++ for (const personId of personIds) {+ const agg = aggByPersonId.get(personId);+ const data = agg ? buildPersonUpdateData(agg) : {};++ if (Object.keys(data).length === 0) {+ continue;+ }++ upserts.push({ id: personId, ...data });+ }++ await upsertRecordsInBatches(client, 'createPeople', upserts);+};diff --git a/packages/twenty-apps/public/last-contact/src/utils/backfill-settings.ts b/packages/twenty-apps/public/last-contact/src/utils/backfill-settings.tsindex 279854857f4..0e50193dbce 100644--- a/packages/twenty-apps/public/last-contact/src/utils/backfill-settings.ts+++ b/packages/twenty-apps/public/last-contact/src/utils/backfill-settings.ts@@ -1,8 +1,6 @@import {BACKFILL_BATCH_SIZE_ENV_VAR_NAME,- BACKFILL_SLEEP_MS_ENV_VAR_NAME,DEFAULT_BACKFILL_BATCH_SIZE,- DEFAULT_BACKFILL_SLEEP_MS,} from 'src/constants/backfill';// Application and server variables are injected into process.env on every@@ -26,6 +24,3 @@ const readPositiveInteger = (export const getBackfillBatchSize = (): number =>readPositiveInteger(BACKFILL_BATCH_SIZE_ENV_VAR_NAME, DEFAULT_BACKFILL_BATCH_SIZE);--export const getBackfillSleepMs = (): number =>- readPositiveInteger(BACKFILL_SLEEP_MS_ENV_VAR_NAME, DEFAULT_BACKFILL_SLEEP_MS);diff --git a/packages/twenty-apps/public/last-contact/src/utils/enqueue-backfill-jobs.ts b/packages/twenty-apps/public/last-contact/src/utils/enqueue-backfill-jobs.tsdeleted file mode 100644index 01895ae4258..00000000000--- a/packages/twenty-apps/public/last-contact/src/utils/enqueue-backfill-jobs.ts+++ /dev/null@@ -1,71 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';-import { enqueueJob } from 'twenty-sdk/logic-function';--import {- type BackfillPhase,- BACKFILL_PHASE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIERS,- BACKFILL_PHASE_ORDER,- BACKFILL_PHASE_QUERY_FIELD,-} from 'src/constants/backfill';-import {- getBackfillBatchSize,- getBackfillSleepMs,-} from 'src/utils/backfill-settings';-import { executeWithRetry } from 'src/utils/execute-with-retry';--// enqueueJob rejects delays beyond 7 days.-const MAX_ENQUEUE_DELAY_MS = 7 * 24 * 60 * 60 * 1_000;--// Batch handlers are idempotent (they recompute from source and overwrite), so-// a batch that dies mid-run can safely be retried by the queue rather than-// leaving its records unbackfilled.-const BACKFILL_JOB_RETRY_LIMIT = 3;--type BackfillPhasePlan = { phase: BackfillPhase; count: number; batches: number };--const countPhaseRecords = async (- client: CoreApiClient,- phase: BackfillPhase,-): Promise<number> => {- const field = BACKFILL_PHASE_QUERY_FIELD[phase];-- const result = await executeWithRetry(() =>- client.query({ [field]: { __args: { first: 1 }, totalCount: true } }),- );-- return result?.[field]?.totalCount ?? 0;-};--// Counts every phase, then enqueues one job per record batch across all phases.-// Jobs are spaced by delayMs so thousands of batches do not all become eligible-// at once and overwhelm the API rate limiting.-export const enqueueBackfillJobs = async (- client: CoreApiClient,-): Promise<BackfillPhasePlan[]> => {- const batchSize = getBackfillBatchSize();- const sleepMs = getBackfillSleepMs();-- const plans: BackfillPhasePlan[] = [];- let enqueuedCount = 0;-- for (const phase of BACKFILL_PHASE_ORDER) {- const count = await countPhaseRecords(client, phase);- const batches = Math.ceil(count / batchSize);-- for (let batchId = 0; batchId < batches; batchId++) {- await enqueueJob({- logicFunctionUniversalIdentifier:- BACKFILL_PHASE_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIERS[phase],- payload: { batchId },- jobId: `last-contact-backfill-${phase}-${batchSize}-${batchId}`,- delayMs: Math.min(enqueuedCount * sleepMs, MAX_ENQUEUE_DELAY_MS),- retryLimit: BACKFILL_JOB_RETRY_LIMIT,- });- enqueuedCount++;- }-- plans.push({ phase, count, batches });- }-- return plans;-};diff --git a/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.ts b/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.tsnew file mode 100644index 00000000000..508fae0c165--- /dev/null+++ b/packages/twenty-apps/public/last-contact/src/utils/run-last-contact-backfill.ts@@ -0,0 +1,125 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import {+ type BackfillPhase,+ BACKFILL_PHASE_ORDER,+} from 'src/constants/backfill';+import { backfillCompaniesLastContact } from 'src/utils/backfill-companies-last-contact';+import {+ backfillOpportunitiesLastContact,+ type OpportunityNode,+} from 'src/utils/backfill-opportunities-last-contact';+import { backfillPeopleLastContact } from 'src/utils/backfill-people-last-contact';+import { getBackfillBatchSize } from 'src/utils/backfill-settings';+import { executeWithRetry } from 'src/utils/execute-with-retry';++// A total order over createdAt then id keeps the cursor stable while the+// backfill runs: records created meanwhile sort to the tail.+const BACKFILL_ORDER_BY = [+ { createdAt: 'AscNullsFirst' },+ { id: 'AscNullsFirst' },+];++export type BackfillPhaseResult = { phase: BackfillPhase; count: number };++const backfillRecordsInBatches = async <TRecord extends { id: string }>({+ client,+ queryField,+ recordSelection,+ batchSize,+ backfillBatch,+}: {+ client: CoreApiClient;+ queryField: string;+ recordSelection: Record<keyof TRecord, true>;+ batchSize: number;+ backfillBatch: (records: TRecord[]) => Promise<void>;+}): Promise<number> => {+ let count = 0;+ let after: string | undefined;++ do {+ const result = await executeWithRetry(() =>+ client.query({+ [queryField]: {+ __args: { first: batchSize, after, orderBy: BACKFILL_ORDER_BY },+ edges: { node: recordSelection },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ }),+ );+ const connection = result?.[queryField];+ const records: TRecord[] = (connection?.edges ?? []).map(+ (edge: { node: TRecord }) => edge.node,+ );++ if (records.length > 0) {+ await backfillBatch(records);+ count += records.length;+ }++ after = connection?.pageInfo.hasNextPage+ ? (connection.pageInfo.endCursor ?? undefined)+ : undefined;+ } while (after);++ return count;+};++const BACKFILL_PHASE_RUNNERS: Record<+ BackfillPhase,+ (client: CoreApiClient, batchSize: number) => Promise<number>+> = {+ people: (client, batchSize) =>+ backfillRecordsInBatches<{ id: string }>({+ client,+ queryField: 'people',+ recordSelection: { id: true },+ batchSize,+ backfillBatch: (people) =>+ backfillPeopleLastContact(+ client,+ people.map(({ id }) => id),+ ),+ }),+ opportunities: (client, batchSize) =>+ backfillRecordsInBatches<OpportunityNode>({+ client,+ queryField: 'opportunities',+ recordSelection: { id: true, pointOfContactId: true },+ batchSize,+ backfillBatch: (opportunities) =>+ backfillOpportunitiesLastContact(client, opportunities),+ }),+ companies: (client, batchSize) =>+ backfillRecordsInBatches<{ id: string }>({+ client,+ queryField: 'companies',+ recordSelection: { id: true },+ batchSize,+ backfillBatch: (companies) =>+ backfillCompaniesLastContact(+ client,+ companies.map(({ id }) => id),+ ),+ }),+};++// Processes every batch in this execution, one after the other, so the+// backfill's API calls stay sequential instead of spreading across concurrent+// jobs that compete for the same rate limit.+export const runLastContactBackfill = async (+ client: CoreApiClient,+): Promise<BackfillPhaseResult[]> => {+ const batchSize = getBackfillBatchSize();+ const results: BackfillPhaseResult[] = [];++ for (const phase of BACKFILL_PHASE_ORDER) {+ const count = await BACKFILL_PHASE_RUNNERS[phase](client, batchSize);++ console.log(`Backfilled last contact on ${count} ${phase}`);+ results.push({ phase, count });+ }++ return results;+};diff --git a/packages/twenty-apps/public/last-contact/yarn.lock b/packages/twenty-apps/public/last-contact/yarn.lockindex 9479baa7902..9fe86b532ab 100644--- a/packages/twenty-apps/public/last-contact/yarn.lock+++ b/packages/twenty-apps/public/last-contact/yarn.lock@@ -1110,8 +1110,8 @@ __metadata:react: "npm:^19.0.0"react-dom: "npm:^19.0.0"semver: "npm:^7.8.5"- twenty-client-sdk: "npm:2.40.0"- twenty-sdk: "npm:2.40.0"+ twenty-client-sdk: "npm:2.42.0"+ twenty-sdk: "npm:2.42.0"twenty-ui: "npm:^2.41.0"typescript: "npm:^5.9.3"vite-tsconfig-paths: "npm:^4.2.1"@@ -3136,22 +3136,22 @@ __metadata:languageName: nodelinkType: hard-"twenty-client-sdk@npm:2.40.0":- version: 2.40.0- resolution: "twenty-client-sdk@npm:2.40.0"+"twenty-client-sdk@npm:2.42.0":+ version: 2.42.0+ resolution: "twenty-client-sdk@npm:2.42.0"dependencies:"@genql/runtime": "npm:^2.10.0"esbuild: "npm:^0.28.1"graphql: "npm:^16.8.1"lodash: "npm:^4.17.21"prettier: "npm:^3.8.3"- checksum: 10c0/60d046ffe7aa289607933e9442fed05f9f8e97b64d6acbe3bbcfe065184cd6c76e86fcc6530d609d6f54d600b5302b2ac709ffddd16737d2e83f3d56b67256c0+ checksum: 10c0/38f77595ffc2bb365cef23a30d7ab7096fcf129d407921bb97497327da27526e9721ba6a1a16d299bd9b3a2e3f0eeac3fb41ec360c0547e7a2c0f0c044cc570blanguageName: nodelinkType: hard-"twenty-sdk@npm:2.40.0":- version: 2.40.0- resolution: "twenty-sdk@npm:2.40.0"+"twenty-sdk@npm:2.42.0":+ version: 2.42.0+ resolution: "twenty-sdk@npm:2.42.0"dependencies:"@sniptt/guards": "npm:^0.2.0"axios: "npm:^1.16.0"@@ -3170,12 +3170,12 @@ __metadata:semver: "npm:7.6.3"sharp: "npm:^0.35.3"tinyglobby: "npm:^0.2.15"- twenty-client-sdk: "npm:2.40.0"+ twenty-client-sdk: "npm:2.42.0"typescript: "npm:^5.9.3"uuid: "npm:^13.0.2"bin:twenty: dist/cli.cjs- checksum: 10c0/74fab301ba98f17ad16396eb48a55af43ea8d4583e8e863c4248774962dce5a272fcb24ae78c8214f2997c9146b3815e1542c202d52ed89d035550eaa8151d96+ checksum: 10c0/1e43d0c2af55ab8705506f55fe693688575325e506b6cfb16ba4d486d0bfdc0c0f257fc8963ee86f218c10d09b87bacdc769803b6b59283f9e24c7a88346fb84languageName: nodelinkType: hard