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): compile cohort filters in conditional branch conditions (#83800)

Meikel Ratzbdc12603b3a7
diff --git a/posthog/hogql/compiler/bytecode.py b/posthog/hogql/compiler/bytecode.py
index c2bf85fe22dd..307002108f09 100644
--- a/posthog/hogql/compiler/bytecode.py
+++ b/posthog/hogql/compiler/bytecode.py
@@ -96,6 +96,7 @@ def create_bytecode(
locals: Optional[list[Local]] = None,
cohort_membership_supported: Optional[bool] = False,
null_safe_comparisons: Optional[bool] = False,
+ allowed_cohort_ids: Optional[set[int]] = None,
) -> CompiledBytecode:
supported_functions = supported_functions or set()
bytecode: list[Any] = []
@@ -111,6 +112,7 @@ def create_bytecode(
locals,
cohort_membership_supported,
null_safe_comparisons,
+ allowed_cohort_ids,
)
bytecode.extend(compiler.visit(expr))
return CompiledBytecode(bytecode, locals=compiler.locals, upvalues=compiler.upvalues)
@@ -129,6 +131,7 @@ class BytecodeCompiler(Visitor):
locals: Optional[list[Local]] = None,
cohort_membership_supported: Optional[bool] = False,
null_safe_comparisons: Optional[bool] = False,
+ allowed_cohort_ids: Optional[set[int]] = None,
):
super().__init__()
self.enclosing = enclosing
@@ -141,6 +144,8 @@ class BytecodeCompiler(Visitor):
self.args = args
self.cohort_membership_supported = cohort_membership_supported
self.null_safe_comparisons = null_safe_comparisons
+ self.allowed_cohort_ids = allowed_cohort_ids
+ self._compiling_cohort_membership_call = False
# we're in a function definition
if args is not None:
for arg in args:
@@ -225,10 +230,21 @@ class BytecodeCompiler(Visitor):
operation = COMPARE_OPERATIONS[node.op]
if operation in [Operation.IN_COHORT, Operation.NOT_IN_COHORT]:
if self.cohort_membership_supported:
- if operation == Operation.IN_COHORT:
- return self.visit(ast.Call(name="inCohort", args=[node.right]))
- else:
- return self.visit(ast.Call(name="notInCohort", args=[node.right]))
+ if self.allowed_cohort_ids is not None:
+ if not isinstance(node.right, ast.Constant) or not isinstance(node.right.value, int):
+ raise QueryError("Cohort conditions require a constant cohort id.")
+ if node.right.value not in self.allowed_cohort_ids:
+ raise QueryError(
+ f"Cohort {node.right.value} can't be used here. "
+ "Reference cohorts through a cohort filter so they can be validated."
+ )
+ name = "inCohort" if operation == Operation.IN_COHORT else "notInCohort"
+ call = ast.Call(name=name, args=[node.right, ast.Field(chain=["cohort_ids"])])
+ self._compiling_cohort_membership_call = True
+ try:
+ return self.visit(call)
+ finally:
+ self._compiling_cohort_membership_call = False
else:
cohort_name = ""
if isinstance(node.right, ast.Constant):
@@ -401,6 +417,13 @@ class BytecodeCompiler(Visitor):
# Did not find a local nor an upvalue, must be a global.
+ if (
+ self.cohort_membership_supported
+ and node.chain[0] == "cohort_ids"
+ and not self._compiling_cohort_membership_call
+ ):
+ raise QueryError("cohort_ids is reserved here. Use a cohort property filter instead.")
+
chain = []
for element in reversed(node.chain):
chain.extend([Operation.STRING, element])
@@ -499,6 +522,8 @@ class BytecodeCompiler(Visitor):
def visit_call(self, node: ast.Call):
self._check_declared_call(node)
+ if node.name in ("inCohort", "notInCohort") and not self._compiling_cohort_membership_call:
+ raise QueryError(f"Can't call {node.name}() directly. Use a cohort property filter instead.")
if node.name == "not" and len(node.args) == 1:
return [*self.visit(node.args[0]), Operation.NOT]
if node.name == "and" and len(node.args) > 1:
@@ -1001,7 +1026,14 @@ class BytecodeCompiler(Visitor):
body = ast.Block(declarations=[node.body, ast.ReturnStatement(expr=None)])
self._declare_local(node.name)
- compiler = BytecodeCompiler(self.supported_functions, node.params, self.context, self)
+ compiler = BytecodeCompiler(
+ self.supported_functions,
+ node.params,
+ self.context,
+ self,
+ cohort_membership_supported=self.cohort_membership_supported,
+ allowed_cohort_ids=self.allowed_cohort_ids,
+ )
bytecode = compiler.visit(body)
ops = [
@@ -1034,7 +1066,14 @@ class BytecodeCompiler(Visitor):
else:
expr = ast.ReturnStatement(expr=expr)
- compiler = BytecodeCompiler(self.supported_functions, node.args, self.context, self)
+ compiler = BytecodeCompiler(
+ self.supported_functions,
+ node.args,
+ self.context,
+ self,
+ cohort_membership_supported=self.cohort_membership_supported,
+ allowed_cohort_ids=self.allowed_cohort_ids,
+ )
bytecode = compiler.visit(expr)
ops = [
Operation.CALLABLE,
diff --git a/products/cdp/backend/filters.py b/products/cdp/backend/filters.py
index 06472e9f3912..a0bd8959adab 100644
--- a/products/cdp/backend/filters.py
+++ b/products/cdp/backend/filters.py
@@ -387,14 +387,59 @@ def hog_function_filters_to_expr(filters: dict, team: Team, actions: dict[int, A
def filter_action_ids(filters: Optional[dict]) -> list[int]:
- if not filters:
+ if not isinstance(filters, dict):
return []
try:
return [int(action["id"]) for action in filters.get("actions", [])]
- except KeyError:
+ except (KeyError, TypeError, ValueError):
return []
+def collect_property_cohort_ids(node: Any) -> set[int]:
+ """Cohort ids in a property tree (lists, AND/OR groups, and cohort leaves)."""
+ ids: set[int] = set()
+
+ def _walk(current: Any) -> None:
+ if isinstance(current, list):
+ for item in current:
+ _walk(item)
+ return
+ if not isinstance(current, dict):
+ return
+ if current.get("type") in ("AND", "OR"):
+ _walk(current.get("values") or [])
+ return
+ if _is_cohort_filter(current):
+ value = current.get("value")
+ if isinstance(value, str | int) and not isinstance(value, bool):
+ try:
+ ids.add(int(value))
+ except ValueError:
+ pass
+
+ _walk(node)
+ return ids
+
+
+def filter_cohort_ids(filters: Optional[dict]) -> list[int]:
+ """Cohort ids referenced by the filters' property tree, for save-time eligibility validation.
+
+ Total over untrusted input, like filter_action_ids: callers scan raw client filters
+ before DRF validation, so a malformed shape yields [] instead of raising.
+ """
+ if not isinstance(filters, dict):
+ return []
+
+ ids = collect_property_cohort_ids(filters.get("properties") or [])
+ for key in ("events", "actions"):
+ entries = filters.get(key)
+ if isinstance(entries, list):
+ for entry in entries:
+ if isinstance(entry, dict):
+ ids |= collect_property_cohort_ids(entry.get("properties") or [])
+ return sorted(ids)
+
+
def compile_filters_expr(filters: Optional[dict], team: Team, actions: Optional[dict[int, Action]] = None) -> ast.Expr:
filters = filters or {}
@@ -480,10 +525,21 @@ TEMPLATE_CALLABLES: set[str] = set(_RUNTIME["callables"])
_UNKNOWN_GLOBAL = "Unknown global variable: "
-def _unknown_filter_globals(expr: ast.Expr) -> list[str]:
+def _declared_globals(cohort_membership_supported: bool) -> dict[str, None]:
+ declared = dict.fromkeys(FILTER_GLOBALS)
+ if cohort_membership_supported:
+ declared["cohort_ids"] = None
+ return declared
+
+
+def _unknown_filter_globals(expr: ast.Expr, cohort_membership_supported: bool = False) -> list[str]:
"""Compile once with the runtime's globals declared, and return the roots the runtime will not have."""
- context = HogQLContext(team_id=None, globals=dict.fromkeys(FILTER_GLOBALS), allowed_functions=FILTER_FUNCTIONS)
- create_bytecode(expr, context=context)
+ context = HogQLContext(
+ team_id=None,
+ globals=_declared_globals(cohort_membership_supported),
+ allowed_functions=FILTER_FUNCTIONS,
+ )
+ create_bytecode(expr, context=context, cohort_membership_supported=cohort_membership_supported)
return sorted(
{w.message.removeprefix(_UNKNOWN_GLOBAL) for w in context.warnings if w.message.startswith(_UNKNOWN_GLOBAL)}
)
@@ -497,39 +553,78 @@ class _RuntimeCompilation:
context: HogQLContext
-def _compile_against_runtime(expr: ast.Expr, team: Team) -> _RuntimeCompilation:
+def _compile_against_runtime(
+ expr: ast.Expr,
+ team: Team,
+ cohort_membership_supported: bool = False,
+ allowed_cohort_ids: Optional[set[int]] = None,
+) -> _RuntimeCompilation:
# Declaring the globals turns the compiler's field resolution into a check: it warns on a
# root that is neither a local, an upvalue, nor one of ours.
- context = HogQLContext(team_id=team.id, globals=dict.fromkeys(FILTER_GLOBALS), allowed_functions=FILTER_FUNCTIONS)
- bytecode = create_bytecode(expr, context=context).bytecode
+ context = HogQLContext(
+ team_id=team.id,
+ globals=_declared_globals(cohort_membership_supported),
+ allowed_functions=FILTER_FUNCTIONS,
+ )
+ bytecode = create_bytecode(
+ expr,
+ context=context,
+ cohort_membership_supported=cohort_membership_supported,
+ allowed_cohort_ids=allowed_cohort_ids,
+ ).bytecode
unknown = sorted(
{w.message.removeprefix(_UNKNOWN_GLOBAL) for w in context.warnings if w.message.startswith(_UNKNOWN_GLOBAL)}
)
return _RuntimeCompilation(bytecode=bytecode, unknown_roots=unknown, context=context)
-def _own_filters_expr(filters: dict, team: Team, actions: Optional[dict[int, Action]]) -> ast.Expr:
+def _own_filters_expr(
+ filters: dict,
+ team: Team,
+ actions: Optional[dict[int, Action]],
+ cohort_membership_supported: bool = False,
+) -> ast.Expr:
"""The destination's filters without the team's test account filters, with warehouse columns resolved."""
own = _LowerConstantMembership().visit(
compile_filters_expr({**filters, "filter_test_accounts": False}, team, actions)
)
if filters.get("source") in DATA_WAREHOUSE_SOURCES:
- own = _WarehouseRowFields(roots=set(_compile_against_runtime(own, team).unknown_roots)).visit(own)
+ own = _WarehouseRowFields(
+ roots=set(
+ _compile_against_runtime(
+ own, team, cohort_membership_supported=cohort_membership_supported
+ ).unknown_roots
+ )
+ ).visit(own)
return own
-def _resolve_warehouse_columns(filters: dict, team: Team, actions: Optional[dict[int, Action]]) -> ast.Expr:
+def _resolve_warehouse_columns(
+ filters: dict,
+ team: Team,
+ actions: Optional[dict[int, Action]],
+ cohort_membership_supported: bool = False,
+) -> ast.Expr:
"""
Only the destination's own filters read the row. The team's test account filters are written
against events, so a root they read that the runtime lacks stays an error rather than becoming
a column.
"""
return _combine_expressions(
- [*_build_test_account_filters(filters, team), _own_filters_expr(filters, team, actions)]
+ [
+ *_build_test_account_filters(filters, team),
+ _own_filters_expr(filters, team, actions, cohort_membership_supported=cohort_membership_supported),
+ ]
)
-def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optional[dict[int, Action]] = None) -> dict:
+def compile_filters_bytecode(
+ filters: Optional[dict],
+ team: Team,
+ actions: Optional[dict[int, Action]] = None,
+ cohort_membership_supported: bool = False,
+ allowed_cohort_ids: Optional[set[int]] = None,
+) -> dict:
filters = filters or {}
try:
expr = compile_filters_expr(filters, team, actions)
@@ -537,9 +632,16 @@ def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optio
raise Exception("Select queries are not allowed in filters")
expr = _LowerConstantMembership().visit(expr)
- compiled = _compile_against_runtime(expr, team)
+ compiled = _compile_against_runtime(expr, team, cohort_membership_supported, allowed_cohort_ids)
if compiled.unknown_roots and filters.get("source") in DATA_WAREHOUSE_SOURCES:
- compiled = _compile_against_runtime(_resolve_warehouse_columns(filters, team, actions), team)
+ compiled = _compile_against_runtime(
+ _resolve_warehouse_columns(
+ filters, team, actions, cohort_membership_supported=cohort_membership_supported
+ ),
+ team,
+ cohort_membership_supported,
+ allowed_cohort_ids,
+ )
filters["bytecode"] = compiled.bytecode
filters["bytecode_contract"] = RUNTIME_CONTRACT
unknown = compiled.unknown_roots
@@ -552,7 +654,10 @@ def compile_filters_bytecode(filters: Optional[dict], team: Team, actions: Optio
if from_team:
# Compile the destination's own filters alone rather than subtracting the team's
# roots: a field that both sources read drops out of the difference and goes unnamed.
- own = _unknown_filter_globals(_own_filters_expr(filters, team, actions))
+ own = _unknown_filter_globals(
+ _own_filters_expr(filters, team, actions, cohort_membership_supported=cohort_membership_supported),
+ cohort_membership_supported,
+ )
raise Exception(
f"Your internal/test user filters read {', '.join(from_team)}, which real-time filters "
f"cannot read. Check the spelling, or use a field or function that real-time filters support. "
diff --git a/products/cdp/backend/presentation/hog_functions.py b/products/cdp/backend/presentation/hog_functions.py
index ca7de9183255..93f9c92cf6b1 100644
--- a/products/cdp/backend/presentation/hog_functions.py
+++ b/products/cdp/backend/presentation/hog_functions.py
@@ -8,6 +8,8 @@ return untyped bytecode, so they cannot cross through the facade.
from products.cdp.backend.filters import (
DATA_WAREHOUSE_SOURCES as DATA_WAREHOUSE_SOURCES,
compile_filters_expr as compile_filters_expr,
+ filter_action_ids as filter_action_ids,
+ filter_cohort_ids as filter_cohort_ids,
)
from products.cdp.backend.flag_gated_templates import (
FLAG_GATED_TEMPLATE_IDS as FLAG_GATED_TEMPLATE_IDS,
diff --git a/products/cdp/backend/test/test_filters.py b/products/cdp/backend/test/test_filters.py
index 25f7165449e5..151259ea6317 100644
--- a/products/cdp/backend/test/test_filters.py
+++ b/products/cdp/backend/test/test_filters.py
@@ -453,7 +453,7 @@ class TestHogFunctionFilters(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest
# where it takes three.
for key, expected in (
("lower() = 'a'", "`lower` takes exactly 1 arguments, got 0"),
- ("inCohort(1)", "`inCohort` takes exactly 2 arguments, got 1"),
+ ("startsWith('a')", "`startsWith` takes exactly 2 arguments, got 1"),
("dateAdd(toIntervalDay(1), timestamp) > now()", "`dateAdd` takes exactly 3 arguments, got 2"),
):
response = compile_filters_bytecode(filters={"properties": [{"type": "hogql", "key": key}]}, team=self.team)
diff --git a/products/cdp/backend/validation.py b/products/cdp/backend/validation.py
index cd7cce79ea59..cb22cb4bbe78 100644
--- a/products/cdp/backend/validation.py
+++ b/products/cdp/backend/validation.py
@@ -17,20 +17,26 @@ from posthog.hogql.parser import parse_program, parse_string_template
from posthog.hogql.visitor import TraversingVisitor
from posthog.models.integration import POSTHOG_CONNECT_KIND, Integration
+from posthog.models.team.team import Team
+from products.actions.backend.models.action import Action
from products.cdp.backend.filters import (
DATA_WAREHOUSE_SOURCES,
FILTER_FUNCTIONS,
RUNTIME_CONTRACT,
TEMPLATE_CALLABLES,
TEMPLATE_GLOBALS,
+ collect_property_cohort_ids,
compile_filters_bytecode,
compile_filters_expr,
+ filter_action_ids,
+ filter_cohort_ids,
)
from products.cdp.backend.models.hog_functions.hog_function import (
TYPES_WITH_JAVASCRIPT_SOURCE,
TYPES_WITH_TRANSPILED_FILTERS,
)
+from products.cohorts.backend.models.cohort import Cohort
from common.hogvm.python.stl import STL
from common.hogvm.python.stl.bytecode import BYTECODE_STL
@@ -1184,7 +1190,16 @@ class HogFunctionFiltersSerializer(serializers.Serializer):
if "bytecode" in data:
del data["bytecode"]
else:
- data = compile_filters_bytecode(data, team)
+ cohort_membership_supported = bool(self.context.get("cohort_membership_supported"))
+ validated_cohort_ids: Optional[set[int]] = None
+ if cohort_membership_supported:
+ validated_cohort_ids = self._validate_realtime_cohorts(data, team)
+ data = compile_filters_bytecode(
+ data,
+ team,
+ cohort_membership_supported=cohort_membership_supported,
+ allowed_cohort_ids=validated_cohort_ids,
+ )
# Uncompilable filters are only fatal when the function will run (stay enabled).
# Callers that allow saving anyway (e.g. disabling/deleting a hog function) opt out
# via context; the error stays persisted on the filters for the UI to surface.
@@ -1193,6 +1208,40 @@ class HogFunctionFiltersSerializer(serializers.Serializer):
return data
+ def _validate_realtime_cohorts(self, data: dict, team: Team) -> set[int]:
+ """A cohort without maintained cohort_membership rows would evaluate everyone as a non-member.
+
+ Returns the validated ids so the compiler can reject any IN COHORT operand outside them.
+ Error messages carry the id rather than the name: they surface to callers holding only
+ workflow scopes, and a name would hand them a cohort-metadata oracle.
+ """
+ collected = set(filter_cohort_ids(data))
+ action_ids = filter_action_ids(data)
+ if action_ids:
+ # nosemgrep: idor-lookup-without-team (scoped by team__project_id)
+ for action in Action.objects.filter(id__in=action_ids, team__project_id=team.project_id, deleted=False):
+ for step in action.steps:
+ collected |= collect_property_cohort_ids(step.properties or [])
+ cohort_ids = sorted(collected)
+ if not cohort_ids:
+ return set()
+
+ cohorts = {cohort.pk: cohort for cohort in Cohort.objects.filter(pk__in=cohort_ids, team=team, deleted=False)}
+ for cohort_id in cohort_ids:
+ cohort = cohorts.get(cohort_id)
+ if cohort is None:
+ raise serializers.ValidationError(f"Cohort {cohort_id} doesn't exist in this environment.")
+ if cohort.is_static:
+ raise serializers.ValidationError(
+ f"Cohort {cohort_id} is a static cohort. Conditions can only use realtime cohorts."
+ )
+ if not cohort.is_flag_compatible:
+ raise serializers.ValidationError(
+ f"Cohort {cohort_id} isn't ready for realtime evaluation. "
+ f"Conditions can only use realtime cohorts that have finished calculating."
+ )
+ return set(cohort_ids)
+
class FunctionInputsSerializer(serializers.Serializer):
inputs_schema = InputsSchemaSerializer(required=False)
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index feb116e86d2a..afe8c3080914 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -68,6 +68,7 @@ from posthog.permissions import (
is_service_auth,
posthog_feature_flag_enabled,
)
+from posthog.ph_client import feature_enabled_or_false
from posthog.plugins.plugin_server_api import (
cancel_hog_flow_batch_job,
cancel_hog_flow_invocations,
@@ -89,6 +90,8 @@ from products.cdp.backend.presentation.hog_functions import (
DATA_WAREHOUSE_SOURCES,
FLAG_GATED_TEMPLATE_IDS,
compile_filters_expr,
+ filter_action_ids,
+ filter_cohort_ids,
gated_template_enabled,
)
from products.cdp.backend.presentation.hog_invocations.cancel import (
@@ -315,6 +318,22 @@ _LookupResult = TypeVar("_LookupResult", Workflow, WorkflowRef, WorkflowEditStat
# been through validation. Comparing them would make an unchanged condition look edited.
_DERIVED_FILTER_KEYS = ("bytecode", "bytecode_error", "bytecode_contract", "source")
+WORKFLOWS_COHORT_CONDITIONS_FLAG = "workflows-cohort-conditions"
+
+
+def _cohort_conditions_rolled_out(user: Any, organization_id: str) -> bool:
+ try:
+ return feature_enabled_or_false(
+ WORKFLOWS_COHORT_CONDITIONS_FLAG,
+ user.distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ return False
+
def _authored_condition(condition: Optional[dict]) -> Optional[dict]:
"""The parts of a wait condition a person actually wrote, with compiler output dropped."""
@@ -364,6 +383,38 @@ def _branch_delay_duration_already_stored(action: dict, context: dict) -> bool:
return stored[action_id] == (action.get("config") or {}).get("delay_duration")
+def _cohort_condition_already_stored(action: dict, condition: dict, context: dict) -> bool:
+ """
+ True when this conditional_branch condition matches one already persisted for the same action.
+
+ Mirrors _wait_condition_already_stored: the cohort-conditions flag polices new adoption, not
+ edits around an accepted condition. Without this, a flag dial-down (or an internal re-save,
+ which has no request to evaluate the flag against) would fail compilation of an active flow's
+ unchanged cohort conditions.
+ """
+ stored = context.get("stored_cohort_conditions")
+ if not stored:
+ return False
+ action_id = action.get("id")
+ if action_id not in stored:
+ return False
+ return _authored_condition(condition) in stored[action_id]
+
+
+def _actions_reference_cohorts(actions: Any) -> bool:
+ """True when a conditional_branch condition in these actions can compile to a cohort membership check."""
+ if not isinstance(actions, list):
+ return False
+ for flow_action in actions:
+ if not isinstance(flow_action, dict) or flow_action.get("type") != "conditional_branch":
+ continue
+ for condition in (flow_action.get("config") or {}).get("conditions") or []:
+ filters = condition.get("filters") if isinstance(condition, dict) else None
+ if isinstance(filters, dict) and (filter_cohort_ids(filters) or filter_action_ids(filters)):
+ return True
+ return False
+
+
def _reject_clock_based_wait(config: dict, team: Team) -> None:
"""
Refuse a wait whose condition depends on the clock rather than on something happening.
@@ -1305,6 +1356,26 @@ class HogFlowActionSerializer(serializers.Serializer):
self.initial_data = data
return super().to_internal_value(data)
+ _cohort_conditions_flag: Optional[bool] = None
+
+ def _cohort_conditions_enabled(self) -> bool:
+ if self._cohort_conditions_flag is None:
+ self._cohort_conditions_flag = self._check_cohort_conditions_flag()
+ return self._cohort_conditions_flag
+
+ def _check_cohort_conditions_flag(self) -> bool:
+ try:
+ request = self.context.get("request")
+ user = getattr(request, "user", None)
+ if user is None or user.is_anonymous or isinstance(user, SyntheticUser):
+ return False
+ get_team = self.context.get("get_team")
+ if get_team is None:
+ return False
+ return _cohort_conditions_rolled_out(user, str(get_team().organization_id))
+ except Exception:
+ return False
+
def _reject_behavioral_cohorts_in_audience(self, properties) -> None:
# Batch/schedule audiences resolve offline by precalculated membership and can't evaluate event
# behavior the way it's intended; the UI hides behavioral cohorts from the audience picker. Mirror
@@ -1777,7 +1848,20 @@ class HogFlowActionSerializer(serializers.Serializer):
if strict:
raise serializers.ValidationError("Event filters are not allowed in conditionals")
else:
- serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)
+ cohorts_supported = (
+ is_conditional_branch
+ and (bool(filter_cohort_ids(filters)) or bool(filter_action_ids(filters)))
+ and (
+ _cohort_condition_already_stored(data, condition, self.context)
+ or self._cohort_conditions_enabled()
+ )
+ )
+ serializer = HogFunctionFiltersSerializer(
+ data=filters,
+ context={**self.context, "cohort_membership_supported": True}
+ if cohorts_supported
+ else self.context,
+ )
if not strict:
if serializer.is_valid():
condition["filters"] = serializer.validated_data
@@ -2885,6 +2969,19 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
and (action.get("config") or {}).get("template_id") in FLAG_GATED_TEMPLATE_IDS
}
+ self.context["stored_cohort_conditions"] = {
+ action["id"]: [
+ _authored_condition(stored_condition)
+ for stored_condition in [
+ *((action.get("config") or {}).get("conditions") or []),
+ (action.get("config") or {}).get("condition"),
+ ]
+ if isinstance(stored_condition, dict)
+ ]
+ for action in ((instance.actions if instance and instance.status == HogFlow.State.ACTIVE else None) or [])
+ if isinstance(action, dict) and action.get("id") and action.get("type") == "conditional_branch"
+ }
+
status = data.get("status")
if status is None and instance:
status = instance.status
@@ -4325,7 +4422,10 @@ class HogFlowViewSet(
# as a group-property oracle. Require group:read on top. The web builder uses session auth, so
# running tests while editing is unaffected.
if self.action == "invocations":
- return ["hog_flow:write", "group:read"]
+ scopes = ["hog_flow:write", "group:read"]
+ if self._test_invocation_may_read_cohort_membership(request):
+ scopes.append("person:read")
+ return scopes
# Rerun re-executes stored invocations — it replays up to 30 days of
# persisted event/person/group data through the current (possibly
# reconfigured) workflow. A `hog_flow:write`-only token could use that to
@@ -4337,6 +4437,35 @@ class HogFlowViewSet(
return ["hog_flow:write", "person:read", "group:read"]
return None
+ _cohort_conditions_rollout: Optional[bool] = None
+
+ def _test_invocation_may_read_cohort_membership(self, request: Request) -> bool:
+ workflow_id = self.kwargs.get("pk")
+ if workflow_id is None:
+ return False
+ if self._cohort_conditions_rollout is None:
+ user = getattr(request, "user", None)
+ self._cohort_conditions_rollout = (
+ user is not None
+ and not user.is_anonymous
+ and not isinstance(user, SyntheticUser)
+ and _cohort_conditions_rolled_out(user, str(self.team.organization_id))
+ )
+ if self._cohort_conditions_rollout:
+ return True
+ data = request.data if isinstance(request.data, dict) else {}
+ configuration = data.get("configuration")
+ if _actions_reference_cohorts(configuration.get("actions") if isinstance(configuration, dict) else None):
+ return True
+ try:
+ hog_flow = get_workflow_edit_state(
+ team_id=self.team_id, workflow_id=workflow_id, user_access_control=None, required_level=None
+ )
+ except WorkflowNotFound:
+ return False
+ draft_actions = hog_flow.draft.get("actions") if isinstance(hog_flow.draft, dict) else None
+ return _actions_reference_cohorts(hog_flow.actions) or _actions_reference_cohorts(draft_actions)
+
def get_serializer_class(self) -> type[BaseSerializer]:
if self.action == "list":
# MCP list ("workflows-list") is a discovery/summary tool — return metadata only so it
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 1e7cd7b13092..99659ee80cac 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -34,7 +34,7 @@ from products.cdp.backend.flag_gated_templates import gated_template_enabled
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.templates.fixtures import template_slack
from products.cdp.backend.templates.hog_function_template import sync_template_to_db
-from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.facade.contracts import WorkflowLastRunDTO
from products.workflows.backend.facade.writes import update_workflow
@@ -52,6 +52,8 @@ _WIDER_AUDIENCE_CONDITION = {"key": "email", "type": "person", "value": "@", "op
webhook_template = MOCK_NODE_TEMPLATES[0]
+BACKFILLED_AT = datetime(2026, 1, 1, tzinfo=UTC)
+
class _StubAccountAudienceProvider:
def __init__(self, group_type: str | None):
@@ -1720,6 +1722,337 @@ class TestHogFlowAPI(APIBaseTest):
assert "bytecode" in conditions[0]["filters"], conditions[0]["filters"]
assert conditions[0]["filters"]["bytecode"] == ["_H", 1, 32, "custom_event", 32, "event", 1, 1, 11]
+ def _create_behavioral_cohort(
+ self, cohort_type: Optional[CohortType], backfilled: bool, team: Optional[Team] = None
+ ) -> Cohort:
+ cohort_kwargs: dict[str, Any] = {
+ "team": team or self.team,
+ "name": "power-users",
+ "filters": {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "key": "$pageview",
+ "event_type": "events",
+ "time_value": 2,
+ "time_interval": "week",
+ "value": "performed_event_first_time",
+ "type": "behavioral",
+ },
+ ],
+ }
+ },
+ }
+ if cohort_type is not None:
+ cohort_kwargs["cohort_type"] = cohort_type
+ if backfilled:
+ cohort_kwargs["last_backfill_person_properties_at"] = BACKFILLED_AT
+ cohort_kwargs["last_backfill_events_at"] = BACKFILLED_AT
+ return Cohort.objects.create(**cohort_kwargs)
+
+ def _hog_flow_with_condition_filters(self, action_type: str, filters: dict) -> dict:
+ condition_key = "conditions" if action_type == "conditional_branch" else "condition"
+ config: dict[str, Any] = (
+ {"conditions": [{"filters": filters}]}
+ if action_type == "conditional_branch"
+ else {"condition": {"filters": filters}, "max_wait_duration": "1h"}
+ )
+ assert condition_key in config
+ return {
+ "name": "Test Flow",
+ "status": "active",
+ "actions": [
+ {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {
+ "type": "event",
+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},
+ },
+ },
+ {"id": "cond_1", "name": "cond_1", "type": action_type, "config": config},
+ ],
+ }
+
+ @parameterized.expand(
+ [
+ ("in_operator", None, "inCohort"),
+ ("not_in_operator", "not_in", "notInCohort"),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_conditional_branch_cohort_filter_compiles(self, _name, operator, expected_call, _mock_flag):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ cohort_property: dict[str, Any] = {"key": "id", "type": "cohort", "value": cohort.id}
+ if operator:
+ cohort_property["operator"] = operator
+ hog_flow = self._hog_flow_with_condition_filters("conditional_branch", {"properties": [cohort_property]})
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 201, response.json()
+ filters = response.json()["actions"][1]["config"]["conditions"][0]["filters"]
+ assert filters["bytecode"] == ["_H", 1, 33, cohort.id, 32, "cohort_ids", 1, 1, 2, expected_call, 2]
+ assert "cohort_ids" not in filters
+
+ @parameterized.expand(
+ [
+ ("static_cohort", "static", "is a static cohort"),
+ ("dynamic_behavioral_cohort", "dynamic", "isn't ready for realtime evaluation"),
+ ("realtime_not_backfilled", "realtime_unbackfilled", "isn't ready for realtime evaluation"),
+ ("missing_cohort", "missing", "doesn't exist in this environment"),
+ ("sibling_environment_cohort", "sibling_environment", "doesn't exist in this environment"),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_conditional_branch_rejects_ineligible_cohorts(
+ self, _name, cohort_kind, expected_detail, _mock_flag
+ ):
+ if cohort_kind == "static":
+ cohort_id = Cohort.objects.create(team=self.team, name="static-cohort", is_static=True).id
+ elif cohort_kind == "dynamic":
+ cohort_id = self._create_behavioral_cohort(None, backfilled=False).id
+ elif cohort_kind == "realtime_unbackfilled":
+ cohort_id = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=False).id
+ elif cohort_kind == "sibling_environment":
+ sibling_team = Team.objects.create(organization=self.organization, project=self.project, name="sibling env")
+ cohort_id = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True, team=sibling_team).id
+ else:
+ cohort_id = 999999
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch", {"properties": [{"key": "id", "type": "cohort", "value": cohort_id}]}
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert expected_detail in response.json()["detail"]
+
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_conditional_branch_validates_cohorts_nested_in_action_filters(self, _mock_flag):
+ eligible = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ static_cohort = Cohort.objects.create(team=self.team, name="static-cohort", is_static=True)
+ action = Action.objects.create(team=self.team, name="Converted", steps_json=[{"event": "converted"}])
+ filters = {
+ "properties": [{"key": "id", "type": "cohort", "value": eligible.id}],
+ "actions": [
+ {
+ "id": str(action.id),
+ "type": "actions",
+ "properties": [{"key": "id", "type": "cohort", "value": static_cohort.id}],
+ }
+ ],
+ }
+ hog_flow = self._hog_flow_with_condition_filters("conditional_branch", filters)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert "is a static cohort" in response.json()["detail"]
+
+ def test_hog_flow_conditional_branch_rejects_cohort_filters_without_flag(self):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch", {"properties": [{"key": "id", "type": "cohort", "value": cohort.id}]}
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert "Cohort membership can't be evaluated in real-time filters" in response.json()["detail"]
+
+ def test_hog_flow_grandfathers_stored_cohort_conditions_after_flag_dial_down(self):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ other_cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch", {"properties": [{"key": "id", "type": "cohort", "value": cohort.id}]}
+ )
+ with patch(
+ "products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True
+ ):
+ created = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+ assert created.status_code == 201, created.json()
+ flow_id = created.json()["id"]
+ stored_actions = created.json()["actions"]
+
+ with patch(
+ "products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=False
+ ):
+ resave = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"name": "renamed", "actions": stored_actions},
+ )
+ assert resave.status_code == 200, resave.json()
+
+ edited_actions = deepcopy(stored_actions)
+ edited_actions[1]["config"]["conditions"].append(
+ {"filters": {"properties": [{"key": "id", "type": "cohort", "value": other_cohort.id}]}}
+ )
+ new_adoption = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ {"actions": edited_actions},
+ )
+ assert new_adoption.status_code == 400, new_adoption.json()
+ assert "Cohort membership can't be evaluated" in new_adoption.json()["detail"]
+
+ @parameterized.expand(
+ [
+ ("expression_only", False),
+ ("mixed_with_structured_cohort", True),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_rejects_hand_authored_incohort_calls(self, _name, include_structured_leaf, _mock_flag):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ properties: list[dict[str, Any]] = [{"key": "inCohort(999999)", "type": "hogql"}]
+ if include_structured_leaf:
+ properties.insert(0, {"key": "id", "type": "cohort", "value": cohort.id})
+ hog_flow = self._hog_flow_with_condition_filters("conditional_branch", {"properties": properties})
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert "Can't call inCohort() directly" in response.json()["detail"]
+
+ @parameterized.expand(
+ [
+ ("top_level", "999999 in cohort_ids"),
+ ("inside_a_lambda", "arrayExists(x -> 999999 in cohort_ids, [1])"),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_rejects_authored_reads_of_the_cohort_ids_global(self, _name, expression, _mock_flag):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ properties: list[dict[str, Any]] = [
+ {"key": "id", "type": "cohort", "value": cohort.id},
+ {"key": expression, "type": "hogql"},
+ ]
+ hog_flow = self._hog_flow_with_condition_filters("conditional_branch", {"properties": properties})
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert "cohort_ids is reserved" in response.json()["detail"]
+
+ @parameterized.expand(
+ [
+ ("filters_is_a_string", "not-a-dict"),
+ ("action_id_not_an_integer", {"actions": [{"id": "not-an-integer", "type": "actions"}]}),
+ ("action_entry_not_a_dict", {"actions": ["bogus"]}),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_conditional_branch_malformed_filters_get_a_400(self, _name, filters, _mock_flag):
+ hog_flow = self._hog_flow_with_condition_filters("conditional_branch", filters)
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_rejects_ineligible_cohorts_inside_referenced_actions(self, _mock_flag):
+ eligible = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ static_cohort = Cohort.objects.create(team=self.team, name="static-in-action", is_static=True)
+ action = Action.objects.create(
+ team=self.team,
+ name="action with cohort step",
+ steps_json=[
+ {"event": "$pageview", "properties": [{"key": "id", "type": "cohort", "value": static_cohort.id}]}
+ ],
+ )
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch",
+ {
+ "properties": [{"key": "id", "type": "cohort", "value": eligible.id}],
+ "actions": [{"id": action.id, "type": "actions"}],
+ },
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert "is a static cohort" in response.json()["detail"]
+
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_compiles_eligible_cohort_referenced_only_through_an_action(self, _mock_flag):
+ eligible = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ action = Action.objects.create(
+ team=self.team,
+ name="action with eligible cohort step",
+ steps_json=[{"event": "$pageview", "properties": [{"key": "id", "type": "cohort", "value": eligible.id}]}],
+ )
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch", {"actions": [{"id": action.id, "type": "actions"}]}
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 201, response.json()
+ bytecode = response.json()["actions"][1]["config"]["conditions"][0]["filters"]["bytecode"]
+ assert "inCohort" in bytecode
+
+ @parameterized.expand(
+ [
+ ("unvalidated_id", "person.properties.plan in cohort 999999", "can't be used here"),
+ ("non_constant_id", "person.properties.plan in cohort person.properties.x", "constant cohort id"),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True)
+ def test_hog_flow_rejects_in_cohort_operator_smuggled_through_hogql(
+ self, _name, hogql_key, expected_detail, _mock_flag
+ ):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch",
+ {
+ "properties": [
+ {"key": "id", "type": "cohort", "value": cohort.id},
+ {"key": hogql_key, "type": "hogql"},
+ ]
+ },
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert expected_detail in response.json()["detail"]
+
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false")
+ def test_hog_flow_cohort_flag_evaluates_the_target_teams_organization(self, mock_flag):
+ other_org = Organization.objects.create(name="Other Org")
+ OrganizationMembership.objects.create(user=self.user, organization=other_org)
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ cohort = Cohort.objects.create(
+ team=other_team,
+ name="other-org-cohort",
+ cohort_type=CohortType.REALTIME,
+ last_backfill_person_properties_at=BACKFILLED_AT,
+ last_backfill_events_at=BACKFILLED_AT,
+ filters=self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True).filters,
+ )
+ mock_flag.return_value = True
+ hog_flow = self._hog_flow_with_condition_filters(
+ "conditional_branch", {"properties": [{"key": "id", "type": "cohort", "value": cohort.id}]}
+ )
+
+ response = self.client.post(f"/api/projects/{other_team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 201, response.json()
+ assert mock_flag.call_args.kwargs["groups"] == {"organization": str(other_org.id)}
+
+ def test_hog_flow_wait_until_condition_rejects_cohort_filters(self):
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ hog_flow = self._hog_flow_with_condition_filters(
+ "wait_until_condition", {"properties": [{"key": "id", "type": "cohort", "value": cohort.id}]}
+ )
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)
+
+ assert response.status_code == 400, response.json()
+ assert "Cohort membership can't be evaluated in real-time filters" in response.json()["detail"]
+
def test_hog_flow_wait_until_condition_defaults_missing_condition(self):
# An events-only wait omits 'condition'; the FE always seeds it and StepWaitUntilCondition
# assumes it, so the serializer defaults it to {filters: None} to keep one canonical shape.
@@ -2659,6 +2992,51 @@ class TestHogFlowAPI(APIBaseTest):
assert payload["globals"] == {"event": {"event": "$pageview", "distinct_id": "test-distinct-id"}}
assert payload["mock_async_functions"] is True
+ @parameterized.expand(
+ [
+ ("cohort_condition_without_person_read", ["hog_flow:write", "group:read"], True, True, 403),
+ ("cohort_condition_with_person_read", ["hog_flow:write", "group:read", "person:read"], True, True, 200),
+ ("rolled_out_without_person_read", ["hog_flow:write", "group:read"], False, True, 403),
+ ("not_rolled_out_without_person_read", ["hog_flow:write", "group:read"], False, False, 200),
+ ("stored_cohort_condition_after_dial_down", ["hog_flow:write", "group:read"], True, False, 403),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false")
+ def test_test_invocation_requires_person_read_where_cohort_conditions_can_run(
+ self, _name, scopes, with_cohort_condition, flag_on_at_test_time, expected_status, mock_flag
+ ):
+ mock_flag.return_value = True
+ if with_cohort_condition:
+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)
+ filters = {"properties": [{"key": "id", "type": "cohort", "value": cohort.id}]}
+ else:
+ filters = {
+ "properties": [{"key": "email", "type": "person", "value": "[email protected]", "operator": "exact"}]
+ }
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ self._hog_flow_with_condition_filters("conditional_branch", filters),
+ )
+ assert created.status_code == 201, created.json()
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="test", user=self.user, secure_value=hash_key_value(key), scopes=scopes)
+ mock_flag.return_value = flag_on_at_test_time
+
+ with patch(
+ "products.workflows.backend.presentation.views.hog_flow.create_hog_flow_invocation_test"
+ ) as mock_invoke:
+ mock_invoke.return_value = MagicMock(status_code=200, json=lambda: {"status": "success"})
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{created.json()['id']}/invocations/",
+ {"globals": {"event": {"event": "$pageview", "distinct_id": "d"}}, "mock_async_functions": True},
+ format="json",
+ headers={"authorization": f"Bearer {key}"},
+ )
+
+ assert response.status_code == expected_status, response.json()
+ if expected_status == 403:
+ assert "person:read" in response.json()["detail"]
+
def test_hog_flow_conditional_event_filter_rejected(self):
conditional_action = {
"id": "cond_1",