: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(workflows): let cohort triggers limit how often a person enters (#117032)
Harley Alexander8faefe1c66f4
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 3de10fda4ffe..d57402212350 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@@ -9,6 +9,7 @@ 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 { HOG_FLOW_MASK_EXAMPLES } from '../_tests/examples'import { createCohortMembershipEvent, createKafkaMessage } from '../_tests/fixtures'import { insertHogFlow } from '../_tests/fixtures-hogflows'import { CyclotronJobInvocationHogFlow } from '../types'@@ -65,6 +66,59 @@ describe('CdpCohortMembershipTriggerConsumer', () => {expect(mockQueueInvocations).toHaveBeenCalledWith(invocations)})+ it('starts one run per person when the workflow runs once per person', async () => {+ const flow = cohortFlow(42, 'entered')+ flow.trigger_masking = HOG_FLOW_MASK_EXAMPLES.onceEver.trigger_masking+ await insertHogFlow(hub.postgres, flow)+ const rejoiner = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })+ const other = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })++ const first = await processor.processBatch(await processor._parseKafkaBatch([createKafkaMessage(rejoiner)]))+ await first.backgroundTask+ const second = await processor.processBatch(+ await processor._parseKafkaBatch([createKafkaMessage(rejoiner), createKafkaMessage(other)])+ )+ await second.backgroundTask++ expect(+ first.invocations.map((invocation) => (invocation as CyclotronJobInvocationHogFlow).state.personId)+ ).toEqual([rejoiner.person_id])+ expect(+ second.invocations.map((invocation) => (invocation as CyclotronJobInvocationHogFlow).state.personId)+ ).toEqual([other.person_id])+ })++ it.each([true, false])(+ 'on redelivery after a partly failed queue, starts only the runs that were not queued (parallel inserts: %s)',+ async (parallel) => {+ hub.CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE = 1+ hub.CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES = parallel+ const flow = cohortFlow(42, 'entered')+ flow.trigger_masking = HOG_FLOW_MASK_EXAMPLES.onceEver.trigger_masking+ await insertHogFlow(hub.postgres, flow)+ const queuedChange = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })+ const failedChange = createCohortMembershipEvent({ team_id: team.id, cohort_id: 42, status: 'entered' })+ const messages = [createKafkaMessage(queuedChange), createKafkaMessage(failedChange)]+ mockQueueInvocations.mockImplementation((batch: CyclotronJobInvocationHogFlow[]) =>+ batch[0].state.personId === failedChange.person_id+ ? Promise.reject(new Error('queue unavailable'))+ : Promise.resolve()+ )++ const failed = await processor.processBatch(await processor._parseKafkaBatch(messages))+ await expect(failed.backgroundTask).rejects.toThrow('queue unavailable')+ mockQueueInvocations.mockResolvedValue(undefined)+ const redelivered = await processor.processBatch(await processor._parseKafkaBatch(messages))+ await redelivered.backgroundTask++ expect(+ redelivered.invocations.map(+ (invocation) => (invocation as CyclotronJobInvocationHogFlow).state.personId+ )+ ).toEqual([failedChange.person_id])+ }+ )+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')diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.tsindex 73a12fa06517..1f15e198a21f 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership-trigger.consumer.ts@@ -1,3 +1,4 @@+import { chunk } from 'lodash'import { Message } from 'node-rdkafka'import { Counter } from 'prom-client'@@ -49,10 +50,15 @@ export class CdpCohortMembershipTriggerConsumer extends CdpConsumerBase {protected hogflowQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFlowPipeline: HogFlowInvocationPipeline+ private queueConfig: Pick<+ PluginsServerConfig,+ 'CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE' | 'CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES'+ >constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, jobQueues: { hogflowQueue: JobQueue }) {super(config, deps)this.hogflowQueue = jobQueues.hogflowQueue+ this.queueConfig = config// 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 },@@ -78,7 +84,7 @@ export class CdpCohortMembershipTriggerConsumer extends CdpConsumerBase {return { backgroundTask: Promise.resolve(), invocations: [] }}- const invocations = await this.hogFlowPipeline.buildInvocations(invocationGlobals, {+ const { invocations, release } = await this.hogFlowPipeline.buildInvocationsWithRelease(invocationGlobals, {eligibilityFn: isMatchingCohortTrigger,})@@ -88,8 +94,48 @@ export class CdpCohortMembershipTriggerConsumer extends CdpConsumerBase {return {backgroundTask: Promise.all([- instrumentFn({ key: 'cdp.background_task.queue_hogflow_invocations', sendException: false }, () =>- this.hogflowQueue.queueInvocations(invocations)+ instrumentFn(+ { key: 'cdp.background_task.queue_hogflow_invocations', sendException: false },+ async () => {+ // One insert per chunk, so a failure leaves a known set of runs queued.+ const batches = chunk(invocations, this.queueConfig.CDP_CYCLOTRON_INSERT_MAX_BATCH_SIZE)+ const queued: CyclotronJobInvocation[] = []+ let failure: { error: unknown } | null = null+ if (this.queueConfig.CDP_CYCLOTRON_INSERT_PARALLEL_BATCHES) {+ const results = await Promise.allSettled(+ batches.map((batch) => this.hogflowQueue.queueInvocations(batch))+ )+ results.forEach((result, index) => {+ if (result.status === 'fulfilled') {+ queued.push(...batches[index])+ } else {+ failure ??= { error: result.reason }+ }+ })+ } else {+ for (const batch of batches) {+ try {+ await this.hogflowQueue.queueInvocations(batch)+ queued.push(...batch)+ } catch (error) {+ failure = { error }+ break+ }+ }+ }+ if (failure) {+ // The batch is retried. Runs that never reached the queue release their claims, or the+ // retry finds them masked. Queued runs keep theirs, so their people do not run twice.+ await release(queued)+ const queuedIds = new Set(queued.map((invocation) => invocation.id))+ this.invocationResultsService.invocationResultsRowsService.dropQueuedRowsFor(+ invocations+ .filter((invocation) => !queuedIds.has(invocation.id))+ .map((invocation) => invocation.id)+ )+ throw failure.error+ }+ }),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.tsindex f6472523649a..6d91fb01172d 100644--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts@@ -70,8 +70,19 @@ export class HogFlowInvocationPipeline {this.hogRateLimiterMirror = new KeyedRateLimiterService(rateLimiterConfig, deps.valkeyShadow.writer)}- @instrumented('cdpConsumer.handleEachBatch.queueMatchingFlows')public async buildInvocations(+ invocationGlobals: HogFunctionInvocationGlobals[],+ options?: { eligibilityFn?: (hogFlow: HogFlow, globals: HogFunctionInvocationGlobals) => boolean }+ ): Promise<CyclotronJobInvocation[]> {+ return (await this.buildInvocationsWithRelease(invocationGlobals, options)).invocations+ }++ /**+ * Also returns the masker's `release`. Masking claims are written before the caller queues the runs,+ * so a caller that retries after a failed queue must release them, or the retry masks every run.+ */+ @instrumented('cdpConsumer.handleEachBatch.queueMatchingFlows')+ public async buildInvocationsWithRelease(invocationGlobals: HogFunctionInvocationGlobals[],options?: {// Predicate evaluated per (flow, globals) before the executor runs filter bytecode.@@ -81,7 +92,10 @@ export class HogFlowInvocationPipeline {// touching the executor.eligibilityFn?: (hogFlow: HogFlow, globals: HogFunctionInvocationGlobals) => boolean}- ): Promise<CyclotronJobInvocation[]> {+ ): Promise<{+ invocations: CyclotronJobInvocation[]+ release: (persisted?: CyclotronJobInvocation[]) => Promise<void>+ }> {const teamsToLoad = [...new Set(invocationGlobals.map((x) => x.project.id))]const hogFlowsByTeam = await this.deps.hogFlowManager.getHogFlowsForTeams(teamsToLoad)const eligibilityFn = options?.eligibilityFn@@ -226,7 +240,11 @@ export class HogFlowInvocationPipeline {}))- const { masked, notMasked: notMaskedInvocations } = await this.deps.hogMasker.filterByMasking(validInvocations)+ const {+ masked,+ notMasked: notMaskedInvocations,+ release,+ } = await this.deps.hogMasker.filterByMasking(validInvocations)this.deps.hogFunctionMonitoringService.queueAppMetrics(masked.map((item) => ({@@ -255,6 +273,6 @@ export class HogFlowInvocationPipeline {this.deps.hogFunctionMonitoringService.queueAppMetrics(triggeredInvocationsMetrics, 'hog_flow')- return notMaskedInvocations+ return { invocations: notMaskedInvocations, release }}}diff --git a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts b/nodejs/src/cdp/services/monitoring/hog-masker.service.tsindex d57d0b24388f..044b5a19be92 100644--- a/nodejs/src/cdp/services/monitoring/hog-masker.service.ts+++ b/nodejs/src/cdp/services/monitoring/hog-masker.service.ts@@ -122,8 +122,10 @@ export class HogMaskerService {* caller persists the invocations, so if that persistence fails, the caller must* release the claims — otherwise a replay of the same batch sees every invocation* as already-masked and silently drops it.+ *+ * Pass the invocations that did persist to keep their claims, so a replay does not run them twice.*/- release: () => Promise<void>+ release: (persisted?: CyclotronJobInvocation[]) => Promise<void>}> {const invocationsWithMasker: GenericHogInvocationWithMasker[] = [...invocations]const masks: Record<string, MaskContext> = {}@@ -199,9 +201,14 @@ export class HogMaskerService {))- const release = async (): Promise<void> => {+ const release = async (persisted: CyclotronJobInvocation[] = []): Promise<void> => {+ const kept = new Set(persisted.map((item) => (item as GenericHogInvocationWithMasker).masker))+ const released = maskContexts.filter((masker) => !kept.has(masker))+ if (released.length === 0) {+ return+ }const buildReleasePipeline = (pipeline: RedisClientPipeline): void => {- maskContexts.forEach(({ hogFunctionId, hash, increment }) => {+ released.forEach(({ hogFunctionId, hash, increment }) => {pipeline.incrby(`${REDIS_KEY_TOKENS}/${hogFunctionId}/${hash}`, -increment)})}diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsxindex b54dfa2f57eb..6954609953e2 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsx+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/cohort.tsx@@ -10,7 +10,10 @@ import { LemonField } from 'lib/lemon-ui/LemonField'import { cohortsModel } from '~/models/cohortsModel'-import { registerTriggerType } from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry'+import {+ PERSON_FREQUENCY_OPTIONS,+ registerTriggerType,+} from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry'import { workflowLogic } from 'products/workflows/frontend/Workflows/workflowLogic'import { HogFlowAction } from '../../types'@@ -89,4 +92,5 @@ registerTriggerType({return { valid: true, errors: {} }},ConfigComponent: StepTriggerConfigurationCohort,+ frequencyOptions: PERSON_FREQUENCY_OPTIONS,})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.tsindex bbb3670d3fc8..fd25a06fc4d8 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry.ts@@ -18,6 +18,15 @@ export type TriggerFrequencyOption = {fixedTtl?: number}+const MASKING_HASH_PER_PERSON_PER_DAY = "{concat(toString(person.id), '-', formatDateTime(now(), '%Y-%m-%d'))}"+const CALENDAR_DAY_TTL = 24 * 60 * 60++export const PERSON_FREQUENCY_OPTIONS: TriggerFrequencyOption[] = [+ { value: null, label: 'Every time the trigger fires' },+ { value: '{person.id}', label: 'One time' },+ { value: MASKING_HASH_PER_PERSON_PER_DAY, label: 'Once per calendar day', fixedTtl: CALENDAR_DAY_TTL },+]+export type TriggerTypeDefinition = {value: stringlabel: stringdiff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex abc062cffed5..be6facd878c2 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -55,7 +55,11 @@ import 'products/workflows/frontend/Workflows/hogflows/registry/triggers'import { workflowLogic } from '../../workflowLogic'import { HogFlowEventFilters, HogFlowPropertyFilters, WORKFLOW_OPERATOR_ALLOWLIST } from '../filters/HogFlowFilters'-import { TriggerFrequencyOption, getRegisteredTriggerTypes } from '../registry/triggers/triggerTypeRegistry'+import {+ PERSON_FREQUENCY_OPTIONS,+ TriggerFrequencyOption,+ getRegisteredTriggerTypes,+} from '../registry/triggers/triggerTypeRegistry'import { HogFlowAction } from '../types'import { createAccountAssignmentFilterUpdate, parseAccountAssignmentFilter } from './accountAssignmentFilter'import { batchTriggerLogic, getAudienceDedupeKey, hogFlowSendsEmail } from './batchTriggerLogic'@@ -866,15 +870,6 @@ function StepTriggerConfigurationTrackingPixel({)}-const MASKING_HASH_PER_PERSON_PER_DAY = "{concat(toString(person.id), '-', formatDateTime(now(), '%Y-%m-%d'))}"-const CALENDAR_DAY_TTL = 24 * 60 * 60--const FREQUENCY_OPTIONS: TriggerFrequencyOption[] = [- { value: null, label: 'Every time the trigger fires' },- { value: '{person.id}', label: 'One time' },- { value: MASKING_HASH_PER_PERSON_PER_DAY, label: 'Once per calendar day', fixedTtl: CALENDAR_DAY_TTL },-]-const TTL_OPTIONS = [{ value: null, label: 'indefinitely' },{ value: 5 * 60, label: '5 minutes' },@@ -909,7 +904,7 @@ function TTLSelect({}function FrequencySection({- options = FREQUENCY_OPTIONS,+ options = PERSON_FREQUENCY_OPTIONS,description = 'Limit how often users can enter this workflow',}: {options?: TriggerFrequencyOption[]