Skip to content

: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.

feat(workflows): evaluate cohort membership in conditional branches (#83799)

Meikel Ratz0d6b98b8efa8
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 000000000000..ac9b11bbb190
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,5 @@
+# Read by oxfmt as a default ignore file. Entries here stay unformatted even when a tool
+# passes the path explicitly (hogli format:js via lint-staged does), unlike .oxfmtrc.json's
+# ignorePatterns, which explicit arguments bypass.
+# CI regenerates this file and requires it byte-identical to the compiler's output (ci-hog.yml).
+common/hogvm/typescript/src/stl/bytecode.ts
diff --git a/common/hogvm/python/stl/bytecode.py b/common/hogvm/python/stl/bytecode.py
index 7fdd2e3a9175..5d93114f0aae 100644
--- a/common/hogvm/python/stl/bytecode.py
+++ b/common/hogvm/python/stl/bytecode.py
@@ -6,6 +6,8 @@ BYTECODE_STL: dict[str, tuple[list[str], list]] = {
"arrayFilter": (["func", "arr"], [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 33, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 9, 36, 2, 36, 7, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -40, 35, 35, 35, 35, 35, 36, 2, 38, 35]),
"arrayMap": (["func", "arr"], [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 29, 36, 4, 36, 5, 45, 37, 7, 36, 2, 36, 7, 36, 0, 54, 1, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -36, 35, 35, 35, 35, 35, 36, 2, 38, 35]),
"arrayReduce": (["func", "arr", "initial"], [36, 2, 36, 1, 36, 4, 2, "values", 1, 33, 1, 36, 5, 2, "length", 1, 31, 36, 7, 36, 6, 16, 40, 26, 36, 5, 36, 6, 45, 37, 8, 36, 3, 36, 8, 36, 0, 54, 2, 37, 3, 36, 6, 33, 1, 6, 37, 6, 39, -33, 35, 35, 35, 35, 35, 36, 3, 38, 35]),
+ "inCohort": (["cohort_id", "cohort_ids"], [31, 36, 1, 11, 40, 6, 32, "inCohort() requires cohort membership to be loaded for this evaluation", 2, "Error", 1, 49, 36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 25, 36, 3, 36, 4, 45, 37, 6, 36, 0, 36, 6, 11, 40, 2, 29, 38, 36, 4, 33, 1, 6, 37, 4, 39, -32, 35, 35, 35, 35, 35, 30, 38]),
+ "notInCohort": (["cohort_id", "cohort_ids"], [31, 36, 1, 11, 40, 6, 32, "notInCohort() requires cohort membership to be loaded for this evaluation", 2, "Error", 1, 49, 36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 25, 36, 3, 36, 4, 45, 37, 6, 36, 0, 36, 6, 11, 40, 2, 30, 38, 36, 4, 33, 1, 6, 37, 4, 39, -32, 35, 35, 35, 35, 35, 29, 38]),
"sortableSemver": (["version"], [31, 36, 0, 11, 40, 3, 43, 0, 38, 36, 0, 32, "(\\d+(\\.\\d+)+)", 2, "extractRegex", 2, 36, 1, 2, "empty", 1, 40, 3, 43, 0, 38, 32, ".", 36, 1, 2, "splitByString", 2, 52, "lambda", 1, 0, 11, 36, 0, 2, "toInt", 1, 47, 3, 35, 33, 0, 38, 53, 0, 36, 2, 2, "arrayMap", 2, 38, 35, 35]),
}
# fmt: on
diff --git a/common/hogvm/stl/src/inCohort.hog b/common/hogvm/stl/src/inCohort.hog
new file mode 100644
index 000000000000..aeadfd2ccc97
--- /dev/null
+++ b/common/hogvm/stl/src/inCohort.hog
@@ -0,0 +1,11 @@
+fun inCohort(cohort_id, cohort_ids) {
+ if (cohort_ids == null) {
+ throw Error('inCohort() requires cohort membership to be loaded for this evaluation')
+ }
+ for (let id in cohort_ids) {
+ if (id == cohort_id) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/common/hogvm/stl/src/notInCohort.hog b/common/hogvm/stl/src/notInCohort.hog
new file mode 100644
index 000000000000..f39c709531b6
--- /dev/null
+++ b/common/hogvm/stl/src/notInCohort.hog
@@ -0,0 +1,11 @@
+fun notInCohort(cohort_id, cohort_ids) {
+ if (cohort_ids == null) {
+ throw Error('notInCohort() requires cohort membership to be loaded for this evaluation')
+ }
+ for (let id in cohort_ids) {
+ if (id == cohort_id) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/common/hogvm/typescript/src/stl/bytecode.ts b/common/hogvm/typescript/src/stl/bytecode.ts
index 6a5673fc2012..304002dbf4a7 100644
--- a/common/hogvm/typescript/src/stl/bytecode.ts
+++ b/common/hogvm/typescript/src/stl/bytecode.ts
@@ -5,5 +5,7 @@ export const BYTECODE_STL: Record<string, [string[], any[]]> = {
"arrayFilter": [["func", "arr"], [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 33, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 9, 36, 2, 36, 7, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -40, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
"arrayMap": [["func", "arr"], [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 29, 36, 4, 36, 5, 45, 37, 7, 36, 2, 36, 7, 36, 0, 54, 1, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -36, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
"arrayReduce": [["func", "arr", "initial"], [36, 2, 36, 1, 36, 4, 2, "values", 1, 33, 1, 36, 5, 2, "length", 1, 31, 36, 7, 36, 6, 16, 40, 26, 36, 5, 36, 6, 45, 37, 8, 36, 3, 36, 8, 36, 0, 54, 2, 37, 3, 36, 6, 33, 1, 6, 37, 6, 39, -33, 35, 35, 35, 35, 35, 36, 3, 38, 35]],
+ "inCohort": [["cohort_id", "cohort_ids"], [31, 36, 1, 11, 40, 6, 32, "inCohort() requires cohort membership to be loaded for this evaluation", 2, "Error", 1, 49, 36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 25, 36, 3, 36, 4, 45, 37, 6, 36, 0, 36, 6, 11, 40, 2, 29, 38, 36, 4, 33, 1, 6, 37, 4, 39, -32, 35, 35, 35, 35, 35, 30, 38]],
+ "notInCohort": [["cohort_id", "cohort_ids"], [31, 36, 1, 11, 40, 6, 32, "notInCohort() requires cohort membership to be loaded for this evaluation", 2, "Error", 1, 49, 36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 25, 36, 3, 36, 4, 45, 37, 6, 36, 0, 36, 6, 11, 40, 2, 30, 38, 36, 4, 33, 1, 6, 37, 4, 39, -32, 35, 35, 35, 35, 35, 29, 38]],
"sortableSemver": [["version"], [31, 36, 0, 11, 40, 3, 43, 0, 38, 36, 0, 32, "(\\d+(\\.\\d+)+)", 2, "extractRegex", 2, 36, 1, 2, "empty", 1, 40, 3, 43, 0, 38, 32, ".", 36, 1, 2, "splitByString", 2, 52, "lambda", 1, 0, 11, 36, 0, 2, "toInt", 1, 47, 3, 35, 33, 0, 38, 53, 0, 36, 2, 2, "arrayMap", 2, 38, 35, 35]],
}
diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.ts
index 2600505e0eb5..7e81ce43663b 100644
--- a/nodejs/src/cdp/cdp-services.ts
+++ b/nodejs/src/cdp/cdp-services.ts
@@ -484,6 +484,7 @@ export function createCdpCoreServices(
hogFlowFunctionsService,
recipientPreferencesService,
emailValidationService,
+ cohortMembershipRepository,
hogFlowDuplicateObserver
)
diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
index dfa54cabc025..f0f426c658eb 100644
--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
@@ -4,6 +4,7 @@ import { FixtureHogFlowBuilder } from '~/cdp/_tests/builders/hogflow.builder'
import { HOG_FILTERS_EXAMPLES } from '~/cdp/_tests/examples'
import { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'
import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'
+import { CohortMembershipRepository } from '~/cdp/services/cohorts/cohort-membership-repository'
import { CyclotronJobInvocationHogFlow } from '~/cdp/types'
import { createInvocationResult } from '~/cdp/utils/invocation-utils'
@@ -174,6 +175,129 @@ describe('action.conditional_branch', () => {
})
})
+ describe('cohort membership conditions', () => {
+ const COHORT_ID = 42
+
+ class FakeCohortMembershipRepository implements CohortMembershipRepository {
+ public calls: { teamId: number; personUuid: string }[] = []
+
+ constructor(
+ private memberCohortIds: number[],
+ private error?: Error
+ ) {}
+
+ getMemberCohortIds(teamId: number, personUuid: string): Promise<number[]> {
+ this.calls.push({ teamId, personUuid })
+ if (this.error) {
+ return Promise.reject(this.error)
+ }
+ return Promise.resolve(this.memberCohortIds)
+ }
+ }
+
+ // Same shape the Python serializer emits: the authored properties plus compiled bytecode.
+ // Keeping the properties key matters: filters holding ONLY bytecode short-circuit to an
+ // unconditional match in filterFunctionInstrumented and never execute the VM.
+ const cohortConditionFilters = (fn: 'inCohort' | 'notInCohort'): Record<string, any> => ({
+ bytecode: ['_H', 1, 33, COHORT_ID, 32, 'cohort_ids', 1, 1, 2, fn, 2],
+ properties: [{ key: 'id', type: 'cohort', value: COHORT_ID }],
+ })
+
+ const executeWithRepository = async (
+ repository: CohortMembershipRepository,
+ fn: 'inCohort' | 'notInCohort'
+ ): Promise<HogFlowAction | undefined> => {
+ action.config.conditions = [
+ { filters: cohortConditionFilters(fn) },
+ { filters: HOG_FILTERS_EXAMPLES.no_filters.filters }, // always-true fallthrough
+ ]
+ const handler = new ConditionalBranchHandler(repository)
+ const result = await handler.execute({
+ invocation,
+ action,
+ result: createInvocationResult(invocation),
+ })
+ return result.nextAction
+ }
+
+ it.each([
+ ['inCohort', true, 'condition_1'],
+ ['inCohort', false, 'condition_2'],
+ ['notInCohort', false, 'condition_1'],
+ ['notInCohort', true, 'condition_2'],
+ ] as const)('routes %s with membership=%s to %s', async (fn, isMember, expectedActionId) => {
+ const repository = new FakeCohortMembershipRepository(isMember ? [7, COHORT_ID] : [7])
+
+ const nextAction = await executeWithRepository(repository, fn)
+
+ expect(nextAction).toEqual(findActionById(invocation.hogFlow, expectedActionId))
+ expect(repository.calls).toEqual([
+ { teamId: invocation.hogFlow.team_id, personUuid: invocation.person!.id },
+ ])
+ })
+
+ it('does not query membership when an earlier non-cohort condition matches', async () => {
+ // The lookup is lazy: a run that never reaches the cohort condition must not depend on
+ // the behavioral cohorts DB, even when that DB is down.
+ const repository = new FakeCohortMembershipRepository([], new Error('cohorts DB down'))
+ action.config.conditions = [
+ { filters: HOG_FILTERS_EXAMPLES.no_filters.filters }, // matches first
+ { filters: cohortConditionFilters('inCohort') },
+ ]
+ const handler = new ConditionalBranchHandler(repository)
+
+ const result = await handler.execute({
+ invocation,
+ action,
+ result: createInvocationResult(invocation),
+ })
+
+ expect(result.nextAction).toEqual(findActionById(invocation.hogFlow, 'condition_1'))
+ expect(repository.calls).toEqual([])
+ })
+
+ it('does not query membership for a condition that merely mentions "inCohort" as a string', async () => {
+ const repository = new FakeCohortMembershipRepository([COHORT_ID])
+ action.config.conditions = [
+ {
+ // properties.foo == 'inCohort' — the name appears as a string constant, not a call
+ filters: {
+ bytecode: ['_H', 1, 32, 'inCohort', 32, 'foo', 32, 'properties', 1, 2, 11],
+ properties: [{ key: 'foo', type: 'event', value: 'inCohort', operator: 'exact' }],
+ },
+ },
+ { filters: HOG_FILTERS_EXAMPLES.no_filters.filters },
+ ]
+ const handler = new ConditionalBranchHandler(repository)
+
+ const result = await handler.execute({
+ invocation,
+ action,
+ result: createInvocationResult(invocation),
+ })
+
+ expect(result.nextAction).toEqual(findActionById(invocation.hogFlow, 'condition_2'))
+ expect(repository.calls).toEqual([])
+ })
+
+ it('treats a person-less invocation as a non-member without querying', async () => {
+ const repository = new FakeCohortMembershipRepository([COHORT_ID])
+ invocation.person = undefined
+ invocation.state.personId = undefined
+
+ const nextAction = await executeWithRepository(repository, 'inCohort')
+
+ expect(nextAction).toEqual(findActionById(invocation.hogFlow, 'condition_2'))
+ expect(repository.calls).toEqual([])
+ })
+
+ it('propagates a lookup failure instead of routing on a made-up answer', async () => {
+ const repository = new FakeCohortMembershipRepository([], new Error('lookup timed out'))
+
+ await expect(executeWithRepository(repository, 'inCohort')).rejects.toThrow('lookup timed out')
+ })
+ })
+
describe('wait_until_condition eventMatched short-circuit', () => {
let waitInvocation: CyclotronJobInvocationHogFlow
let waitAction: Extract<HogFlowAction, { type: 'wait_until_condition' }>
@@ -214,7 +338,10 @@ describe('action.conditional_branch', () => {
id: waitAction.id,
startedAtTimestamp: DateTime.utc().toMillis(),
}
- handler = new ConditionalBranchHandler()
+ const stubCohortMembershipRepository: CohortMembershipRepository = {
+ getMemberCohortIds: () => Promise.resolve([]),
+ }
+ handler = new ConditionalBranchHandler(stubCohortMembershipRepository)
counterHogflowWaitPollOnlyAdvance.reset()
counterHogflowRekeyWake.reset()
})
diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
index 075d74dfcca5..3a6b271719fb 100644
--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
@@ -2,7 +2,8 @@ import { DateTime } from 'luxon'
import { Counter } from 'prom-client'
import { HogFlowAction } from '~/cdp/schema/hogflow'
-import { CyclotronJobInvocationHogFlow } from '~/cdp/types'
+import { CohortMembershipRepository } from '~/cdp/services/cohorts/cohort-membership-repository'
+import { CyclotronJobInvocationHogFlow, HogFunctionFilters } from '~/cdp/types'
import { filterFunctionInstrumented } from '~/cdp/utils/hog-function-filtering'
import { findContinueAction, findNextAction, isEvaluableCondition } from '../hogflow-utils'
@@ -34,6 +35,8 @@ export const counterHogflowRekeyWake = new Counter({
})
export class ConditionalBranchHandler implements ActionHandler {
+ constructor(private cohortMembershipRepository: CohortMembershipRepository) {}
+
async execute({
invocation,
action,
@@ -82,8 +85,7 @@ export class ConditionalBranchHandler implements ActionHandler {
}
}
- const conditionResult = await checkConditions(
- invocation,
+ const conditionalAction: Extract<HogFlowAction, { type: 'conditional_branch' }> =
action.type === 'conditional_branch'
? action
: {
@@ -97,6 +99,11 @@ export class ConditionalBranchHandler implements ActionHandler {
delay_duration: action.config.max_wait_duration,
},
}
+
+ const conditionResult = await checkConditions(
+ invocation,
+ conditionalAction,
+ this.createMemberCohortIdsLoader(invocation)
)
const isWait = action.type === 'wait_until_condition'
@@ -127,22 +134,74 @@ export class ConditionalBranchHandler implements ActionHandler {
return { nextAction: findContinueAction(invocation), result: { conditionResult } }
}
+
+ /**
+ * Memoized so one lookup covers every cohort condition in the action. Person-less
+ * invocations (warehouse rows, account audiences) are non-members of everything.
+ */
+ private createMemberCohortIdsLoader(invocation: CyclotronJobInvocationHogFlow): () => Promise<number[]> {
+ let loaded: Promise<number[]> | undefined
+ return () => {
+ if (!loaded) {
+ const personUuid = invocation.person?.id ?? invocation.state.personId
+ loaded = personUuid
+ ? this.cohortMembershipRepository.getMemberCohortIds(invocation.hogFlow.team_id, personUuid)
+ : Promise.resolve([])
+ }
+ return loaded
+ }
+ }
+}
+
+// Operation.CALL_GLOBAL from @posthog/hogvm, which is a const enum and can't be imported
+// under isolatedModules
+const CALL_GLOBAL = 2
+
+// Scans the compiled bytecode so expression-authored inCohort(...) calls count too. Matches the
+// call encoding [CALL_GLOBAL, name, argCount] rather than the bare name: string constants and
+// property chains put their text in the same flat array, and a stray match here would couple an
+// unrelated condition's run to the behavioral cohorts DB.
+function conditionReferencesCohorts(condition: { filters?: unknown }): boolean {
+ const bytecode = (condition.filters as HogFunctionFilters | null | undefined)?.bytecode
+ if (!Array.isArray(bytecode)) {
+ return false
+ }
+ return bytecode.some(
+ (op, index) =>
+ (op === 'inCohort' || op === 'notInCohort') &&
+ bytecode[index - 1] === CALL_GLOBAL &&
+ typeof bytecode[index + 1] === 'number'
+ )
}
export async function checkConditions(
invocation: CyclotronJobInvocationHogFlow,
- action: Extract<HogFlowAction, { type: 'conditional_branch' }>
+ action: Extract<HogFlowAction, { type: 'conditional_branch' }>,
+ loadMemberCohortIds?: () => Promise<number[]>
): Promise<{
scheduledAt?: DateTime
nextAction?: HogFlowAction
}> {
// the index is used to find the right edge
for (const [index, condition] of action.config.conditions.entries()) {
+ // Loaded only when evaluation actually reaches a cohort condition, so a run whose earlier
+ // condition matches never touches the behavioral cohorts DB. A lookup failure throws here
+ // on purpose (following the action's on_error) instead of guessing non-membership; the
+ // inCohort/notInCohort STL functions read the resulting cohort_ids global.
+ const cohortGlobals =
+ loadMemberCohortIds && conditionReferencesCohorts(condition)
+ ? { cohort_ids: await loadMemberCohortIds() }
+ : {}
+
// TODO(team-workflows): Figure out error handling here - do we throw or just move on to other conditions?
const filterResults = await filterFunctionInstrumented({
fn: invocation.hogFlow,
filters: condition.filters,
- filterGlobals: { ...invocation.filterGlobals, variables: invocation.state.variables },
+ filterGlobals: {
+ ...invocation.filterGlobals,
+ variables: invocation.state.variables,
+ ...cohortGlobals,
+ },
})
if (filterResults.match) {
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index 4ee6c08503ab..29b1460b3d91 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -26,6 +26,7 @@ import { TeamWorkflowsConfigService } from '../managers/team-workflows-config.se
import { EmailSuppressionService, emailSuppressionConfigFromEnv } from '../messaging/email-suppression.service'
import { EmailValidationService } from '../messaging/email-validation.service'
import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'
+import { CohortMembershipRepository } from '../cohorts/cohort-membership-repository'
import { HogFlowExecutorService, createHogFlowInvocation } from './hogflow-executor.service'
import { HogFlowFunctionsService } from './hogflow-functions.service'
@@ -157,10 +158,14 @@ describe('Hogflow Executor', () => {
await insertHogFunctionTemplate(hub.postgres, posthogCaptureTemplate)
+ const stubCohortMembershipRepository: CohortMembershipRepository = {
+ getMemberCohortIds: () => Promise.resolve([]),
+ }
executor = new HogFlowExecutorService(
hogFlowFunctionsService,
recipientPreferencesService,
- emailValidationService
+ emailValidationService,
+ stubCohortMembershipRepository
)
})
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
index ec60b4721ce7..ecc1a2df8629 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts
@@ -21,6 +21,7 @@ import {
} from '../../types'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../../utils/hog-function-filtering'
import { createInvocationResult } from '../../utils/invocation-utils'
+import { CohortMembershipRepository } from '../cohorts/cohort-membership-repository'
import { HogExecutorExecuteAsyncOptions } from '../hog-executor-async.service'
import { EmailValidationService } from '../messaging/email-validation.service'
import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'
@@ -112,6 +113,7 @@ export class HogFlowExecutorService {
hogFlowFunctionsService: HogFlowFunctionsService,
recipientPreferencesService: RecipientPreferencesService,
emailValidationService: EmailValidationService,
+ cohortMembershipRepository: CohortMembershipRepository,
duplicateObserver?: HogFlowDuplicateObserverService
) {
this.hogFlowFunctionsService = hogFlowFunctionsService
@@ -137,8 +139,8 @@ export class HogFlowExecutorService {
this.actionHandlers = {
trigger: new TriggerHandler(),
- conditional_branch: new ConditionalBranchHandler(),
- wait_until_condition: new ConditionalBranchHandler(),
+ conditional_branch: new ConditionalBranchHandler(cohortMembershipRepository),
+ wait_until_condition: new ConditionalBranchHandler(cohortMembershipRepository),
delay: new DelayHandler(),
wait_until_time_window: new WaitUntilTimeWindowHandler(),
random_cohort_branch: new RandomCohortBranchHandler(),
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index eea5a1f32c79..344500a97dc6 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -191,6 +191,7 @@ export type HogFunctionFilterGlobals = {
}
variables: Record<string, any> | undefined // For HogFlows, workflow-level variables
+ cohort_ids?: number[] // Cohorts the person is a member of, read by the inCohort/notInCohort STL functions
}
export type MetricLogSource = 'hog_function' | 'hog_flow' | 'legacy_plugin'
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 79b113ea33e8..7e6c7da8413f 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -42,13 +42,18 @@ import { UUIDT } from '~/common/utils/utils'
import { createCdpConsumerDeps } from '~/tests/helpers/cdp'
import { waitForExpect } from '~/tests/helpers/expectations'
import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'
-import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'
+import { getFirstTeam, resetBehavioralCohortsDatabase, resetTestDatabase } from '~/tests/helpers/sql'
import { Hub, Team } from '../../src/types'
import { createRedisV2PoolFromConfig } from '../common/redis/redis-v2'
import { FixtureHogFlowBuilder } from './_tests/builders/hogflow.builder'
import { HOG_FILTERS_EXAMPLES, HOG_FLOW_MASK_EXAMPLES } from './_tests/examples'
-import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from './_tests/fixtures'
+import {
+ createHogExecutionGlobals,
+ insertCohortMembership,
+ insertHogFunctionTemplate,
+ insertIntegration,
+} from './_tests/fixtures'
import { insertHogFlow } from './_tests/fixtures-hogflows'
import { CdpApi } from './cdp-api'
import { CdpCyclotronWorkerBatchResolve } from './consumers/cdp-cyclotron-worker-batch-resolve.consumer'
@@ -644,6 +649,89 @@ describe('Workflows E2E (postgres-v2)', () => {
})
})
+ describe('cohort condition workflow', () => {
+ const COHORT_ID = 4242
+ const PERSON_UUID = 'a5f478a1-1d34-4c8a-a0b5-6a3b62e3f8a1'
+
+ // What the Django serializer compiles for a cohort condition filter; the shape is pinned
+ // from the Python side by test_hog_flow_conditional_branch_cohort_filter_compiles
+ const cohortConditionFilters = (cohortId: number): Record<string, any> => ({
+ bytecode: ['_H', 1, 33, cohortId, 32, 'cohort_ids', 1, 1, 2, 'inCohort', 2],
+ properties: [{ key: 'id', type: 'cohort', value: cohortId }],
+ })
+
+ beforeEach(async () => {
+ await resetBehavioralCohortsDatabase(hub.postgres)
+ // The person's uuid is the key the cohort_membership lookup runs against
+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([
+ {
+ id: '1',
+ uuid: PERSON_UUID,
+ team_id: team.id,
+ properties: {},
+ properties_last_updated_at: {},
+ properties_last_operation: null,
+ created_at: DateTime.utc(),
+ version: 1,
+ is_identified: true,
+ is_user_id: null,
+ last_seen_at: null,
+ distinct_id: 'distinct_id',
+ },
+ ])
+ await createWorkflow({
+ actions: {
+ trigger: trigger(),
+ branch: {
+ type: 'conditional_branch',
+ config: {
+ conditions: [{ filters: cohortConditionFilters(COHORT_ID) }],
+ },
+ },
+ function_member: fetchAction('https://example.com/in-cohort'),
+ function_non_member: fetchAction('https://example.com/not-in-cohort'),
+ exit: exitAction(),
+ },
+ edges: [
+ { from: 'trigger', to: 'branch', type: 'continue' },
+ { from: 'branch', to: 'function_member', type: 'branch', index: 0 },
+ { from: 'branch', to: 'function_non_member', type: 'continue' },
+ { from: 'function_member', to: 'exit', type: 'continue' },
+ { from: 'function_non_member', to: 'exit', type: 'continue' },
+ ],
+ })
+ globals = createGlobals()
+ })
+
+ it.each([
+ ['a membership row', true, 'https://example.com/in-cohort'],
+ ['an in_cohort=false row (person left)', false, 'https://example.com/not-in-cohort'],
+ ])('routes a person with %s down the right branch', async (_name, inCohort, expectedUrl) => {
+ await insertCohortMembership(hub.postgres, {
+ team_id: team.id,
+ cohort_id: COHORT_ID,
+ person_id: PERSON_UUID,
+ in_cohort: inCohort,
+ })
+
+ await triggerWorkflow(globals)
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith(expectedUrl, expect.anything())
+ })
+
+ it('routes a person the pipeline never wrote a row for as a non-member', async () => {
+ await triggerWorkflow(globals)
+
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/not-in-cohort', expect.anything())
+ })
+ })
+
describe('workflow disabled mid-execution', () => {
let hogFlowId: string
diff --git a/posthog/management/commands/survey_cohort_bytecode_stl.py b/posthog/management/commands/survey_cohort_bytecode_stl.py
index c4c64af743a0..2c184c6f6c7e 100644
--- a/posthog/management/commands/survey_cohort_bytecode_stl.py
+++ b/posthog/management/commands/survey_cohort_bytecode_stl.py
@@ -104,6 +104,8 @@ RUST_NATIVE_STL: frozenset[str] = frozenset(
"randomFloat",
}
)
+# inCohort/notInCohort exist in stl.rs but take 2 args (cohort_id, cohort_ids); stored realtime cohort
+# bytecode calls them with 1 arg, which the Rust VM can't run — so they stay flagged as gaps here.
RUST_HOG_STL: frozenset[str] = frozenset(
{"arrayCount", "arrayExists", "arrayFilter", "arrayMap", "arrayReduce", "sortableSemver"}
)
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 4237191f2320..9ba2b5c72cbe 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -1449,6 +1449,8 @@ pub fn hog_stl() -> Module {
"arrayFilter": [2, [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 33, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 9, 36, 2, 36, 7, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -40, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
"arrayMap": [2, [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 29, 36, 4, 36, 5, 45, 37, 7, 36, 2, 36, 7, 36, 0, 54, 1, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -36, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
"arrayReduce": [3, [36, 2, 36, 1, 36, 4, 2, "values", 1, 33, 1, 36, 5, 2, "length", 1, 31, 36, 7, 36, 6, 16, 40, 26, 36, 5, 36, 6, 45, 37, 8, 36, 3, 36, 8, 36, 0, 54, 2, 37, 3, 36, 6, 33, 1, 6, 37, 6, 39, -33, 35, 35, 35, 35, 35, 36, 3, 38, 35]],
+ "inCohort": [2, [31, 36, 1, 11, 40, 6, 32, "inCohort() requires cohort membership to be loaded for this evaluation", 2, "Error", 1, 49, 36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 25, 36, 3, 36, 4, 45, 37, 6, 36, 0, 36, 6, 11, 40, 2, 29, 38, 36, 4, 33, 1, 6, 37, 4, 39, -32, 35, 35, 35, 35, 35, 30, 38]],
+ "notInCohort": [2, [31, 36, 1, 11, 40, 6, 32, "notInCohort() requires cohort membership to be loaded for this evaluation", 2, "Error", 1, 49, 36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 25, 36, 3, 36, 4, 45, 37, 6, 36, 0, 36, 6, 11, 40, 2, 30, 38, 36, 4, 33, 1, 6, 37, 4, 39, -32, 35, 35, 35, 35, 35, 29, 38]],
"sortableSemver": [1, [31, 36, 0, 11, 40, 3, 43, 0, 38, 36, 0, 32, "(\\d+(\\.\\d+)+)", 2, "extractRegex", 2, 36, 1, 2, "empty", 1, 40, 3, 43, 0, 38, 32, ".", 36, 1, 2, "splitByString", 2, 52, "lambda", 1, 0, 11, 36, 0, 2, "toInt", 1, 47, 3, 35, 33, 0, 38, 53, 0, 36, 2, 2, "arrayMap", 2, 38, 35, 35]],
});