: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): send batch audiences to realtime cohorts from postgres membership (#117662)
Harley Alexander1139c182ffe7
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 0e17c68a090c..42c77d0118c2 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -352,10 +352,11 @@ def create_batch_hog_flow_job_invocation(batch_job_id: UUIDT,max_audience_size: int | None = None,filters: dict | None = None,+ realtime_cohort: dict | None = None,) -> requests.Response:return internal_requests.post(CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/batch_invocations/{batch_job_id}",- json={"max_audience_size": max_audience_size, "filters": filters},+ json={"max_audience_size": max_audience_size, "filters": filters, "realtime_cohort": realtime_cohort},headers=get_internal_api_headers(),)diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex bc82e1f5947b..34986631d870 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -79,6 +79,15 @@ class WorkflowVisionScanDailyLimits:per_team: int | None+@frozen+class RealtimeAudienceCohort:+ """A realtime cohort a batch audience sends to from the realtime pipeline's membership."""++ id: int+ name: str+ ready: bool++@frozenclass WorkflowBatchJob:"""One batch run of a workflow.diff --git a/products/workflows/backend/facade/validation.py b/products/workflows/backend/facade/validation.pyindex 536056d1cb52..c668d94f5ac8 100644--- a/products/workflows/backend/facade/validation.py+++ b/products/workflows/backend/facade/validation.py@@ -1,5 +1,8 @@"""Save-time checks on a workflow's steps that need the database or shared parsing rules."""+from products.cohorts.backend.models.cohort import Cohort+from products.workflows.backend.facade.contracts import RealtimeAudienceCohort+from products.workflows.backend.services import batch_audience_cohortsfrom products.workflows.backend.services.batch_audience_cohorts import find_behavioral_cohort_namefrom products.workflows.backend.services.wait_clock_conditions import find_clock_functionfrom products.workflows.backend.utils.durations import (@@ -10,12 +13,33 @@ from products.workflows.backend.utils.durations import (is_signed_duration,)++def _to_realtime_audience_cohort(cohort: Cohort | None) -> RealtimeAudienceCohort | None:+ if cohort is None:+ return None+ return RealtimeAudienceCohort(+ id=cohort.pk, name=str(cohort.name), ready=batch_audience_cohorts.realtime_cohort_is_ready(cohort)+ )+++def find_realtime_behavioral_cohort(project_id: int, cohort_ids: list[int | str]) -> RealtimeAudienceCohort | None:+ """The first realtime cohort among `cohort_ids` that filters on event behavior."""+ return _to_realtime_audience_cohort(batch_audience_cohorts.find_realtime_behavioral_cohort(project_id, cohort_ids))+++def realtime_audience_cohort(project_id: int, filters: object) -> RealtimeAudienceCohort | None:+ """The realtime cohort an audience sends to from the realtime pipeline's membership, or None."""+ return _to_realtime_audience_cohort(batch_audience_cohorts.realtime_audience_cohort(project_id, filters))++__all__ = ["DURATION_PATTERN","duration_error","duration_minutes","find_behavioral_cohort_name","find_clock_function",+ "find_realtime_behavioral_cohort","is_duration","is_signed_duration",+ "realtime_audience_cohort",]diff --git a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.pyindex 1ae41e031cd9..0b6527005fb3 100644--- a/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py+++ b/products/workflows/backend/models/hog_flow_batch_job/hog_flow_batch_job.py@@ -8,6 +8,10 @@ from posthog.models.utils import RootTeamMixin, UUIDTModelfrom posthog.plugins.plugin_server_api import create_batch_hog_flow_job_invocationfrom products.workflows.backend.facade.enums import HogFlowBatchJobState+from products.workflows.backend.services.batch_audience_cohorts import (+ realtime_audience_cohort,+ realtime_cohort_is_ready,+)from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit, hog_flow_sends_emaillogger = structlog.get_logger(__name__)@@ -39,9 +43,30 @@ class HogFlowBatchJob(RootTeamMixin, UUIDTModel):return f"HogFlow batch run {self.id}"+def batch_job_audience_filters(job: HogFlowBatchJob) -> dict:+ """The audience the resolver reads: each key from the snapshot, or from the live trigger when the+ snapshot has none. The resolver resolves the keys the same way."""+ trigger_filters = (job.hog_flow.trigger or {}).get("filters") or {}+ snapshot = job.filters or {}+ return {+ key: snapshot[key] if snapshot.get(key) is not None else trigger_filters.get(key)+ for key in ("properties", "filter_test_accounts")+ }++@receiver(post_save, sender=HogFlowBatchJob)def handle_hog_flow_batch_job_created(sender, instance, created, **kwargs):if created:+ realtime_cohort = realtime_audience_cohort(instance.team.project_id, batch_job_audience_filters(instance))+ if realtime_cohort is not None and not realtime_cohort_is_ready(realtime_cohort):+ # An edit to the cohort since the save cleared its readiness. Its membership is partial until+ # it finishes calculating again, so the run fails instead of sending to the wrong people.+ logger.warning(+ "Batch run audience realtime cohort isn't ready", batch_job_id=instance.id, cohort_id=realtime_cohort.pk+ )+ HogFlowBatchJob.objects.filter(pk=instance.pk).update(status=HogFlowBatchJobState.FAILED)+ instance.status = HogFlowBatchJobState.FAILED+ returntry:create_batch_hog_flow_job_invocation(team_id=instance.team.id,@@ -58,6 +83,9 @@ def handle_hog_flow_batch_job_created(sender, instance, created, **kwargs):# The audience snapshot the confirm check validated - the resolver dispatches from# this, not the live trigger, so a trigger edit racing the dispatch can't widen it.filters=instance.filters,+ realtime_cohort=(+ {"id": realtime_cohort.pk, "team_id": realtime_cohort.team_id} if realtime_cohort else None+ ),)except Exception as e:logger.exception(diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 17a0ac30df64..a1d543ed590e 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -274,8 +274,10 @@ from products.workflows.backend.facade.validation import (duration_minutes,find_behavioral_cohort_name,find_clock_function,+ find_realtime_behavioral_cohort,is_duration,is_signed_duration,+ realtime_audience_cohort,)from products.workflows.backend.facade.workflows import (BILLABLE_ACTION_TYPES,@@ -1411,12 +1413,13 @@ class HogFlowActionSerializer(serializers.Serializer):except serializers.ValidationError as error:raise serializers.ValidationError({"cohort_id": error.detail})- def _reject_behavioral_cohorts_in_audience(self, properties) -> None:+ def _reject_behavioral_cohorts_in_audience(self, filters: dict, *, allow_realtime: bool) -> 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# that for API/MCP callers. Static cohorts are exempt regardless of how they were built — their# membership is frozen and precalculated — matching the audience-picker exemption in# _build_cohort_dependency_graph in products/cohorts/backend/models/dependencies.py.+ properties = filters.get("properties")if not isinstance(properties, list):returncohort_ids = [@@ -1426,7 +1429,39 @@ class HogFlowActionSerializer(serializers.Serializer):]if not cohort_ids:return- cohort_name = find_behavioral_cohort_name(self.context["get_team"]().project_id, cohort_ids)+ project_id = self.context["get_team"]().project_id++ # Behind the cohort-conditions flag, a realtime cohort can be a batch trigger's whole audience:+ # the batch resolver then pages its members from the realtime pipeline's Postgres table, which+ # holds no person properties. A schedule trigger starts one run with no person, so it never+ # reads the audience this way. An active flow keeps an audience it saved under the flag.+ realtime_cohort = find_realtime_behavioral_cohort(project_id, cohort_ids) if allow_realtime else None+ if realtime_cohort is not None and (+ realtime_cohort.id in (self.context.get("stored_realtime_audience_cohort_ids") or set())+ or self._cohort_conditions_enabled()+ ):+ if realtime_audience_cohort(project_id, filters) is None:+ raise serializers.ValidationError(+ {+ "filters": (+ f"Cohort '{realtime_cohort.name}' is a realtime cohort, so the audience can only be "+ "the people in it, with no other conditions and no test account filter. Add any "+ "other conditions to the cohort itself."+ )+ }+ )+ if not realtime_cohort.ready:+ raise serializers.ValidationError(+ {+ "filters": (+ f"Cohort '{realtime_cohort.name}' isn't ready yet. You can send to it once it "+ "finishes calculating."+ )+ }+ )+ return++ cohort_name = find_behavioral_cohort_name(project_id, cohort_ids)if cohort_name is not None:raise serializers.ValidationError({@@ -1662,7 +1697,7 @@ class HogFlowActionSerializer(serializers.Serializer):)parse_account_audience_filters(filters)else:- self._reject_behavioral_cohorts_in_audience(filters.get("properties"))+ self._reject_behavioral_cohorts_in_audience(filters, allow_realtime=True)elif data.get("config", {}).get("type") == "api":# A transactional email's trigger: the authenticated send endpoint runs the workflow once# per call, so the trigger has nothing to configure.@@ -1673,7 +1708,7 @@ class HogFlowActionSerializer(serializers.Serializer):if strict:filters = data.get("config", {}).get("filters", {})if isinstance(filters, dict):- self._reject_behavioral_cohorts_in_audience(filters.get("properties"))+ self._reject_behavioral_cohorts_in_audience(filters, allow_realtime=False)elif data.get("config", {}).get("type") in DATA_WAREHOUSE_TRIGGER_TYPES:# Warehouse-triggered workflows are person-less ("row-scoped"): one workflow run# per synced row, filtering only against the row payload. The table_name must match@@ -3141,6 +3176,17 @@ class HogFlowSerializer(HogFlowMinimalSerializer):and (action.get("config") or {}).get("type") == "cohort"}+ # Realtime cohorts an active flow's batch or schedule audience already sends to, so a flag+ # dial-down polices new adoption only, like stored_cohort_conditions below.+ self.context["stored_realtime_audience_cohort_ids"] = {+ cohort_id+ for action in ((instance.actions if instance and instance.status == HogFlow.State.ACTIVE else None) or [])+ if isinstance(action, dict)+ and action.get("type") == "trigger"+ and (action.get("config") or {}).get("type") == "batch"+ for cohort_id in filter_cohort_ids((action.get("config") or {}).get("filters"))+ }+self.context["stored_cohort_conditions"] = {action["id"]: [_authored_condition(stored_condition)diff --git a/products/workflows/backend/services/batch_audience_cohorts.py b/products/workflows/backend/services/batch_audience_cohorts.pyindex f0ec3fffb6ca..97479a35cf92 100644--- a/products/workflows/backend/services/batch_audience_cohorts.py+++ b/products/workflows/backend/services/batch_audience_cohorts.py@@ -1,5 +1,6 @@-from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.util import get_all_cohort_dependencies+from products.cohorts.backend.realtime_teams import is_realtime_cohort_teamdef find_behavioral_cohort_name(project_id: int, cohort_ids: list[int | str]) -> str | None:@@ -19,3 +20,60 @@ def find_behavioral_cohort_name(project_id: int, cohort_ids: list[int | str]) -># Cohort.name is nullable, and the caller reads None as "no behavioral cohort".return str(dep.name)return None+++def _filters_on_behavior(cohort: Cohort) -> bool:+ for dep in [cohort, *get_all_cohort_dependencies(cohort)]:+ if not dep.is_static and any(p.type == "behavioral" for p in dep.properties.flat):+ return True+ return False+++def find_realtime_behavioral_cohort(project_id: int, cohort_ids: list[int | str]) -> Cohort | None:+ """The first realtime cohort among `cohort_ids` that filters on event behavior."""+ for cohort_id in cohort_ids:+ try:+ cohort = Cohort.objects.get(+ pk=cohort_id, team__project_id=project_id, deleted=False, cohort_type=CohortType.REALTIME+ )+ except (Cohort.DoesNotExist, ValueError, TypeError):+ continue+ if _filters_on_behavior(cohort):+ return cohort+ return None+++def realtime_audience_cohort(project_id: int, filters: object) -> Cohort | None:+ """The realtime cohort an audience sends to from the realtime pipeline's membership, or None.++ Only an audience of exactly one condition, "in" a realtime cohort that filters on event+ behavior, takes this path. The membership lives in a Postgres database that holds no person+ properties, so any other condition, a negated one, or the test account filter keeps the+ ClickHouse audience query.+ """+ if not isinstance(filters, dict) or filters.get("filter_test_accounts"):+ return None+ properties = filters.get("properties")+ if not isinstance(properties, list) or len(properties) != 1:+ return None+ condition = properties[0]+ if (+ not isinstance(condition, dict)+ or condition.get("type") != "cohort"+ or condition.get("operator") not in (None, "in")+ or condition.get("negation")+ ):+ return None+ cohort_id = condition.get("value")+ if not isinstance(cohort_id, int | str):+ return None+ return find_realtime_behavioral_cohort(project_id, [cohort_id])+++def realtime_cohort_is_ready(cohort: Cohort) -> bool:+ """Whether the realtime pipeline holds this cohort's full membership and keeps it current.++ The backfill stamps stay set when a team leaves the realtime allowlist, but the pipeline then+ stops updating the membership, so the team has to be on the allowlist too.+ """+ return cohort.is_flag_compatible and is_realtime_cohort_team(cohort.team_id)diff --git a/products/workflows/backend/services/blast_radius.py b/products/workflows/backend/services/blast_radius.pyindex 3565d7fb2985..7b35f96895be 100644--- a/products/workflows/backend/services/blast_radius.py+++ b/products/workflows/backend/services/blast_radius.py@@ -15,6 +15,7 @@ from products.workflows.backend.services.account_audience import ()from products.workflows.backend.services.audience_v2 import get_dedupe_audience_count_v2, get_person_audience_count_v2from products.workflows.backend.services.batch_audience import audience_page_size, get_batch_audience_person_ids+from products.workflows.backend.services.batch_audience_cohorts import realtime_audience_cohortfrom products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit@@ -32,6 +33,18 @@ def get_audience_size(# The applied key is echoed back so the frontend labels the count from the response# instead of guessing whether the dedup actually ran.applied_dedupe_key = None+ realtime_cohort = realtime_audience_cohort(team.project_id, filters) if group_type_index is None else None+ if realtime_cohort is not None:+ # The send reads the realtime pipeline's Postgres table, which this process can't query. The+ # cohort's count from its periodic calculation stands in as an estimate, and the send skips the+ # email dedupe.+ everyone = get_person_audience_count_v2(team, {"properties": []})+ return AudienceSize(+ affected=realtime_cohort.count or 0,+ total=everyone.total,+ limit=get_hogflow_batch_trigger_limit(team_id, sends_email=sends_email),+ dedupe_key=None,+ )if group_type_index is not None:blast_radius = get_user_blast_radius(team, filters, group_type_index)elif dedupe_key is not None:diff --git a/products/workflows/backend/test/test_batch_audience.py b/products/workflows/backend/test/test_batch_audience.pyindex 81f388d35b2d..f62e12494b6a 100644--- a/products/workflows/backend/test/test_batch_audience.py+++ b/products/workflows/backend/test/test_batch_audience.py@@ -4,8 +4,10 @@ from django.test import override_settingsfrom parameterized import parameterized+from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.feature_flags.backend.user_blast_radius import PERSON_BATCH_SIZE, get_user_blast_radius_personsfrom products.workflows.backend.services.batch_audience import audience_page_size, get_batch_audience_person_ids+from products.workflows.backend.services.blast_radius import get_audience_sizeFILTERS = {"properties": [{"key": "subscribed", "type": "person", "value": ["true"], "operator": "exact"}]}@@ -79,3 +81,39 @@ class TestBatchAudience(ClickhouseTestMixin, BaseTest):# page length against the person setting would stop after the first page.assert audience_page_size(None) == 7assert audience_page_size(0) == PERSON_BATCH_SIZE++ def test_realtime_cohort_audience_size_estimates_from_the_cohort_count(self):+ # The send reads realtime membership from a Postgres database Django can't reach, so the+ # preview estimates from the cohort's periodic count and reports no email dedupe.+ cohort = Cohort.objects.create(+ team=self.team,+ name="c",+ cohort_type=CohortType.REALTIME,+ count=2,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "key": "$pageview",+ "event_type": "events",+ "time_value": 30,+ "time_interval": "day",+ "value": "performed_event",+ "type": "behavioral",+ }+ ],+ }+ },+ )++ size = get_audience_size(+ team_id=self.team.pk,+ filters={"properties": [{"key": "id", "type": "cohort", "value": cohort.pk, "operator": "in"}]},+ group_type_index=None,+ dedupe_key="email",+ sends_email=True,+ )++ assert (size.affected, size.total, size.dedupe_key) == (2, 3, None)diff --git a/products/workflows/backend/test/test_hog_flow_batch_job.py b/products/workflows/backend/test/test_hog_flow_batch_job.pyindex 1487aa00a977..4b5e2a7ef451 100644--- a/products/workflows/backend/test/test_hog_flow_batch_job.py+++ b/products/workflows/backend/test/test_hog_flow_batch_job.py@@ -1,10 +1,15 @@+from datetime import UTC, datetime+from unittest.mock import patchfrom django.db.models.signals import post_save-from django.test import TestCase+from django.test import TestCase, override_settings++from parameterized import parameterizedfrom posthog.models.user import User+from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job import handle_hog_flow_batch_job_created@@ -56,6 +61,107 @@ class TestHogFlowBatchJob(TestCase):assert str(batch_job) == f"HogFlow batch run {batch_job.id}"mock_create_invocation.assert_called_once()+ @parameterized.expand(+ [+ ("single_realtime_cohort", "realtime", None, True),+ ("realtime_cohort_with_another_condition", "realtime", "with_property", False),+ # Postgres membership can't exclude test accounts, so that audience keeps the Django query.+ ("realtime_cohort_with_test_account_filter", "realtime", "test_accounts", False),+ ("non_realtime_cohort", "not_realtime", None, False),+ ]+ )+ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")+ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_hog_flow_batch_job_dispatch_names_a_realtime_cohort_audience(+ self, _name, cohort_kind, shape, expect_realtime, mock_create_invocation+ ):+ behavioral = {+ "properties": {+ "type": "AND",+ "values": [+ {+ "key": "$pageview",+ "event_type": "events",+ "time_value": 30,+ "time_interval": "day",+ "value": "performed_event",+ "type": "behavioral",+ }+ ],+ }+ }+ cohort = Cohort.objects.create(+ team=self.team,+ name="c",+ filters=behavioral,+ cohort_type=CohortType.REALTIME if cohort_kind == "realtime" else None,+ last_backfill_events_at=datetime(2026, 1, 1, tzinfo=UTC),+ last_backfill_person_properties_at=datetime(2026, 1, 1, tzinfo=UTC),+ )+ properties: list[dict] = [{"key": "id", "type": "cohort", "value": cohort.pk, "operator": "in"}]+ if shape == "with_property":+ properties.append({"key": "plan", "type": "person", "value": "pro", "operator": "exact"})++ filters: dict = {"properties": properties}+ if shape == "test_accounts":+ filters["filter_test_accounts"] = True++ HogFlowBatchJob.objects.create(team=self.team, hog_flow=self.hog_flow, filters=filters)++ expected = {"id": cohort.pk, "team_id": self.team.pk} if expect_realtime else None+ assert mock_create_invocation.call_args.kwargs["realtime_cohort"] == expected++ @parameterized.expand(+ [+ # An edit after the save clears the cohort's readiness; its membership is partial until it recalculates.+ ("stamps_cleared", False, "all"),+ # The stamps stay set, but the pipeline stops updating the membership.+ ("team_left_the_realtime_allowlist", True, "none"),+ ]+ )+ @patch(+ "products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation"+ )+ def test_hog_flow_batch_job_fails_when_its_realtime_cohort_is_no_longer_ready(+ self, _name, backfilled, allowlist, mock_create_invocation+ ):+ backfill_stamp = datetime(2026, 1, 1, tzinfo=UTC) if backfilled else None+ cohort = Cohort.objects.create(+ team=self.team,+ name="c",+ cohort_type=CohortType.REALTIME,+ last_backfill_events_at=backfill_stamp,+ last_backfill_person_properties_at=backfill_stamp,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "key": "$pageview",+ "event_type": "events",+ "time_value": 30,+ "time_interval": "day",+ "value": "performed_event",+ "type": "behavioral",+ }+ ],+ }+ },+ )++ with override_settings(REALTIME_COHORT_TEAM_ALLOWLIST=allowlist):+ job = HogFlowBatchJob.objects.create(+ team=self.team,+ hog_flow=self.hog_flow,+ filters={"properties": [{"key": "id", "type": "cohort", "value": cohort.pk, "operator": "in"}]},+ )++ mock_create_invocation.assert_not_called()+ job.refresh_from_db()+ assert job.status == HogFlowBatchJob.State.FAILED+@patch("products.workflows.backend.models.hog_flow_batch_job.hog_flow_batch_job.create_batch_hog_flow_job_invocation")diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.pyindex d30696a57264..178fce7bbbe0 100644--- a/products/workflows/backend/tests/api/test_hog_flow.py+++ b/products/workflows/backend/tests/api/test_hog_flow.py@@ -4126,6 +4126,92 @@ class TestHogFlowAPI(APIBaseTest):assert response.status_code == 400, response.json()assert "behavior" in response.json()["detail"].lower()+ @parameterized.expand(+ [+ ("ready_alone", "batch", "ready", None, True, 201, None),+ # A schedule trigger starts one run with no person, so it never fans out to the members.+ ("schedule_trigger", "schedule", "ready", None, True, 400, "can't evaluate"),+ ("not_ready", "batch", "not_ready", None, True, 400, "isn't ready yet"),+ # The backfill stamps outlive the team's place on the realtime allowlist; the membership doesn't.+ ("team_off_realtime_allowlist", "batch", "ready_off_allowlist", None, True, 400, "isn't ready yet"),+ # The send pages the cohort's members from Postgres, which holds no person properties.+ ("with_another_condition", "batch", "ready", "with_property", True, 400, "only be the people in it"),+ ("not_in", "batch", "ready", "not_in", True, 400, "only be the people in it"),+ ("negated", "batch", "ready", "negated", True, 400, "only be the people in it"),+ ("test_account_filter", "batch", "ready", "test_accounts", True, 400, "only be the people in it"),+ ("flag_off", "batch", "ready", None, False, 400, "can't evaluate"),+ ("behavioral_not_realtime", "batch", "not_realtime", None, True, 400, "can't evaluate"),+ ]+ )+ @patch("products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false")+ def test_hog_flow_audience_realtime_cohort(+ self, _name, trigger_type, cohort_kind, shape, flag_on, expected_status, expected_detail, mock_flag+ ):+ mock_flag.return_value = flag_on+ if cohort_kind == "not_realtime":+ cohort = self._make_cohort(behavioral=True)+ else:+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=cohort_kind != "not_ready")+ condition: dict[str, Any] = {"key": "id", "type": "cohort", "value": cohort.pk, "operator": "in"}+ if shape == "not_in":+ condition["operator"] = "not_in"+ if shape == "negated":+ condition["negation"] = True+ properties = [condition]+ if shape == "with_property":+ properties.append({"key": "plan", "type": "person", "value": "pro", "operator": "exact"})+ filters: dict[str, Any] = {"properties": properties}+ if shape == "test_accounts":+ filters["filter_test_accounts"] = True+ hog_flow = {+ "name": "Test Batch Flow",+ "status": "active",+ "actions": [+ {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {"type": trigger_type, "filters": filters},+ }+ ],+ }++ allowlist = "none" if cohort_kind == "ready_off_allowlist" else "all"+ with override_settings(REALTIME_COHORT_TEAM_ALLOWLIST=allowlist):+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)++ assert response.status_code == expected_status, response.json()+ if expected_detail:+ assert expected_detail in response.json()["detail"]++ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")+ def test_hog_flow_audience_keeps_a_stored_realtime_cohort_after_flag_dial_down(self):+ cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)+ other_cohort = self._create_behavioral_cohort(CohortType.REALTIME, backfilled=True)+ with patch(+ "products.workflows.backend.presentation.views.hog_flow.feature_enabled_or_false", return_value=True+ ):+ created = self._post_batch_with_cohort(cohort.pk)+ 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[0]["config"]["filters"]["properties"][0]["value"] = other_cohort.pk+ 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 "can't evaluate" in new_adoption.json()["detail"]+def test_hog_flow_batch_trigger_rejects_nested_behavioral_cohort(self):behavioral = self._make_cohort(behavioral=True)wrapper = self._make_cohort(nested_cohort_id=behavioral.pk)diff --git a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsxindex 2f196504072f..51dd03bcd149 100644--- a/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx+++ b/products/workflows/frontend/Broadcasts/steps/BroadcastRecipientsStep.tsx@@ -6,6 +6,7 @@ import { LemonBanner, LemonButton, LemonModal, LemonSelect, Link, Spinner } fromimport { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { humanFriendlyNumber } from 'lib/utils/numbers'import { COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS } from 'scenes/feature-flags/cohortPickerProps'import { Scene } from 'scenes/sceneTypes'@@ -143,6 +144,7 @@ function AudienceListModal({ isOpen, onClose }: { isOpen: boolean; onClose: () =}export function BroadcastRecipientsStep(): JSX.Element {+ const cohortConditionsEnabled = useFeatureFlag('WORKFLOWS_COHORT_CONDITIONS')const { audienceProperties, linkAudienceRejected } = useValues(broadcastWizardLogic)const { setAudienceProperties, sendToEveryoneAfterRejectedLink } = useActions(broadcastWizardLogic)const { props } = useMountedLogic(broadcastWizardLogic)@@ -193,7 +195,7 @@ export function BroadcastRecipientsStep(): JSX.Element {sendAllKeyUpdatesallowRelativeDateOptions{...COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS}- hideBehavioralCohorts+ hideBehavioralCohorts={!cohortConditionsEnabled}logicalRowDivideronChange={(properties) => setAudienceProperties(properties)}taxonomicGroupTypes={[diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex b86077c75b1f..372ea1753493 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -761,7 +761,7 @@ function StepTriggerConfigurationBatch({sendAllKeyUpdatesallowRelativeDateOptions{...COHORTS_ONLY_SUPPORT_IN_PICKER_PROPS}- hideBehavioralCohorts+ hideBehavioralCohorts={!featureFlags[FEATURE_FLAGS.WORKFLOWS_COHORT_CONDITIONS]}logicalRowDivideronChange={(properties) =>partialSetWorkflowActionConfig(action.id, {