: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
feat(cdp): start workflow runs from realtime cohort membership changes (#116951)
Harley Alexander9e950f7606ed
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.tsindex 7aa0daeb6e37..3cb41d31f8b7 100644--- a/nodejs/src/capabilities.ts+++ b/nodejs/src/capabilities.ts@@ -30,6 +30,7 @@ export const CAPABILITIES_CDP_WORKFLOWS: PluginServerCapabilities = {cdpCyclotronV2Janitor: isDevEnv(),cdpHogflowScheduler: isDevEnv(),cdpHogflowSubscriptionMatcher: isDevEnv(),+ cdpCohortMembershipTriggers: true,}/** Realtime Cohorts - cohort membership persistence */@@ -143,6 +144,10 @@ export function getPluginServerCapabilities(return {cdpCohortMembership: true,}+ case PluginServerMode.cdp_cohort_membership_triggers:+ return {+ cdpCohortMembershipTriggers: true,+ }case PluginServerMode.cdp_legacy_on_event:return {cdpLegacyOnEvent: true,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.tsnew file mode 100644index 000000000000..3de10fda4ffe--- /dev/null+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.test.ts@@ -0,0 +1,85 @@+import '../../../tests/helpers/mocks/consumer.mock'+import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'+import '../../../tests/helpers/mocks/producer.mock'++import { HogFlow } from '~/cdp/schema/hogflow'+import { closeHub, createHub } from '~/common/utils/db/hub'++import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'+import { createTestTeamFixture } from '../../../tests/helpers/sql'+import { Hub, Team } from '../../types'+import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'+import { createCohortMembershipEvent, createKafkaMessage } from '../_tests/fixtures'+import { insertHogFlow } from '../_tests/fixtures-hogflows'+import { CyclotronJobInvocationHogFlow } from '../types'+import {+ COHORT_MEMBERSHIP_CHANGED_EVENT,+ CdpCohortMembershipTriggerConsumer,+} from './cdp-cohort-membership-trigger.consumer'++describe('CdpCohortMembershipTriggerConsumer', () => {+ let processor: CdpCohortMembershipTriggerConsumer+ let hub: Hub+ let team: Team+ let mockQueueInvocations: jest.MockedFunction<any>++ const cohortFlow = (cohortId: number, transition: 'entered' | 'left'): HogFlow =>+ new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withSimpleWorkflow({ trigger: { type: 'cohort', cohort_id: cohortId, transition } })+ .build()++ beforeEach(async () => {+ hub = await createHub({ SITE_URL: 'http://localhost:8000' })+ team = (await createTestTeamFixture(hub.postgres)).team+ jest.spyOn(hub.quotaLimiting, 'isTeamQuotaLimited').mockResolvedValue(false)++ const mockJobQueue = createMockJobQueue()+ processor = new CdpCohortMembershipTriggerConsumer(hub, createCdpConsumerDeps(hub), {+ hogflowQueue: mockJobQueue,+ })+ mockQueueInvocations = mockJobQueue.queueInvocations+ await processor.start()+ })++ afterEach(async () => {+ await processor.stop()+ await closeHub(hub)+ })++ it('starts a run only for workflows triggered by that cohort and transition', async () => {+ const matching = await insertHogFlow(hub.postgres, cohortFlow(42, 'entered'))+ await insertHogFlow(hub.postgres, cohortFlow(42, 'left'))+ await insertHogFlow(hub.postgres, cohortFlow(7, 'entered'))+ const change = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })++ const globals = await processor._parseKafkaBatch([createKafkaMessage(change)])+ const { invocations, backgroundTask } = await processor.processBatch(globals)+ await backgroundTask++ expect(invocations).toHaveLength(1)+ const invocation = invocations[0] as CyclotronJobInvocationHogFlow+ expect(invocation.functionId).toBe(matching.id)+ expect(invocation.state.personId).toBe(change.person_id)+ expect(invocation.state.event.event).toBe(COHORT_MEMBERSHIP_CHANGED_EVENT)+ expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)+ })++ it('fails the batch when loading workflows fails, so the change is retried', async () => {+ jest.spyOn(processor['hogFlowManager'], 'getHogFlowsForTeam').mockRejectedValue(+ new Error('canceling statement due to conflict with recovery')+ )+ const change = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })++ await expect(processor._parseKafkaBatch([createKafkaMessage(change)])).rejects.toThrow('conflict with recovery')+ })++ 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 })++ const globals = await processor._parseKafkaBatch([createKafkaMessage(change)])++ expect(globals).toHaveLength(0)+ })+})diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.tsnew file mode 100644index 000000000000..73a12fa06517--- /dev/null+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts@@ -0,0 +1,188 @@+import { Message } from 'node-rdkafka'+import { Counter } from 'prom-client'++import { KAFKA_COHORT_MEMBERSHIP_CHANGED } from '~/common/config/kafka-topics'+import { KafkaConsumerInterface, START_AT_LATEST, createKafkaConsumer } from '~/common/kafka/consumer'+import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'+import { parseJSON } from '~/common/utils/json-parse'+import { logger } from '~/common/utils/logger'+import { captureException } from '~/common/utils/posthog'++import { HealthCheckResult, PluginsServerConfig } from '../../types'+import { HogFlow } from '../schema/hogflow'+import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'+import { JobQueue } from '../services/job-queue/job-queue.interface'+import { CyclotronJobInvocation, HogFunctionInvocationGlobals } from '../types'+import { convertBatchHogFlowRequestToHogFunctionInvocationGlobals } from '../utils'+import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'+import { CohortMembershipChange, CohortMembershipChangeSchema } from './cdp-cohort-membership.consumer'+import { counterParseError } from './metrics'++// pinned: stored as the event of every cohort-triggered run, which workflow steps and logs read+export const COHORT_MEMBERSHIP_CHANGED_EVENT = '$cohort_membership_changed'++export const counterCohortMembershipTriggerSkipped = new Counter({+ name: 'cdp_cohort_membership_trigger_skipped',+ help: 'Membership changes the cohort trigger consumer did not turn into workflow runs, by reason.',+ labelNames: ['reason'],+})++export function isMatchingCohortTrigger(flow: HogFlow, globals: HogFunctionInvocationGlobals): boolean {+ const trigger = flow.trigger+ return (+ trigger.type === 'cohort' &&+ globals.event.event === COHORT_MEMBERSHIP_CHANGED_EVENT &&+ trigger.cohort_id === globals.event.properties.cohort_id &&+ trigger.transition === globals.event.properties.status+ )+}++/**+ * Starts workflow runs from realtime cohort membership changes.+ *+ * Reads the same topic as CdpCohortMembershipConsumer under its own group, so persisting membership+ * and starting runs fail and lag independently.+ */+export class CdpCohortMembershipTriggerConsumer extends CdpConsumerBase {+ protected name = 'CdpCohortMembershipTriggerConsumer'++ protected hogflowQueue: JobQueue+ protected kafkaConsumer: KafkaConsumerInterface+ private hogFlowPipeline: HogFlowInvocationPipeline++ constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, jobQueues: { hogflowQueue: JobQueue }) {+ super(config, deps)+ this.hogflowQueue = jobQueues.hogflowQueue+ // A fresh group starts at the tip. Replaying the retained topic would start runs for old changes.+ this.kafkaConsumer = createKafkaConsumer(+ { groupId: 'cdp-cohort-membership-trigger-consumer', topic: KAFKA_COHORT_MEMBERSHIP_CHANGED },+ START_AT_LATEST+ )+ this.hogFlowPipeline = new HogFlowInvocationPipeline(config, {+ hogFlowManager: this.hogFlowManager,+ hogFlowExecutor: this.hogFlowExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })+ }++ public async processBatch(+ invocationGlobals: HogFunctionInvocationGlobals[]+ ): Promise<{ backgroundTask: Promise<any>; invocations: CyclotronJobInvocation[] }> {+ if (!invocationGlobals.length) {+ return { backgroundTask: Promise.resolve(), invocations: [] }+ }++ const invocations = await this.hogFlowPipeline.buildInvocations(invocationGlobals, {+ eligibilityFn: isMatchingCohortTrigger,+ })++ for (const invocation of invocations) {+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ }++ return {+ backgroundTask: Promise.all([+ instrumentFn({ key: 'cdp.background_task.queue_hogflow_invocations', sendException: false }, () =>+ this.hogflowQueue.queueInvocations(invocations)+ ),+ instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {+ try {+ await this.hogFunctionMonitoringService.flush()+ } catch (err) {+ captureException(err)+ logger.error('🔴', 'Error producing queued messages for monitoring', { err })+ }+ }),+ instrumentFn({ key: 'cdp.background_task.lifecycle_running_flush', sendException: false }, () =>+ this.invocationResultsService.invocationResultsRowsService.flush()+ ),+ ]),+ invocations,+ }+ }++ @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+ }++ // 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+ }++ // 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(+ (flow) => flow.trigger.type === 'cohort' && flow.trigger.cohort_id === change.cohort_id+ )+ if (!triggered) {+ return+ }++ const team = await this.deps.teamManager.getTeam(change.team_id)+ if (!team) {+ // The team has active cohort-triggered workflows, so a missing team means the lookup is broken.+ logger.warn('Team not found for a cohort membership change', { teamId: change.team_id })+ counterCohortMembershipTriggerSkipped.labels({ reason: 'team_not_found' }).inc()+ return+ }++ const globals = convertBatchHogFlowRequestToHogFunctionInvocationGlobals({+ team,+ personId: change.person_id,+ siteUrl: this.config.SITE_URL,+ })+ globals.event = {+ ...globals.event,+ event: COHORT_MEMBERSHIP_CHANGED_EVENT,+ properties: { cohort_id: change.cohort_id, status: change.status },+ }+ events.push(globals)+ })+ )++ return events+ }++ public override async start(): Promise<void> {+ await super.start()+ await this.hogflowQueue.startAsProducer()+ await this.kafkaConsumer.connect(async (messages) => {+ logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })+ return await instrumentFn('cdpConsumer.handleEachBatch', async () => {+ const invocationGlobals = await this._parseKafkaBatch(messages)+ const { backgroundTask } = await this.processBatch(invocationGlobals)+ return { backgroundTask }+ })+ })+ }++ public override async stop(): Promise<void> {+ logger.info('💤', 'Stopping consumer...')+ await this.kafkaConsumer.disconnect()+ await this.hogflowQueue.stopProducer()+ await super.stop()+ }++ public isHealthy(): HealthCheckResult {+ return this.kafkaConsumer.isHealthy()+ }+}diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.tsindex 5a6cfe1210d9..f13336c6a85d 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts@@ -49,7 +49,7 @@ const offFormatVersions = new Counter({// `origin` is a loose string, not an enum: nothing branches on it, and rejecting a value the// processor added later would throw the whole batch and crash-loop on redelivery.-const CohortMembershipChangeSchema = z.object({+export const CohortMembershipChangeSchema = z.object({person_id: z.guid(),cohort_id: z.number(),team_id: z.number(),diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 149753dc5adb..12f77108301a 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -200,6 +200,15 @@ export class HogFlowExecutorService {for (const hogFlow of hogFlows) {const trigger = hogFlow.trigger+ if (trigger.type === 'cohort') {+ // A cohort trigger has no filters to evaluate: eligibility already matched the membership change.+ const invocation = createHogFlowInvocation(triggerGlobals, hogFlow, filterGlobals)+ // A membership change carries no distinct_id, so the worker loads the person by id.+ invocation.state.personId = triggerGlobals.person?.id+ invocations.push(invocation)+ continue+ }+// Defensive: only the trigger types that carry `filters` make it through eligibility.// isRowScopedTrigger covers internal-event too, alongside the two warehouse types.if (trigger.type !== 'event' && !isRowScopedTrigger(trigger)) {diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 26d552c697ce..8a6d7df6f711 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -52,6 +52,7 @@ export enum PluginServerMode {cdp_precalculated_filters = 'cdp-precalculated-filters',cdp_hogflow_subscription_matcher = 'cdp-hogflow-subscription-matcher',cdp_cohort_membership = 'cdp-cohort-membership',+ cdp_cohort_membership_triggers = 'cdp-cohort-membership-triggers',cdp_cyclotron_worker_hogflow = 'cdp-cyclotron-worker-hogflow',cdp_cyclotron_worker_email = 'cdp-cyclotron-worker-email',cdp_api = 'cdp-api',diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 2183449ee9ce..3f5d995b513c 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -24,6 +24,7 @@ import { startEvaluationScheduler } from './ai-observability/evaluation-scheduleimport { getPluginServerCapabilities } from './capabilities'import { CdpApi } from './cdp/cdp-api'import { CdpConsumerBaseDeps } from './cdp/consumers/cdp-base.consumer'+import { CdpCohortMembershipTriggerConsumer } from './cdp/consumers/cdp-cohort-membership-trigger.consumer'import { CdpCohortMembershipConsumer } from './cdp/consumers/cdp-cohort-membership.consumer'import { CdpCyclotronWorkerBatchResolve } from './cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer'import { CdpCyclotronWorkerEmail } from './cdp/consumers/cdp-cyclotron-worker-email.consumer'@@ -103,6 +104,7 @@ export class PluginServer implements NodeServer {capabilities.cdpCyclotronWorkerHogFlow ||capabilities.cdpCyclotronWorkerEmail ||capabilities.cdpCohortMembership ||+ capabilities.cdpCohortMembershipTriggers ||capabilities.cdpCyclotronWorkerBatchResolve ||capabilities.cdpHogflowSubscriptionMatcher ||capabilities.cdpRerunWorker ||@@ -391,6 +393,16 @@ export class PluginServer implements NodeServer {})}+ if (capabilities.cdpCohortMembershipTriggers) {+ serviceLoaders.push(async () => {+ const consumer = new CdpCohortMembershipTriggerConsumer(this.config, cdpDeps!, {+ hogflowQueue: postgresV2Queue,+ })+ await consumer.start()+ return consumer.service+ })+ }+if (capabilities.cdpHogflowSubscriptionMatcher) {serviceLoaders.push(async () => {const consumer = new CdpHogflowSubscriptionMatcherConsumer(this.config, cdpDeps!)diff --git a/nodejs/src/types.ts b/nodejs/src/types.tsindex fb81c7cee35c..9678003d31e2 100644--- a/nodejs/src/types.ts+++ b/nodejs/src/types.ts@@ -145,6 +145,7 @@ export interface PluginServerCapabilities {cdpCyclotronWorkerHogFlow?: booleancdpCyclotronWorkerEmail?: booleancdpCohortMembership?: boolean+ cdpCohortMembershipTriggers?: booleancdpApi?: booleanappManagementSingleton?: booleanevaluationScheduler?: boolean