: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): dedupe batch email sends by address (#69305)
Meikel Ratze9fbf809a2c1
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e9f90bb0e960..e0d42a531816 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6627,9 +6627,13 @@ const api = {return await new ApiRequest().hogFlow(hogFlowId).withAction('invocations').create({ data })},async getBatchTriggerBlastRadius(- filters: Extract<HogFlowAction['config'], { type: 'batch' }>['filters']+ filters: Extract<HogFlowAction['config'], { type: 'batch' }>['filters'],+ dedupeKey?: 'email'): Promise<BlastRadiusApi> {- return await new ApiRequest().hogFlows().withAction('user_blast_radius').create({ data: { filters } })+ return await new ApiRequest()+ .hogFlows()+ .withAction('user_blast_radius')+ .create({ data: { filters, dedupe_key: dedupeKey ?? null } })},async createHogFlowBatchJob(hogFlowId: HogFlow['id'],diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 4af94ace0d46..c57f7ea30f00 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -955,6 +955,125 @@ describe('CDP API', () => {totalEnqueued: 0,pagesProcessed: 0,})+ // No email action in the flow, so the audience must not be deduped by email+ expect(state.dedupeKey).toBeUndefined()+ } finally {+ api['batchResolverProducer'] = null+ }+ })++ it('sets email dedupe on the resolver state when the flow sends email to the default {{person.properties.email}}', async () => {+ const emailHogFlow = await insertHogFlow({+ id: new UUIDT().toString(),+ name: 'test batch email hog flow',+ status: 'active',+ version: 1,+ exit_condition: 'exit_on_conversion',+ edges: [],+ actions: [+ {+ id: 'email_1',+ type: 'function_email',+ name: 'Send email',+ config: {+ template_id: 'template-email',+ inputs: {+ email: {+ value: {+ to: { email: '{{ person.properties.email }}', name: '' },+ from: {},+ subject: 'Hi',+ text: 'Hello',+ html: '<p>Hello</p>',+ },+ },+ },+ },+ },+ ] as any,+ trigger: {+ type: 'batch',+ filters: { properties: [] },+ },+ })++ const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')+ api['batchResolverProducer'] = {+ createJob: createJobMock,+ disconnect: jest.fn().mockResolvedValue(undefined),+ }++ try {+ const res = await supertest(app)+ .post(+ `/api/projects/${emailHogFlow.team_id}/hog_flows/${emailHogFlow.id}/batch_invocations/job-790`+ )+ .send({})++ expect(res.status).toEqual(200)+ const arg = createJobMock.mock.calls[0][0]+ const state = parseJSON((arg.state as Buffer).toString('utf-8')) as Record<string, unknown>+ expect(state.dedupeKey).toEqual('email')+ } finally {+ api['batchResolverProducer'] = null+ }+ })++ it('skips email dedupe when the flow sends to a customized recipient (e.g. work_email)', async () => {+ // Regression guard for the wrong-property footgun: if the customer wired their+ // email action to send to `person.properties.work_email`, deduping on+ // `person.properties.email` would collapse the wrong groups. Better to skip dedupe.+ const emailHogFlow = await insertHogFlow({+ id: new UUIDT().toString(),+ name: 'test batch email hog flow (custom recipient)',+ status: 'active',+ version: 1,+ exit_condition: 'exit_on_conversion',+ edges: [],+ actions: [+ {+ id: 'email_1',+ type: 'function_email',+ name: 'Send email',+ config: {+ template_id: 'template-email',+ inputs: {+ email: {+ value: {+ to: { email: '{{ person.properties.work_email }}', name: '' },+ from: {},+ subject: 'Hi',+ text: 'Hello',+ html: '<p>Hello</p>',+ },+ },+ },+ },+ },+ ] as any,+ trigger: {+ type: 'batch',+ filters: { properties: [] },+ },+ })++ const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')+ api['batchResolverProducer'] = {+ createJob: createJobMock,+ disconnect: jest.fn().mockResolvedValue(undefined),+ }++ try {+ const res = await supertest(app)+ .post(+ `/api/projects/${emailHogFlow.team_id}/hog_flows/${emailHogFlow.id}/batch_invocations/job-791`+ )+ .send({})++ expect(res.status).toEqual(200)+ const arg = createJobMock.mock.calls[0][0]+ const state = parseJSON((arg.state as Buffer).toString('utf-8')) as Record<string, unknown>+ expect(state.dedupeKey).toBeUndefined()} finally {api['batchResolverProducer'] = null}diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex a119bb07ab54..16367130f178 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -81,6 +81,25 @@ function sanitizeContentType(contentType: string | undefined, fallback: string):return fallback}+// Matches the default email template's `to.email` value: `{{ person.properties.email }}`, whitespace-tolerant.+// Anything else (custom property, computed Liquid, static address) makes the dedupe key diverge from the+// actual send target — see `canDedupeByEmail`.+const DEFAULT_EMAIL_TO_TEMPLATE_RE = /^\s*\{\{\s*person\.properties\.email\s*\}\}\s*$/++function canDedupeByEmail(hogFlow: { actions?: unknown }): boolean {+ if (!Array.isArray(hogFlow.actions)) {+ return false+ }+ const emailActions = hogFlow.actions.filter((action: any) => action?.type === 'function_email')+ if (emailActions.length === 0) {+ return false+ }+ return emailActions.every((action: any) => {+ const toEmail = action?.config?.inputs?.email?.value?.to?.email+ return typeof toEmail === 'string' && DEFAULT_EMAIL_TO_TEMPLATE_RE.test(toEmail)+ })+}+export type CdpApiConfig = PluginsServerConfigexport type CdpApiDeps = CdpConsumerBaseDeps@@ -819,6 +838,11 @@ export class CdpApi {},variables: req.body.variables ?? {},groupTypeIndex: typeof req.body.group_type_index === 'number' ? req.body.group_type_index : undefined,+ // Only dedupe by email when every email action's `to` template is exactly the default+ // `{{ person.properties.email }}`. Custom recipients (work_email, computed Liquid, static+ // strings) would make the dedupe key diverge from the actual send target — better to skip+ // dedupe than dedupe wrongly. Also skip when the flow has no email action at all.+ dedupeKey: canDedupeByEmail(hogFlow) ? ('email' as const) : undefined,maxAudienceSize: maxAudienceSize ?? this.config.CDP_BATCH_WORKFLOW_MAX_AUDIENCE_SIZE,cursor: null,totalEnqueued: 0,diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.tsindex c15c30091706..592321cc56a7 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts@@ -194,7 +194,8 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServeteam,state.filters,state.groupTypeIndex,- state.cursor+ state.cursor,+ state.dedupeKey))} catch (err) {diff --git a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts b/nodejs/src/cdp/services/hogflows/batch-resolver.types.tsindex 31f8d7bec40a..00c77b32ae7b 100644--- a/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts+++ b/nodejs/src/cdp/services/hogflows/batch-resolver.types.ts@@ -26,6 +26,12 @@ export const BatchResolverStateSchema = z.object({}),variables: z.record(z.string(), z.unknown()),groupTypeIndex: z.number().int().optional(),+ // When set, the Django audience query collapses persons sharing the same+ // normalized email so an address receives the batch send only once. Decided+ // once at enqueue time (flows containing an email action) and frozen here so+ // mid-run flow edits can't flip dedup semantics between pages. Optional so+ // jobs written by older deploys keep parsing (they run un-deduped).+ dedupeKey: z.enum(['email']).optional(),maxAudienceSize: z.number().int().nonnegative(),cursor: z.string().nullable(),totalEnqueued: z.number().int().nonnegative(),diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.tsindex fb34141acf41..c731b483e5be 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts@@ -142,6 +142,7 @@ describe('HogFlowBatchPersonQueryService', () => {filters,group_type_index: 2,cursor: null,+ dedupe_key: null,}),},})@@ -153,12 +154,16 @@ describe('HogFlowBatchPersonQueryService', () => {filters,group_type_index: 2,cursor: 'next-cursor',+ dedupe_key: null,}),},})})- it('sends cursor as null when not provided', async () => {+ it.each([+ ['email dedupe key is forwarded', 'email' as const, 'email'],+ ['missing dedupe key is sent as null', undefined, null],+ ])('%s', async (_name, dedupeKey, expectedBodyValue) => {const service = createService()fetchMock.mockResolvedValue({@@ -170,7 +175,7 @@ describe('HogFlowBatchPersonQueryService', () => {fetchError: null,})- await service.getBlastRadiusPersons(team, filters)+ await service.getBlastRadiusPersons(team, filters, undefined, null, dedupeKey)expect(fetchMock).toHaveBeenCalledWith({urlPath: '/api/projects/123/internal/hog_flows/user_blast_radius_persons',@@ -180,6 +185,7 @@ describe('HogFlowBatchPersonQueryService', () => {filters,group_type_index: undefined,cursor: null,+ dedupe_key: expectedBodyValue,}),},})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.tsindex 9a65537157a8..6ffbf9c93c75 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts@@ -84,7 +84,8 @@ export class HogFlowBatchPersonQueryService {team: Team,filters: Pick<HogFunctionFilters, 'properties' | 'filter_test_accounts'>,groupTypeIndex?: number,- cursor?: string | null+ cursor?: string | null,+ dedupeKey?: 'email'): Promise<BlastRadiusPersonsResponse> {const urlPath = `/api/projects/${team.id}/internal/hog_flows/user_blast_radius_persons` as const@@ -97,6 +98,7 @@ export class HogFlowBatchPersonQueryService {filters,group_type_index: groupTypeIndex,cursor: cursor || null,+ dedupe_key: dedupeKey ?? null,}),},})diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 0b6f58fbbea4..3ea51cade932 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -86,6 +86,13 @@ from products.workflows.backend.models.hog_flow.hog_flow import ()from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule+from products.workflows.backend.services.batch_audience import (+ PERSON_BATCH_SIZE as WORKFLOWS_PERSON_BATCH_SIZE,+ SUPPORTED_DEDUPE_KEYS,+ get_batch_audience_count,+ get_batch_audience_person_ids,+ use_workflows_batch_audience_query,+)from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limitfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule@@ -181,12 +188,23 @@ class BlastRadiusRequestSerializer(serializers.Serializer):group_type_index = serializers.IntegerField(required=False, allow_null=True, help_text="Group type index for group-based targeting")+ dedupe_key = serializers.ChoiceField(+ choices=list(SUPPORTED_DEDUPE_KEYS),+ required=False,+ allow_null=True,+ help_text="When 'email', count unique email addresses instead of persons, matching how batch email sends deduplicate recipients.",+ )class BlastRadiusSerializer(serializers.Serializer):affected = serializers.IntegerField(help_text="Number of users matching the filters")total = serializers.IntegerField(help_text="Total number of users")limit = serializers.IntegerField(help_text="Maximum allowed audience size for batch triggers for this team.")+ dedupe_key = serializers.ChoiceField(+ choices=list(SUPPORTED_DEDUPE_KEYS),+ allow_null=True,+ help_text="The dedupe key that was actually applied to 'affected'. 'email' means it counts unique email addresses; null means it counts persons.",+ )class WorkflowGlobalStatsRequestSerializer(serializers.Serializer):@@ -1550,22 +1568,38 @@ class HogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMixin, vie@extend_schema(request=BlastRadiusRequestSerializer, responses=BlastRadiusSerializer)@action(methods=["POST"], detail=False)def user_blast_radius(self, request: Request, **kwargs):- if "filters" not in request.data:- raise exceptions.ValidationError("Missing filters for which to get blast radius")+ param_serializer = BlastRadiusRequestSerializer(data=request.data)+ param_serializer.is_valid(raise_exception=True)+ params = param_serializer.validated_data- filters = request.data.get("filters", {})- group_type_index = request.data.get("group_type_index", None)+ filters = params["filters"]+ group_type_index = params.get("group_type_index")+ dedupe_key = params.get("dedupe_key")reject_flag_conditions_in_audience(self.team, filters)- result = get_user_blast_radius(self.team, filters, group_type_index)+ # Preview matches the actual send: with dedup active, "affected" is the number of+ # sends (unique emails + email-less persons), not the number of matching persons —+ # the legacy person-count query is skipped entirely, "total" comes straight from+ # the cached team-wide count it would have returned anyway. The applied key is+ # echoed back so the frontend labels the count from the response instead of+ # guessing whether the flag-gated dedup actually ran.+ applied_dedupe_key = None+ if dedupe_key is not None and group_type_index is None and use_workflows_batch_audience_query(self.team):+ total = self.team.persons_seen_so_far+ affected = min(get_batch_audience_count(self.team, filters, dedupe_key), total)+ applied_dedupe_key = dedupe_key+ else:+ result = get_user_blast_radius(self.team, filters, group_type_index)+ affected, total = result.affected, result.totalreturn Response(BlastRadiusSerializer({- "affected": result.affected,- "total": result.total,+ "affected": affected,+ "total": total,"limit": get_hogflow_batch_trigger_limit(self.team_id),+ "dedupe_key": applied_dedupe_key,}).data)@@ -1884,6 +1918,7 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi"affected": result.affected,"total": result.total,"limit": get_hogflow_batch_trigger_limit(team.id),+ "dedupe_key": None,}).data)@@ -1912,15 +1947,26 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMifilters = request.data.get("filters", {}) or {}group_type_index = request.data.get("group_type_index", None)cursor = request.data.get("cursor", None)+ dedupe_key = request.data.get("dedupe_key", None)++ if dedupe_key is not None and dedupe_key not in SUPPORTED_DEDUPE_KEYS:+ return Response({"error": f"Unsupported dedupe_key: {dedupe_key}"}, status=400)try:reject_flag_conditions_in_audience(team, filters)- users_affected = get_user_blast_radius_persons(team, filters, group_type_index, cursor)+ if use_workflows_batch_audience_query(team):+ users_affected = get_batch_audience_person_ids(+ team, filters, group_type_index, cursor, dedupe_key=dedupe_key+ )+ batch_size = WORKFLOWS_PERSON_BATCH_SIZE+ else:+ users_affected = get_user_blast_radius_persons(team, filters, group_type_index, cursor)+ batch_size = PERSON_BATCH_SIZEreturn Response({"users_affected": users_affected,"cursor": users_affected[-1] if users_affected else None,- "has_more": len(users_affected) == PERSON_BATCH_SIZE,+ "has_more": len(users_affected) == batch_size,})except exceptions.ValidationError as e:diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex e5dbcca94004..45aa748c549c 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -2,7 +2,7 @@ from datetime import UTC, datetime, timedeltafrom typing import Optionalfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, PropertyMock, patchfrom django.test import override_settings@@ -2009,7 +2009,7 @@ class TestHogFlowAPI(APIBaseTest):response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/user_blast_radius", {})assert response.status_code == 400, response.json()- assert "Missing filters" in response.json().get("detail", "")+ assert response.json().get("attr") == "filters"mock_get_user_blast_radius.assert_not_called()def test_hog_flow_user_blast_radius_returns_counts(self):@@ -2161,6 +2161,107 @@ class TestHogFlowAPI(APIBaseTest):assert "Feature flags can't be used as a batch audience condition" in response.json().get("error", "")mock_get_user_blast_radius_persons.assert_not_called()+ @parameterized.expand(+ [+ ("flag_on_uses_workflows_query", True),+ ("flag_off_uses_legacy_query", False),+ ]+ )+ @override_settings(INTERNAL_API_SECRET="test-secret-123")+ def test_internal_user_blast_radius_persons_query_selection(self, _name, flag_enabled):+ with (+ patch(+ "products.workflows.backend.api.hog_flow.use_workflows_batch_audience_query",+ return_value=flag_enabled,+ ),+ patch(+ "products.workflows.backend.api.hog_flow.get_batch_audience_person_ids", return_value=["id-1"]+ ) as mock_workflows_query,+ patch(+ "products.workflows.backend.api.hog_flow.get_user_blast_radius_persons", return_value=["id-1"]+ ) as mock_legacy_query,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/internal/hog_flows/user_blast_radius_persons",+ {"filters": {"properties": []}, "dedupe_key": "email"},+ format="json",+ headers={"x-internal-api-secret": "test-secret-123"},+ )++ assert response.status_code == 200, response.json()+ assert response.json()["users_affected"] == ["id-1"]+ if flag_enabled:+ mock_workflows_query.assert_called_once_with(self.team, {"properties": []}, None, None, dedupe_key="email")+ mock_legacy_query.assert_not_called()+ else:+ mock_legacy_query.assert_called_once_with(self.team, {"properties": []}, None, None)+ mock_workflows_query.assert_not_called()++ @parameterized.expand(+ [+ ("flag_on_uses_deduped_count", True, 3),+ ("flag_off_keeps_person_count", False, 5),+ ]+ )+ def test_user_blast_radius_dedupe_key_affects_count(self, _name, flag_enabled, expected_affected):+ from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415++ with (+ patch(+ "products.workflows.backend.api.hog_flow.use_workflows_batch_audience_query",+ return_value=flag_enabled,+ ),+ patch(+ "products.workflows.backend.api.hog_flow.get_user_blast_radius",+ return_value=BlastRadiusResult(affected=5, total=10),+ ) as mock_legacy_count,+ patch(+ "products.workflows.backend.api.hog_flow.get_batch_audience_count", return_value=3+ ) as mock_deduped_count,+ patch(+ "posthog.models.team.team.Team.persons_seen_so_far",+ new_callable=PropertyMock,+ return_value=10,+ ),+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": {"properties": []}, "dedupe_key": "email"},+ )++ assert response.status_code == 200, response.json()+ assert response.json()["affected"] == expected_affected+ assert response.json()["total"] == 10+ # The applied key is echoed so the frontend can label the count correctly+ assert response.json()["dedupe_key"] == ("email" if flag_enabled else None)+ if flag_enabled:+ # The legacy person-count query is skipped — only the deduped count runs+ mock_deduped_count.assert_called_once_with(self.team, {"properties": []}, "email")+ mock_legacy_count.assert_not_called()+ else:+ mock_deduped_count.assert_not_called()+ mock_legacy_count.assert_called_once()++ def test_user_blast_radius_rejects_unsupported_dedupe_key(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": {"properties": []}, "dedupe_key": "phone"},+ )++ assert response.status_code == 400, response.json()++ @override_settings(INTERNAL_API_SECRET="test-secret-123")+ def test_internal_user_blast_radius_persons_rejects_unsupported_dedupe_key(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/internal/hog_flows/user_blast_radius_persons",+ {"filters": {"properties": []}, "dedupe_key": "phone"},+ format="json",+ headers={"x-internal-api-secret": "test-secret-123"},+ )++ assert response.status_code == 400, response.json()+ assert "Unsupported dedupe_key" in response.json().get("error", "")+@override_settings(INTERNAL_API_SECRET="test-secret-123")@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/services/batch_audience.py b/products/workflows/backend/services/batch_audience.pynew file mode 100644index 000000000000..59cfd4874e51--- /dev/null+++ b/products/workflows/backend/services/batch_audience.py@@ -0,0 +1,205 @@+from typing import Optional++import structlog+import posthoganalytics++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr+from posthog.hogql.property import property_to_expr+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models.filters import Filter+from posthog.models.property import GroupTypeIndex+from posthog.models.team.team import Team++from products.feature_flags.backend.user_blast_radius import get_user_blast_radius_persons, replace_proxy_properties++logger = structlog.get_logger(__name__)++PERSON_BATCH_SIZE = 500++EMAIL_DEDUPE_KEY = "email"+SUPPORTED_DEDUPE_KEYS = (EMAIL_DEDUPE_KEY,)++WORKFLOWS_BATCH_AUDIENCE_QUERY_FLAG = "workflows-batch-audience-query"+++def use_workflows_batch_audience_query(team: Team) -> bool:+ """Gates the workflows-owned audience query; off means the legacy flags-owned query.++ A raised exception (Redis/HyperCache blip, network glitch, SDK bug) is treated as+ "flag off" — the legacy path is the safe fallback per the PR's kill-switch design.+ Batch sends are a critical path, so a transient flag-eval failure must not 500 the+ preview endpoint or cause the resolver to exhaust its retry budget and fail the job.+ """+ try:+ return bool(+ posthoganalytics.feature_enabled(+ WORKFLOWS_BATCH_AUDIENCE_QUERY_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ )+ )+ except Exception:+ logger.warning(+ "workflows.batch_audience.feature_flag_check_failed_defaulting_off",+ team_id=team.id,+ flag=WORKFLOWS_BATCH_AUDIENCE_QUERY_FLAG,+ exc_info=True,+ )+ return False+++def get_batch_audience_person_ids(+ team: Team,+ filters: dict,+ group_type_index: Optional[GroupTypeIndex] = None,+ cursor: Optional[str] = None,+ dedupe_key: Optional[str] = None,+) -> list[str]:+ """+ Enumerate one page of a batch workflow's audience (person UUIDs, cursor-paginated).++ With dedupe_key="email", persons sharing a normalized email collapse to the one with+ the smallest UUID, so an email address receives a given batch send only once. Persons+ without an email are never collapsed.+ """+ if group_type_index is not None:+ # Group keys are already unique; the flags-owned group query needs no dedup.+ return get_user_blast_radius_persons(team, filters, group_type_index, cursor)++ cleaned_filter = replace_proxy_properties(team, filters)+ select_query = _build_audience_person_query(team, cleaned_filter, cursor=cursor, dedupe_key=dedupe_key)++ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)+ response = execute_hogql_query(query=select_query, team=team)++ return [str(row[0]) for row in response.results] if response.results else []+++def get_batch_audience_count(+ team: Team,+ filters: dict,+ dedupe_key: str,+) -> int:+ """+ Count how many sends a batch workflow would produce with dedup applied — i.e. the+ number of dedupe groups (unique emails, plus one group per email-less person).+ Mirrors get_batch_audience_person_ids so the preview matches the actual audience.+ """+ # Defence-in-depth against a new dedupe key slipping past the endpoint's allowlist:+ # if we ever add another supported key, this raise forces the caller to teach this+ # function about it too, rather than silently returning the email-deduped count.+ if dedupe_key == EMAIL_DEDUPE_KEY:+ group_expr = _email_dedupe_group_expr()+ else:+ raise ValueError(f"Unsupported dedupe_key: {dedupe_key!r} (supported: {SUPPORTED_DEDUPE_KEYS})")++ cleaned_filter = replace_proxy_properties(team, filters)++ where_exprs: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["persons", "team_id"]),+ right=ast.Constant(value=team.pk),+ ),+ property_to_expr(cleaned_filter.property_groups, team, scope="person"),+ ]++ select_query = ast.SelectQuery(+ select=[ast.Call(name="count", distinct=True, args=[group_expr])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ where=ast.And(exprs=where_exprs),+ )++ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)+ response = execute_hogql_query(query=select_query, team=team)++ return response.results[0][0] if response.results else 0+++def _email_dedupe_group_expr() -> ast.Expr:+ # Fields stay fully qualified so nothing resolves to an enclosing query's alias.+ return parse_expr(+ """+ if(+ isNull(persons.properties.email) OR trim(toString(persons.properties.email)) = '',+ toString(persons.id),+ lower(trim(toString(persons.properties.email)))+ )+ """+ )+++def _build_audience_person_query(+ team: Team,+ filter: Filter,+ cursor: Optional[str] = None,+ dedupe_key: Optional[str] = None,+) -> ast.SelectQuery:+ where_exprs: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["persons", "team_id"]),+ right=ast.Constant(value=team.pk),+ ),+ property_to_expr(filter.property_groups, team, scope="person"),+ ]++ if dedupe_key == EMAIL_DEDUPE_KEY:+ return _wrap_with_email_dedupe(where_exprs, cursor)++ if cursor is not None:+ where_exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Field(chain=["persons", "id"]),+ right=ast.Constant(value=cursor),+ )+ )++ return ast.SelectQuery(+ select=[ast.Field(chain=["persons", "id"])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ distinct=True,+ where=ast.And(exprs=where_exprs),+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["persons", "id"]), order="ASC")],+ limit=ast.Constant(value=PERSON_BATCH_SIZE),+ )+++def _wrap_with_email_dedupe(where_exprs: list[ast.Expr], cursor: Optional[str]) -> ast.SelectQuery:+ """+ One person (min UUID) per normalized email; persons without an email keep their own group.++ The cursor filter MUST sit outside the aggregation: applying `id > cursor` before the+ GROUP BY would recompute min(id) over the remaining persons only, re-emitting an email+ whose persons straddle a page boundary.+ """+ inner_query = ast.SelectQuery(+ select=[ast.Alias(alias="person_id", expr=ast.Call(name="min", args=[ast.Field(chain=["persons", "id"])]))],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ where=ast.And(exprs=where_exprs),+ group_by=[_email_dedupe_group_expr()],+ )++ outer_where: Optional[ast.Expr] = None+ if cursor is not None:+ outer_where = ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Field(chain=["person_id"]),+ right=ast.Constant(value=cursor),+ )++ return ast.SelectQuery(+ select=[ast.Field(chain=["person_id"])],+ select_from=ast.JoinExpr(table=inner_query),+ where=outer_where,+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["person_id"]), order="ASC")],+ limit=ast.Constant(value=PERSON_BATCH_SIZE),+ )diff --git a/products/workflows/backend/test/test_batch_audience.py b/products/workflows/backend/test/test_batch_audience.pynew file mode 100644index 000000000000..f3b655d73718--- /dev/null+++ b/products/workflows/backend/test/test_batch_audience.py@@ -0,0 +1,102 @@+import pytest+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events+from unittest.mock import patch++from parameterized import parameterized++from products.feature_flags.backend.user_blast_radius import get_user_blast_radius_persons+from products.workflows.backend.services.batch_audience import (+ get_batch_audience_count,+ get_batch_audience_person_ids,+ use_workflows_batch_audience_query,+)++FILTERS = {"properties": [{"key": "subscribed", "type": "person", "value": ["true"], "operator": "exact"}]}+++def _uuid(index: int) -> str:+ # Only the last digit differs, so string ordering and ClickHouse UUID ordering agree.+ return f"01970000-0000-0000-0000-00000000000{index}"+++class TestBatchAudience(ClickhouseTestMixin, BaseTest):+ def _create_audience(self, emails: list[str | None]) -> list[str]:+ person_ids = []+ for i, email in enumerate(emails, start=1):+ properties: dict = {"subscribed": "true"}+ if email is not None:+ properties["email"] = email+ _create_person(team=self.team, distinct_ids=[f"user-{i}"], uuid=_uuid(i), properties=properties)+ person_ids.append(_uuid(i))+ flush_persons_and_events()+ return person_ids++ @parameterized.expand(+ [+ # Duplicate emails (case/whitespace variants) collapse to the smallest UUID;+ # persons without an email (missing or empty) each keep their own entry.+ ("email_dedupe", "email", [1, 3, 4, 5]),+ ("no_dedupe", None, [1, 2, 3, 4, 5]),+ ]+ )+ def test_audience_dedupe_by_email(self, _name, dedupe_key, expected_indices):+ self._create_audience(["[email protected]", " [email protected] ", "[email protected]", None, ""])++ result = get_batch_audience_person_ids(self.team, FILTERS, dedupe_key=dedupe_key)++ assert sorted(result) == [_uuid(i) for i in expected_indices]++ def test_count_matches_deduped_audience_size(self):+ self._create_audience(["[email protected]", " [email protected] ", "[email protected]", None, ""])++ count = get_batch_audience_count(self.team, FILTERS, dedupe_key="email")++ assert count == len(get_batch_audience_person_ids(self.team, FILTERS, dedupe_key="email")) == 4++ def test_count_rejects_unsupported_dedupe_key(self):+ # Defence-in-depth: the endpoint's serializer allowlist is the primary gate, but this+ # raise forces a future maintainer adding a new supported key to teach the count+ # function about it too, rather than silently returning email-deduped counts.+ with pytest.raises(ValueError, match="Unsupported dedupe_key"):+ get_batch_audience_count(self.team, FILTERS, dedupe_key="sms")++ def test_audience_without_dedupe_matches_legacy_query(self):++ assert sorted(get_batch_audience_person_ids(self.team, FILTERS)) == sorted(+ get_user_blast_radius_persons(self.team, FILTERS)+ )++ @parameterized.expand(+ [+ ("email_dedupe", "email", [1, 2, 3, 5]),+ ("no_dedupe", None, [1, 2, 3, 4, 5]),+ ]+ )+ def test_pagination_emits_each_email_exactly_once(self, _name, dedupe_key, expected_indices):+ # Person 4 duplicates person 1's email but sorts onto a later page — if the cursor+ # were applied inside the aggregation, min(id) would be recomputed per page and+ # [email protected] would be emitted twice.+ self._create_audience(["[email protected]", "[email protected]", "[email protected]", "[email protected]", None])++ collected: list[str] = []+ cursor = None+ with patch("products.workflows.backend.services.batch_audience.PERSON_BATCH_SIZE", 2):+ for _ in range(10):+ page = get_batch_audience_person_ids(self.team, FILTERS, cursor=cursor, dedupe_key=dedupe_key)+ collected.extend(page)+ if len(page) < 2:+ break+ cursor = page[-1]++ assert collected == [_uuid(i) for i in expected_indices]++ def test_use_flag_defaults_off_when_feature_enabled_raises(self):+ # Batch sends are a critical path — a Redis/HyperCache blip that makes+ # posthoganalytics.feature_enabled() throw must fall back to the legacy+ # audience query, not 500 the preview endpoint or fail the resolver job.+ with patch(+ "products.workflows.backend.services.batch_audience.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("HyperCache is down"),+ ):+ assert use_workflows_batch_audience_query(self.team) is Falsediff --git a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsxindex ade51b95bdd9..7737b7282e45 100644--- a/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx+++ b/products/workflows/frontend/Workflows/hogflows/HogFlowManualTriggerButton.tsx@@ -11,7 +11,7 @@ import { CyclotronJobInputSchemaType } from '~/types'import { WorkflowLogicProps, workflowLogic } from '../workflowLogic'import { hogFlowManualTriggerButtonLogic } from './HogFlowManualTriggerButtonLogic'-import { batchTriggerLogic } from './steps/batchTriggerLogic'+import { batchTriggerLogic, getAudienceDedupeKey } from './steps/batchTriggerLogic'const TriggerPopover = ({setPopoverVisible,@@ -28,6 +28,7 @@ const TriggerPopover = ({batchTriggerLogic({id: props.id,filters: workflow?.trigger?.type === 'batch' ? workflow?.trigger?.filters : undefined,+ dedupeKey: getAudienceDedupeKey(workflow),}))diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 79dc12d734a9..8c7b8e521697 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -52,7 +52,7 @@ import { workflowLogic } from '../../workflowLogic'import { HogFlowEventFilters, WORKFLOW_OPERATOR_ALLOWLIST } from '../filters/HogFlowFilters'import { getRegisteredTriggerTypes } from '../registry/triggers/triggerTypeRegistry'import { HogFlowAction } from '../types'-import { batchTriggerLogic } from './batchTriggerLogic'+import { batchTriggerLogic, getAudienceDedupeKey } from './batchTriggerLogic'import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'import { RecurringSchedulePicker } from './components/RecurringSchedulePicker'import { ScheduleStatusBadge } from './components/ScheduleStatusBadge'@@ -494,7 +494,9 @@ function StepTriggerConfigurationManual(): JSX.Element {}function StepTriggerAffectedUsers({ actionId, filters }: { actionId: string; filters: any }): JSX.Element | null {- const logic = batchTriggerLogic({ id: actionId, filters })+ const { workflow } = useValues(workflowLogic)+ const dedupeKey = getAudienceDedupeKey(workflow)+ const logic = batchTriggerLogic({ id: actionId, filters, dedupeKey })const { blastRadiusLoading, blastRadius, blastRadiusError } = useValues(logic)if (blastRadiusLoading) {diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.tsnew file mode 100644index 000000000000..951f7a8ff818--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.test.ts@@ -0,0 +1,68 @@+import { HogFlowAction } from '../types'+import { getAudienceDedupeKey } from './batchTriggerLogic'++const emailAction = (toEmail: string | null): HogFlowAction =>+ ({+ id: 'email_1',+ type: 'function_email',+ name: 'Send email',+ config: {+ template_id: 'template-email',+ inputs:+ toEmail === null+ ? {}+ : {+ email: {+ value: {+ to: { email: toEmail, name: '' },+ from: {},+ subject: 'Hi',+ text: 'Hello',+ html: '<p>Hello</p>',+ },+ },+ },+ },+ }) as any++describe('getAudienceDedupeKey', () => {+ it.each([+ ['{{ person.properties.email }}', 'email' as const],+ ['{{person.properties.email}}', 'email' as const],+ [' {{ person.properties.email }} ', 'email' as const],+ ])('returns "email" for default recipient template %j', (template, expected) => {+ expect(getAudienceDedupeKey({ actions: [emailAction(template)] })).toBe(expected)+ })++ it.each([+ ['{{ person.properties.work_email }}', 'custom property'],+ ['{{ person.properties.email || person.properties.work_email }}', 'computed expression'],+ ['[email protected]', 'static address'],+ ['', 'empty string'],+ [null, 'missing inputs (no email input at all)'],+ ] as [string | null, string][])(+ 'returns undefined when recipient is %j (%s) — avoids deduping on the wrong key',+ (template) => {+ expect(getAudienceDedupeKey({ actions: [emailAction(template)] })).toBeUndefined()+ }+ )++ it('returns undefined when there is no function_email action at all', () => {+ const nonEmailAction = { id: 'a1', type: 'function', config: {} } as any+ expect(getAudienceDedupeKey({ actions: [nonEmailAction] })).toBeUndefined()+ expect(getAudienceDedupeKey({ actions: [] })).toBeUndefined()+ expect(getAudienceDedupeKey({})).toBeUndefined()+ expect(getAudienceDedupeKey(null)).toBeUndefined()+ })++ it('returns undefined when any email action uses a non-default recipient — mixed workflows cannot dedupe consistently', () => {+ expect(+ getAudienceDedupeKey({+ actions: [+ emailAction('{{ person.properties.email }}'),+ emailAction('{{ person.properties.work_email }}'),+ ],+ })+ ).toBeUndefined()+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.tsindex 71d186b83eec..1742bbec70d5 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/batchTriggerLogic.ts@@ -9,9 +9,30 @@ import { BlastRadiusApi } from 'products/workflows/frontend/generated/api.schemaimport { HogFlowAction } from '../types'import type { batchTriggerLogicType } from './batchTriggerLogicType'+// Matches the default email template's `to.email` value: `{{ person.properties.email }}`, whitespace-tolerant.+// Anything else (custom property, computed Liquid, static address) makes the dedupe key diverge from the+// actual send target, so dedupe is skipped rather than applied wrongly.+const DEFAULT_EMAIL_TO_TEMPLATE_RE = /^\s*\{\{\s*person\.properties\.email\s*\}\}\s*$/++export function getAudienceDedupeKey(workflow?: { actions?: HogFlowAction[] } | null): 'email' | undefined {+ // Mirrors the backend (`canDedupeByEmail` in `nodejs/src/cdp/cdp-api.ts`): batch sends dedupe by+ // email only when every email action sends to the default `{{ person.properties.email }}` recipient.+ const emailActions = workflow?.actions?.filter((action) => action.type === 'function_email') ?? []+ if (emailActions.length === 0) {+ return undefined+ }+ const allDefault = emailActions.every((action) => {+ const toEmail = (action as any)?.config?.inputs?.email?.value?.to?.email+ return typeof toEmail === 'string' && DEFAULT_EMAIL_TO_TEMPLATE_RE.test(toEmail)+ })+ return allDefault ? 'email' : undefined+}+export interface BatchTriggerLogicProps {id?: string | 'new'filters?: Extract<HogFlowAction['config'], { type: 'batch' }>['filters']+ /** When 'email', the count reflects unique email addresses, matching batch send dedup. */+ dedupeKey?: 'email'}export const batchTriggerLogic = kea<batchTriggerLogicType>([@@ -42,7 +63,7 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([if (!props.filters) {return null}- return await api.hogFlows.getBatchTriggerBlastRadius(props.filters)+ return await api.hogFlows.getBatchTriggerBlastRadius(props.filters, props.dedupeKey)},},],@@ -58,7 +79,7 @@ export const batchTriggerLogic = kea<batchTriggerLogicType>([},})),propsChanged(({ actions, props }, oldProps) => {- if (!oldProps || !objectsEqual(props.filters, oldProps.filters)) {+ if (!oldProps || !objectsEqual(props.filters, oldProps.filters) || props.dedupeKey !== oldProps.dedupeKey) {actions.loadBlastRadius()}}),diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.tsindex 13cb3b196222..215b46d8ff4e 100644--- a/products/workflows/frontend/generated/api.schemas.ts+++ b/products/workflows/frontend/generated/api.schemas.ts@@ -863,6 +863,15 @@ export interface WorkflowStatsRowApi {*/export type BlastRadiusRequestApiFilters = { [key: string]: unknown }+/**+ * * `email` - email+ */+export type DedupeKeyEnumApi = (typeof DedupeKeyEnumApi)[keyof typeof DedupeKeyEnumApi]++export const DedupeKeyEnumApi = {+ Email: 'email',+} as const+export interface BlastRadiusRequestApi {/** Property filters to apply */filters: BlastRadiusRequestApiFilters@@ -871,6 +880,10 @@ export interface BlastRadiusRequestApi {* @nullable*/group_type_index?: number | null+ /** When 'email', count unique email addresses instead of persons, matching how batch email sends deduplicate recipients.+ *+ * * `email` - email */+ dedupe_key?: DedupeKeyEnumApi | null}export interface BlastRadiusApi {@@ -880,6 +893,10 @@ export interface BlastRadiusApi {total: number/** Maximum allowed audience size for batch triggers for this team. */limit: number+ /** The dedupe key that was actually applied to 'affected'. 'email' means it counts unique email addresses; null means it counts persons.+ *+ * * `email` - email */+ dedupe_key: DedupeKeyEnumApi | null}export type HogFlowTemplatesListParams = {diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.tsindex 3d716fe7f6b7..58b26864bd5e 100644--- a/products/workflows/frontend/generated/api.zod.ts+++ b/products/workflows/frontend/generated/api.zod.ts@@ -2321,4 +2321,10 @@ export const HogFlowsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({export const HogFlowsUserBlastRadiusCreateBody = /* @__PURE__ */ zod.object({filters: zod.record(zod.string(), zod.unknown()).describe('Property filters to apply'),group_type_index: zod.number().nullish().describe('Group type index for group-based targeting'),+ dedupe_key: zod+ .union([zod.enum(['email']).describe('\* `email` - email'), zod.null()])+ .optional()+ .describe(+ "When 'email', count unique email addresses instead of persons, matching how batch email sends deduplicate recipients.\n\n\* `email` - email"+ ),})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e19745386027..0b2a68d05343 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -11915,6 +11915,16 @@ export namespace Schemas {BigQuery: 'BigQuery',} as const;+ /**+ * * `email` - email+ */+ export type DedupeKeyEnum = typeof DedupeKeyEnum[keyof typeof DedupeKeyEnum];+++ export const DedupeKeyEnum = {+ Email: 'email',+ } as const;+export interface BlastRadius {/** Number of users matching the filters */affected: number;@@ -11922,6 +11932,10 @@ export namespace Schemas {total: number;/** Maximum allowed audience size for batch triggers for this team. */limit: number;+ /** The dedupe key that was actually applied to 'affected'. 'email' means it counts unique email addresses; null means it counts persons.+ *+ * * `email` - email */+ dedupe_key: DedupeKeyEnum | null;}/**@@ -11937,6 +11951,10 @@ export namespace Schemas {* @nullable*/group_type_index?: number | null;+ /** When 'email', count unique email addresses instead of persons, matching how batch email sends deduplicate recipients.+ *+ * * `email` - email */+ dedupe_key?: DedupeKeyEnum | null;}export interface BooleanScoreDefinitionConfig {