: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
fix(workflows): fetch batch audiences in pages of 5000 persons (#101922)
Daniel Marchuk9738e386d6b5
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 005c60a3343b..96aaf0789cb7 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -3,6 +3,8 @@ import osimport jsonfrom datetime import timedelta+from django.core.exceptions import ImproperlyConfigured+import structlogfrom corsheaders.defaults import default_headersfrom whitenoise.compress import Compressor@@ -1055,6 +1057,13 @@ HOG_FUNCTIONS_DAILY_DIGEST_TEAM_IDS = get_list(get_from_env("HOG_FUNCTIONS_DAILY# Maximum audience size for HogFlow batch triggers. Default that applies to all teams unless they# opt in to the elevated value below. Only used to inform the frontend UI; no backend enforcement.HOGFLOW_BATCH_TRIGGER_LIMIT = int(get_from_env("HOGFLOW_BATCH_TRIGGER_LIMIT", 500000))+# Persons per page when the batch resolver enumerates a workflow audience. Each page is a separate+# ClickHouse query, so a bigger page means fewer scans per run; the resolver inserts a page as one+# Postgres transaction, which is why this is not unbounded.+WORKFLOWS_PERSON_BATCH_SIZE = int(get_from_env("WORKFLOWS_PERSON_BATCH_SIZE", 5000))+if WORKFLOWS_PERSON_BATCH_SIZE < 1:+ # An empty page reports has_more, so the resolver would refetch it forever.+ raise ImproperlyConfigured("WORKFLOWS_PERSON_BATCH_SIZE must be at least 1")# Elevated maximum audience size, returned for teams listed in HOGFLOW_BATCH_TRIGGER_ELEVATED_TEAM_IDS.HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED = int(get_from_env("HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED", 1000000))# Comma-separated list of team IDs that get the elevated batch trigger limit instead of the default.diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex bf7e5827002a..6de68ac13d7e 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -166,8 +166,8 @@ from products.workflows.backend.services.audience_v2 import (use_audience_query_v2,)from products.workflows.backend.services.batch_audience import (- PERSON_BATCH_SIZE as WORKFLOWS_PERSON_BATCH_SIZE,SUPPORTED_DEDUPE_KEYS,+ audience_page_size,get_batch_audience_count,get_batch_audience_person_ids,)@@ -6073,7 +6073,7 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi{"users_affected": users_affected,"cursor": users_affected[-1] if users_affected else None,- "has_more": len(users_affected) == WORKFLOWS_PERSON_BATCH_SIZE,+ "has_more": len(users_affected) == audience_page_size(group_type_index),}).data)diff --git a/products/workflows/backend/services/batch_audience.py b/products/workflows/backend/services/batch_audience.pyindex c25fd7abfc7f..a3cd40e7e8f0 100644--- a/products/workflows/backend/services/batch_audience.py+++ b/products/workflows/backend/services/batch_audience.py@@ -1,5 +1,7 @@from typing import Optional+from django.conf import settings+from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.parser import parse_expr@@ -13,17 +15,31 @@ from posthog.models.property import GroupTypeIndexfrom posthog.models.team.team import Teamfrom products.feature_flags.backend.user_blast_radius import (+ PERSON_BATCH_SIZE as GROUP_AUDIENCE_PAGE_SIZE,get_user_blast_radius_persons,replace_proxy_properties,unevaluable_filters_as_validation_errors,)-PERSON_BATCH_SIZE = 500-EMAIL_DEDUPE_KEY = "email"SUPPORTED_DEDUPE_KEYS = (EMAIL_DEDUPE_KEY,)+def person_audience_page_size() -> int:+ return settings.WORKFLOWS_PERSON_BATCH_SIZE+++def audience_page_size(group_type_index: Optional[GroupTypeIndex]) -> int:+ """+ Page size the resolver must compare a page length against to decide `has_more`.++ Group audiences page through the flags-owned group query, which keeps its own fixed limit.+ """+ if group_type_index is not None:+ return GROUP_AUDIENCE_PAGE_SIZE+ return person_audience_page_size()++def get_batch_audience_person_ids(team: Team,filters: dict,@@ -155,7 +171,7 @@ def _build_audience_person_query(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),+ limit=ast.Constant(value=person_audience_page_size()),)@@ -187,5 +203,5 @@ def _wrap_with_email_dedupe(where_exprs: list[ast.Expr], cursor: Optional[str])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),+ limit=ast.Constant(value=person_audience_page_size()),)diff --git a/products/workflows/backend/test/test_batch_audience.py b/products/workflows/backend/test/test_batch_audience.pyindex cb9b37256545..aaf61f9c0f0f 100644--- a/products/workflows/backend/test/test_batch_audience.py+++ b/products/workflows/backend/test/test_batch_audience.py@@ -1,11 +1,16 @@import pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events-from unittest.mock import patch++from django.test import override_settingsfrom 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+from products.feature_flags.backend.user_blast_radius import PERSON_BATCH_SIZE, get_user_blast_radius_persons+from products.workflows.backend.services.batch_audience import (+ audience_page_size,+ get_batch_audience_count,+ get_batch_audience_person_ids,+)FILTERS = {"properties": [{"key": "subscribed", "type": "person", "value": ["true"], "operator": "exact"}]}@@ -77,7 +82,7 @@ class TestBatchAudience(ClickhouseTestMixin, BaseTest):collected: list[str] = []cursor = None- with patch("products.workflows.backend.services.batch_audience.PERSON_BATCH_SIZE", 2):+ with override_settings(WORKFLOWS_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)@@ -86,3 +91,10 @@ class TestBatchAudience(ClickhouseTestMixin, BaseTest):cursor = page[-1]assert collected == [_uuid(i) for i in expected_indices]++ @override_settings(WORKFLOWS_PERSON_BATCH_SIZE=7)+ def test_has_more_page_size_follows_the_audience_kind(self):+ # A group audience pages through the flags-owned query with its own limit; comparing its+ # page length against the person setting would stop after the first page.+ assert audience_page_size(None) == 7+ assert audience_page_size(0) == PERSON_BATCH_SIZE