:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cdp): look up cohort trigger workflows once per batch (#118407)
Harley Alexander40232a1adeb4
diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.tsindex d57402212350..7716512c79f9 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts@@ -120,7 +120,7 @@ describe('CdpCohortMembershipTriggerConsumer', () => {)it('fails the batch when loading workflows fails, so the change is retried', async () => {- jest.spyOn(processor['hogFlowManager'], 'getHogFlowsForTeam').mockRejectedValue(+ jest.spyOn(processor['hogFlowManager'], 'getHogFlowsForTeams').mockRejectedValue(new Error('canceling statement due to conflict with recovery'))const change = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })@@ -128,6 +128,20 @@ describe('CdpCohortMembershipTriggerConsumer', () => {await expect(processor._parseKafkaBatch([createKafkaMessage(change)])).rejects.toThrow('conflict with recovery')})+ it("loads a team's workflows once per batch, however many changes the batch holds for it", async () => {+ await insertHogFlow(hub.postgres, cohortFlow(42, 'entered'))+ const lookup = jest.spyOn(processor['hogFlowManager'], 'getHogFlowsForTeams')+ const messages = [1, 2, 3].map(() =>+ createKafkaMessage(createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' }))+ )++ const globals = await processor._parseKafkaBatch(messages)++ expect(globals).toHaveLength(3)+ expect(lookup).toHaveBeenCalledTimes(1)+ expect(lookup).toHaveBeenCalledWith([team.id])+ })+it.each(['seed', 'reconcile'])('starts no run for a %s message', async (origin) => {await insertHogFlow(hub.postgres, cohortFlow(42, 'entered'))const change = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered', origin })diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.tsindex 1f15e198a21f..12fbe14ec8d8 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts@@ -155,28 +155,35 @@ export class CdpCohortMembershipTriggerConsumer extends CdpConsumerBase {@instrumented('cdpConsumer.handleEachBatch.parseKafkaMessages')public async _parseKafkaBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {- const events: HogFunctionInvocationGlobals[] = []- await Promise.all(- messages.map(async (message) => {- let change: CohortMembershipChange- try {- change = CohortMembershipChangeSchema.parse(parseJSON(message.value!.toString()))- } catch (e) {- logger.error('Error parsing cohort membership change', e)- counterParseError.labels({ error: e.message }).inc()- return- }+ const changes: CohortMembershipChange[] = []+ for (const message of messages) {+ let change: CohortMembershipChange+ try {+ change = CohortMembershipChangeSchema.parse(parseJSON(message.value!.toString()))+ } catch (e) {+ logger.error('Error parsing cohort membership change', e)+ counterParseError.labels({ error: e.message }).inc()+ continue+ }++ // Seed and reconcile messages restate membership the cohort already had. Starting runs+ // on them would put every existing member through the workflow when a cohort is built.+ if (change.origin) {+ counterCohortMembershipTriggerSkipped.labels({ reason: 'backfill' }).inc()+ continue+ }+ changes.push(change)+ }- // Seed and reconcile messages restate membership the cohort already had. Starting runs- // on them would put every existing member through the workflow when a cohort is built.- if (change.origin) {- counterCohortMembershipTriggerSkipped.labels({ reason: 'backfill' }).inc()- return- }+ // One lookup per team per batch: a cohort recompute fills whole batches with one team's changes.+ // Load errors propagate, so the batch fails, the offsets stay put and the consumer retries.+ const teamIds = [...new Set(changes.map((change) => change.team_id))]+ const hogFlowsByTeam = await this.hogFlowManager.getHogFlowsForTeams(teamIds)- // Load errors propagate, so the batch fails, the offsets stay put and the consumer retries.- const teamHogFlows = await this.hogFlowManager.getHogFlowsForTeam(change.team_id)- const triggered = teamHogFlows.some(+ const events: HogFunctionInvocationGlobals[] = []+ await Promise.all(+ changes.map(async (change) => {+ const triggered = (hogFlowsByTeam[change.team_id] ?? []).some((flow) => flow.trigger.type === 'cohort' && flow.trigger.cohort_id === change.cohort_id)if (!triggered) {