: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): memory-bounded audience blast radius behind a flag (#96739)
Meikel Ratze7ae958d2624
diff --git a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.mdindex cbdb6903b884..2d28ece3a58d 100644--- a/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md+++ b/.agents/skills/optimizing-clickhouse-and-hogql-queries/references/learnings.md@@ -183,3 +183,29 @@ At 180k docs CURRENT peak*mem was 96 MiB; at 360k it was 174 MiB — memory grow| Candidate-bounded | 88 | 210k | **30 MiB** | **11 MiB** |~18x fewer bytes, ~84x less memory, ~6.6x faster — far larger than the pruned-content case above, and on every axis (the extra DISTINCT scan reads only `document_id` + `metadata`, so total bytes still collapses because `content` is now read for one report's docs, not the team's). Lesson: the candidate-bound win scales with how much per-document data the post-filter throws away — biggest when the dedup buffers a wide column (`content`/`embedding`) that downstream actually needs.++## 2026-09-08: counting persons on big teams: stream it, or better, sample it++Context: the workflows blast radius (count persons matching filters). The person table stores multiple rows per person (one per update), so every "how many persons" query first collapses them to one row per person (`GROUP BY id`). By default ClickHouse does that with an in-memory hash table holding one entry per person. At 87M persons that is 18.6 GiB and the query gets killed.++Three ways to run the same count, measured on team 2 (~87M persons):++| approach | memory | time |+| --------------------------------- | ---------------- | ------ |+| hash table (default) | 18.6 GiB, killed | 0.8 s |+| `optimize_aggregation_in_order=1` | 604 MiB | 9.1 s |+| sample 1 in 64, multiply by 64 | 245 MiB | 0.09 s |++- `optimize_aggregation_in_order=1`: the table is sorted by `(team_id, id)`, so ClickHouse can walk it in order and drop each person's state once all their rows went by. Bounded memory, but ~11x slower: the parallel streams funnel through one thread to keep the order. Use it when the result must be exact.+- Sampling: add `WHERE modulo(cityHash64(id), 64) = 0`, count, multiply by 64. The hash puts every person in one of 64 buckets and you count only bucket 0. Because the bucket comes from `id` (the thing you GROUP BY), all rows of a person land in the same bucket, so the dedup stays exact inside the sample. Only the multiply is an estimate.+- How wrong the estimate gets: about `sqrt(63 / matched)`. ~1% at 640k matches, 17-32% worst case below ~20k. So fall back to the exact query when the sample has few matches (we cut at 10,000 sampled matches), which is exactly where exact is cheap anyway.++Traps we hit:++- Write the sample condition as `modulo(cityHash64(id), 64) = 0`, not `cityHash64(id) % 64 = 0`. Same meaning, but the persons lazy table only pushes function calls into the inner scan; with the `%` operator the pushdown is dropped and the query silently scans the whole team again. Pin the pushdown with a test on the generated SQL.+- Counting distinct groups instead of persons (we count unique emails for send dedup): hash the group key, not the person. Sampling persons makes a 2-person email twice as likely to land in the sample, so the estimate drifts back toward a person count. `cityHash64(lower(trim(email)))` gives every email exactly a 1/64 chance. Worst draw at 87M email groups: 0.2% off.+- Don't put `optimize_aggregation_in_order` on the sampled query. The sample already made the hash table small, so the setting only made it 40% slower with 2.4x the memory (measured).+- `count(DISTINCT id)` on the persons table is a waste when nothing joins: the dedup already returns one row per person, plain `count()` is the same result without holding every id. But a filter that adds a join needs the DISTINCT back, e.g. a `distinct_id` filter joins one row per alias and plain `count()` counts that person once per alias.+- The `id IN (prefilter)` set the persons table builds stays in memory no matter what (it is a set, not a GROUP BY, so the spill setting can't touch it). ~1 GiB per ~6M matched ids. Sampling shrinks it; exact queries on huge broad audiences keep paying it, which is where precalculated audiences eventually win.++Applied in `products/workflows/backend/services/audience_v2.py` behind the `workflows-audience-query-v2` flag.diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 8d4f2b6aed15..6dcc6538155d 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -159,6 +159,12 @@ from products.workflows.backend.services.account_audience import (is_account_audience,parse_account_audience_filters,)+from products.workflows.backend.services.audience_v2 import (+ bounded_memory_settings,+ get_dedupe_audience_count_v2,+ get_person_audience_count_v2,+ use_audience_query_v2,+)from products.workflows.backend.services.batch_audience import (PERSON_BATCH_SIZE as WORKFLOWS_PERSON_BATCH_SIZE,SUPPORTED_DEDUPE_KEYS,@@ -4835,11 +4841,17 @@ class HogFlowViewSet(# echoed back so the frontend labels the count from the response instead of# guessing whether the dedup actually ran.applied_dedupe_key = None+ audience_v2 = group_type_index is None and use_audience_query_v2(self.team)if dedupe_key is not None and group_type_index is None:- total = self.team.persons_seen_so_far- affected = min(get_batch_audience_count(self.team, filters, dedupe_key), total)- blast_radius = BlastRadiusResult(affected=affected, total=total)+ if audience_v2:+ blast_radius = get_dedupe_audience_count_v2(self.team, filters, dedupe_key)+ else:+ total = self.team.persons_seen_so_far+ affected = min(get_batch_audience_count(self.team, filters, dedupe_key), total)+ blast_radius = BlastRadiusResult(affected=affected, total=total)applied_dedupe_key = dedupe_key+ elif audience_v2:+ blast_radius = get_person_audience_count_v2(self.team, filters)else:blast_radius = get_user_blast_radius(self.team, filters, group_type_index)@@ -5633,7 +5645,10 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMitry:reject_flag_conditions_in_audience(team, filters)- result = get_user_blast_radius(team, filters, group_type_index)+ if group_type_index is None and use_audience_query_v2(team):+ result = get_person_audience_count_v2(team, filters)+ else:+ result = get_user_blast_radius(team, filters, group_type_index)return Response(BlastRadiusSerializer({@@ -5678,8 +5693,11 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMitry:reject_flag_conditions_in_audience(team, filters)+ enumeration_settings = (+ bounded_memory_settings() if group_type_index is None and use_audience_query_v2(team) else None+ )users_affected = get_batch_audience_person_ids(- team, filters, group_type_index, cursor, dedupe_key=dedupe_key+ team, filters, group_type_index, cursor, dedupe_key=dedupe_key, settings=enumeration_settings)return Response(InternalBlastRadiusPersonsSerializer(diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex b7b4bbd88d24..b96b58f22612 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -3182,6 +3182,54 @@ class TestHogFlowAPI(APIBaseTest):assert "limit" in bodyassert body["limit"] > 0+ def test_hog_flow_user_blast_radius_routes_to_v2_when_flag_enabled(self):+ with (+ patch("products.workflows.backend.api.hog_flow.use_audience_query_v2", return_value=True),+ patch("products.workflows.backend.api.hog_flow.get_person_audience_count_v2") as mock_v2,+ patch("products.workflows.backend.api.hog_flow.get_dedupe_audience_count_v2") as mock_dedupe_v2,+ patch("products.workflows.backend.api.hog_flow.get_user_blast_radius") as mock_v1,+ ):+ from products.feature_flags.backend.user_blast_radius import BlastRadiusResult # noqa: PLC0415++ mock_v2.return_value = BlastRadiusResult(affected=6400, total=64000)++ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": {"properties": []}},+ )++ assert response.status_code == 200, response.json()+ body = response.json()+ assert body["affected"] == 6400+ assert body["total"] == 64000+ mock_v1.assert_not_called()++ # Dedupe-enabled workflows route to the sampled dedupe count.+ mock_dedupe_v2.return_value = BlastRadiusResult(affected=3200, total=64000)+ 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()+ body = response.json()+ assert body["affected"] == 3200+ assert body["dedupe_key"] == "email"+ mock_dedupe_v2.assert_called_once_with(self.team, {"properties": []}, "email")+ mock_v1.assert_not_called()++ # Group audiences stay on the v1 query even with the flag on: the v2+ # sampled count only covers person audiences.+ mock_v1.return_value = BlastRadiusResult(affected=1, total=2)+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/user_blast_radius",+ {"filters": {"properties": []}, "group_type_index": 0},+ )++ assert response.status_code == 200, response.json()+ mock_v1.assert_called_once()+ mock_v2.assert_called_once()+@override_settings(HOGFLOW_BATCH_TRIGGER_LIMIT=5000,HOGFLOW_BATCH_TRIGGER_LIMIT_ELEVATED=50000,@@ -3327,7 +3375,9 @@ class TestHogFlowAPI(APIBaseTest):assert response.status_code == 200, response.json()assert response.json()["users_affected"] == ["id-1"]- mock_workflows_query.assert_called_once_with(self.team, {"properties": []}, None, None, dedupe_key="email")+ mock_workflows_query.assert_called_once_with(+ self.team, {"properties": []}, None, None, dedupe_key="email", settings=None+ )@parameterized.expand([diff --git a/products/workflows/backend/services/audience_v2.py b/products/workflows/backend/services/audience_v2.pynew file mode 100644index 000000000000..4563678c595d--- /dev/null+++ b/products/workflows/backend/services/audience_v2.py@@ -0,0 +1,238 @@+from typing import Optional++import posthoganalytics++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Database+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.team.team import Team++from products.feature_flags.backend.user_blast_radius import (+ BlastRadiusResult,+ replace_proxy_properties,+ unevaluable_filters_as_validation_errors,+)+from products.workflows.backend.services.batch_audience import (+ EMAIL_DEDUPE_KEY,+ SUPPORTED_DEDUPE_KEYS,+ email_dedupe_group_expr,+)++AUDIENCE_QUERY_V2_FLAG = "workflows-audience-query-v2"++# 1-in-64 sample of the person keyspace. Sampling keys on person id (the dedup key), so every+# version row of a sampled person lands in the sample and the argMax dedup stays exact within it.+SAMPLE_MODULUS = 64++# Below this many sampled matches the extrapolation is too noisy, so rerun exact. The relative+# error of the estimate is about sqrt(63 / matched_persons), so 10,000 sampled matches+# (~640k matched persons) keeps the worst case near 3%. The exact query is usually cheap in+# that regime: few matching persons means the id prefilter keeps the dedup aggregation small.+# Caveat: the prefilter matches any historical row version, so a churny property (many persons+# matched once, few match now) can make the exact rerun carry a candidate set far larger than+# the current match count suggests.+MIN_SAMPLED_MATCHES = 10_000+++def use_audience_query_v2(team: Team) -> bool:+ return bool(+ posthoganalytics.feature_enabled(+ AUDIENCE_QUERY_V2_FLAG,+ str(team.uuid),+ send_feature_flag_events=False,+ )+ )+++def bounded_memory_settings() -> HogQLGlobalSettings:+ """+ Execution settings that keep person-dedup aggregations memory-bounded on large teams.++ The person table sorts by (team_id, id), so with in-order aggregation the dedup+ GROUP BY id streams instead of holding every person in a hash table. The spill+ threshold is the backstop for aggregations where in-order cannot apply (for+ example cohort subqueries): degrade to disk instead of a memory-limit error.+ """+ return HogQLGlobalSettings(+ optimize_aggregation_in_order=True,+ max_bytes_before_external_group_by=4 * 1024**3,+ )+++def get_person_audience_count_v2(team: Team, filters: dict) -> BlastRadiusResult:+ """+ Person-audience blast radius sized from a sample of the person keyspace.++ Counts run on 1 in SAMPLE_MODULUS persons and extrapolate, so cost is bounded on+ teams where the exact dedup count exceeds the query memory limit. When a sample+ holds too few matches for a stable extrapolation, the exact count runs instead.+ """+ with unevaluable_filters_as_validation_errors():+ cleaned_filter = replace_proxy_properties(team, filters)++ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)+ # One database build shared by all counts below; each execute_hogql_query call+ # would otherwise rebuild it, and the build cost scales with warehouse size.+ database = Database.create_for(team=team)++ total = _count_matching_persons(team, None, database)+ if len(cleaned_filter.property_groups.flat) == 0:+ return BlastRadiusResult(affected=total, total=total)++ affected = _count_matching_persons(team, cleaned_filter, database)+ return BlastRadiusResult(affected=min(affected, total), total=total)+++def get_dedupe_audience_count_v2(team: Team, filters: dict, dedupe_key: str) -> BlastRadiusResult:+ """+ Send count for a dedupe-enabled batch workflow, sized from a sample of the dedupe groups.++ Sampling keys on the dedupe group (the normalized email, or the person id when there is+ no email), not on the person: a group with several persons would otherwise be that many+ times more likely to land in the sample, and the estimate would drift back toward a+ person count. Hashing the group gives every group the same 1-in-SAMPLE_MODULUS chance.+ """+ # Defence-in-depth mirror of get_batch_audience_count: a new supported key must be+ # taught to this function too, instead of silently getting the email grouping.+ if dedupe_key != EMAIL_DEDUPE_KEY:+ raise ValueError(f"Unsupported dedupe_key: {dedupe_key!r} (supported: {SUPPORTED_DEDUPE_KEYS})")++ with unevaluable_filters_as_validation_errors():+ cleaned_filter = replace_proxy_properties(team, filters)++ tag_queries(product=Product.WORKFLOWS, feature=Feature.QUERY)+ database = Database.create_for(team=team)++ total = _count_matching_persons(team, None, database)+ sampled = _run_dedupe_count(team, cleaned_filter, database, sample_modulus=SAMPLE_MODULUS)+ if sampled >= MIN_SAMPLED_MATCHES:+ affected = sampled * SAMPLE_MODULUS+ else:+ affected = _run_dedupe_count(team, cleaned_filter, database, sample_modulus=None)+ return BlastRadiusResult(affected=min(affected, total), total=total)+++def _run_dedupe_count(team: Team, filter: Filter, database: Database, sample_modulus: Optional[int]) -> int:+ query = build_dedupe_count_query(team, filter, sample_modulus=sample_modulus)+ response = execute_hogql_query(+ query=query,+ team=team,+ query_type="workflows_audience_count_v2",+ context=HogQLContext(team_id=team.pk, database=database),+ settings=_count_settings(sample_modulus),+ )+ return response.results[0][0] if response.results else 0+++def _count_settings(sample_modulus: Optional[int]) -> HogQLGlobalSettings:+ # A sampled count keeps the fast parallel hash aggregation: the sample already bounds+ # the hash table, and in-order aggregation only makes it slower. The exact runs need+ # the streaming mode to stay memory-bounded on large teams.+ if sample_modulus is not None:+ return HogQLGlobalSettings(max_bytes_before_external_group_by=4 * 1024**3)+ return bounded_memory_settings()+++def build_dedupe_count_query(team: Team, filter: Filter, sample_modulus: Optional[int]) -> 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),+ )+ ]+ if sample_modulus is not None:+ # A fresh group expr per use: the resolver annotates AST nodes in place, so the+ # WHERE and SELECT must not share one instance.+ where_exprs.append(+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Call(+ name="modulo",+ args=[+ ast.Call(name="cityHash64", args=[email_dedupe_group_expr()]),+ ast.Constant(value=sample_modulus),+ ],+ ),+ right=ast.Constant(value=0),+ )+ )+ if len(filter.property_groups.flat) > 0:+ where_exprs.append(property_to_expr(filter.property_groups, team, scope="person"))++ return ast.SelectQuery(+ select=[ast.Call(name="count", distinct=True, args=[email_dedupe_group_expr()])],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ where=ast.And(exprs=where_exprs),+ )+++def _count_matching_persons(team: Team, filter: Optional[Filter], database: Database) -> int:+ sampled = _run_person_count(team, filter, database, sample_modulus=SAMPLE_MODULUS)+ if sampled >= MIN_SAMPLED_MATCHES:+ return sampled * SAMPLE_MODULUS+ return _run_person_count(team, filter, database, sample_modulus=None)+++def _run_person_count(team: Team, filter: Optional[Filter], database: Database, sample_modulus: Optional[int]) -> int:+ query = build_person_count_query(team, filter, sample_modulus=sample_modulus)+ response = execute_hogql_query(+ query=query,+ team=team,+ query_type="workflows_audience_count_v2",+ context=HogQLContext(team_id=team.pk, database=database),+ settings=_count_settings(sample_modulus),+ )+ return response.results[0][0] if response.results else 0+++def build_person_count_query(team: Team, filter: Optional[Filter], sample_modulus: Optional[int]) -> 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),+ )+ ]+ if sample_modulus is not None:+ where_exprs.append(_sample_predicate(sample_modulus))+ if filter is not None:+ where_exprs.append(property_to_expr(filter.property_groups, team, scope="person"))++ # A filter can add a one-to-many join: a `distinct_id` person property resolves through+ # persons.pdi, which gives a person one row per distinct id. So a filtered count dedups on+ # the person id. The unfiltered total joins nothing, so it keeps the plain count() and+ # avoids a uniqExact state over every person on the team.+ if filter is None:+ count_expr: ast.Expr = ast.Call(name="count", args=[])+ else:+ count_expr = ast.Call(name="count", distinct=True, args=[ast.Field(chain=["persons", "id"])])++ return ast.SelectQuery(+ select=[count_expr],+ select_from=ast.JoinExpr(table=ast.Field(chain=["persons"])),+ where=ast.And(exprs=where_exprs),+ )+++def _sample_predicate(modulus: int) -> ast.Expr:+ # Built as modulo(...) calls, not the % operator: WhereClauseExtractor fails safe to+ # "no prefilter" on ArithmeticOperation nodes, and the memory bound depends on this+ # predicate reaching the raw person scan inside the persons lazy table.+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Call(+ name="modulo",+ args=[+ ast.Call(name="cityHash64", args=[ast.Field(chain=["persons", "id"])]),+ ast.Constant(value=modulus),+ ],+ ),+ right=ast.Constant(value=0),+ )diff --git a/products/workflows/backend/services/batch_audience.py b/products/workflows/backend/services/batch_audience.pyindex 06e1885850df..c25fd7abfc7f 100644--- a/products/workflows/backend/services/batch_audience.py+++ b/products/workflows/backend/services/batch_audience.py@@ -1,10 +1,12 @@from typing import Optionalfrom posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.parser import parse_exprfrom posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models.filters import Filterfrom posthog.models.property import GroupTypeIndex@@ -28,6 +30,7 @@ def get_batch_audience_person_ids(group_type_index: Optional[GroupTypeIndex] = None,cursor: Optional[str] = None,dedupe_key: Optional[str] = None,+ settings: Optional[HogQLGlobalSettings] = None,) -> list[str]:"""Enumerate one page of a batch workflow's audience (person UUIDs, cursor-paginated).@@ -45,7 +48,9 @@ def get_batch_audience_person_ids(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)+ # Background traffic: the only caller is the internal batch-send resolver, so route to+ # the offline pool like the group branch does, away from interactive product queries.+ response = execute_hogql_query(query=select_query, team=team, settings=settings, workload=Workload.OFFLINE)return [str(row[0]) for row in response.results] if response.results else []@@ -69,7 +74,7 @@ def get_batch_audience_count(# 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()+ group_expr = email_dedupe_group_expr()else:raise ValueError(f"Unsupported dedupe_key: {dedupe_key!r} (supported: {SUPPORTED_DEDUPE_KEYS})")@@ -104,7 +109,7 @@ def get_batch_audience_count(return response.results[0][0] if response.results else 0-def _email_dedupe_group_expr() -> ast.Expr:+def email_dedupe_group_expr() -> ast.Expr:# Fields stay fully qualified so nothing resolves to an enclosing query's alias.return parse_expr("""@@ -166,7 +171,7 @@ def _wrap_with_email_dedupe(where_exprs: list[ast.Expr], cursor: Optional[str])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()],+ group_by=[email_dedupe_group_expr()],)outer_where: Optional[ast.Expr] = Nonediff --git a/products/workflows/backend/test/test_audience_v2.py b/products/workflows/backend/test/test_audience_v2.pynew file mode 100644index 000000000000..970a7b1258c8--- /dev/null+++ b/products/workflows/backend/test/test_audience_v2.py@@ -0,0 +1,204 @@+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_person, flush_persons_and_events+from unittest.mock import patch++from posthog.hogql.query import execute_hogql_query++from products.cohorts.backend.models.cohort import Cohort+from products.feature_flags.backend.user_blast_radius import get_user_blast_radius, replace_proxy_properties+from products.workflows.backend.services.audience_v2 import (+ bounded_memory_settings,+ build_dedupe_count_query,+ build_person_count_query,+ get_dedupe_audience_count_v2,+ get_person_audience_count_v2,+)+from products.workflows.backend.services.batch_audience import get_batch_audience_count++FILTERS = {"properties": [{"key": "subscribed", "type": "person", "value": ["true"], "operator": "exact"}]}+++class TestAudienceV2(ClickhouseTestMixin, BaseTest):+ def _create_persons(self, subscribed_flags: list[bool]) -> None:+ for i, subscribed in enumerate(subscribed_flags, start=1):+ _create_person(+ team=self.team,+ distinct_ids=[f"user-{i}"],+ properties={"subscribed": "true" if subscribed else "false"},+ )+ flush_persons_and_events()++ def test_small_audience_falls_back_to_exact_count_and_matches_v1(self):+ # A handful of persons never clears MIN_SAMPLED_MATCHES under the default 1-in-64+ # sample, so this exercises the exact fallback and pins it to the v1 result.+ self._create_persons([True, True, True, False])++ result = get_person_audience_count_v2(self.team, FILTERS)+ v1_result = get_user_blast_radius(self.team, FILTERS)++ assert (result.affected, result.total) == (3, 4)+ assert (result.affected, result.total) == (v1_result.affected, v1_result.total)++ def test_sampled_path_extrapolates_by_modulus(self):+ self._create_persons([True, True, False])++ # Modulus 1 samples everyone and MIN_SAMPLED_MATCHES 0 forces the sampled branch,+ # so the extrapolated result must equal the exact count.+ with (+ patch("products.workflows.backend.services.audience_v2.SAMPLE_MODULUS", 1),+ patch("products.workflows.backend.services.audience_v2.MIN_SAMPLED_MATCHES", 0),+ ):+ result = get_person_audience_count_v2(self.team, FILTERS)++ assert (result.affected, result.total) == (2, 3)++ def test_no_filters_returns_total_for_everyone(self):+ self._create_persons([True, False])++ result = get_person_audience_count_v2(self.team, {})++ assert (result.affected, result.total) == (2, 2)++ def test_person_whose_latest_version_no_longer_matches_is_excluded(self):+ # The id prefilter matches any row version, but only the latest version decides+ # membership. A person updated from subscribed=true to false must not count.+ churned_uuid = "01970000-0000-0000-0000-0000000000a1"+ _create_person(+ team=self.team,+ distinct_ids=["churned"],+ uuid=churned_uuid,+ properties={"subscribed": "true"},+ version=0,+ )+ _create_person(+ team=self.team,+ distinct_ids=["churned-v1"],+ uuid=churned_uuid,+ properties={"subscribed": "false"},+ version=1,+ )+ _create_person(team=self.team, distinct_ids=["kept"], properties={"subscribed": "true"})+ flush_persons_and_events()++ result = get_person_audience_count_v2(self.team, FILTERS)++ assert (result.affected, result.total) == (1, 2)++ def test_distinct_id_filter_counts_a_person_with_several_aliases_once(self):+ # A `distinct_id` person property resolves through the persons.pdi join, which gives a+ # person one row per distinct id. Both count branches must dedup on the person id, or+ # the preview reports more sends than the enumeration produces.+ _create_person(team=self.team, distinct_ids=["alias-a", "alias-b"], properties={"subscribed": "true"})+ _create_person(team=self.team, distinct_ids=["other"], properties={"subscribed": "true"})+ flush_persons_and_events()++ filters = {+ "properties": [+ {"key": "distinct_id", "type": "person", "value": ["alias-a", "alias-b"], "operator": "exact"}+ ]+ }++ result = get_person_audience_count_v2(self.team, filters)+ v1_result = get_user_blast_radius(self.team, filters)++ assert (result.affected, result.total) == (1, 2)+ assert (result.affected, result.total) == (v1_result.affected, v1_result.total)++ with (+ patch("products.workflows.backend.services.audience_v2.SAMPLE_MODULUS", 1),+ patch("products.workflows.backend.services.audience_v2.MIN_SAMPLED_MATCHES", 0),+ ):+ sampled_result = get_person_audience_count_v2(self.team, filters)++ assert (sampled_result.affected, sampled_result.total) == (1, 2)++ def test_cohort_filter_matches_v1(self):+ # Cohort filters compile to a different subquery shape than plain property filters,+ # so the sampled query and the bounded settings must not break them.+ for i in range(6):+ _create_person(team=self.team, distinct_ids=[f"cohort-user-{i}"], properties={"group": str(i)})+ flush_persons_and_events()+ cohort = Cohort.objects.create(+ team=self.team,+ name="cohort1",+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {"type": "OR", "values": [{"key": "group", "value": ["1", "2", "3"], "type": "person"}]}+ ],+ }+ },+ )+ filters = {"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}++ result = get_person_audience_count_v2(self.team, filters)+ v1_result = get_user_blast_radius(self.team, filters)++ assert (result.affected, result.total) == (3, 6)+ assert (result.affected, result.total) == (v1_result.affected, v1_result.total)++ cohort.calculate_people_ch(pending_version=0)+ with self.settings(USE_PRECALCULATED_CH_COHORT_PEOPLE=True):+ result = get_person_audience_count_v2(self.team, filters)++ assert (result.affected, result.total) == (3, 6)++ def test_dedupe_count_matches_v1(self):+ # Duplicate emails (case/whitespace variants) collapse to one send group; persons+ # without an email keep their own group. Small data exercises the exact fallback.+ 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}"], properties=properties)+ flush_persons_and_events()++ result = get_dedupe_audience_count_v2(self.team, FILTERS, "email")++ assert result.affected == get_batch_audience_count(self.team, FILTERS, dedupe_key="email") == 4+ assert result.total == 5++ def test_sampled_dedupe_count_extrapolates_by_modulus(self):+ for i in range(3):+ _create_person(+ team=self.team,+ distinct_ids=[f"user-{i}"],+ properties={"subscribed": "true", "email": f"user-{i}@example.com"},+ )+ flush_persons_and_events()++ with (+ patch("products.workflows.backend.services.audience_v2.SAMPLE_MODULUS", 1),+ patch("products.workflows.backend.services.audience_v2.MIN_SAMPLED_MATCHES", 0),+ ):+ result = get_dedupe_audience_count_v2(self.team, FILTERS, "email")++ assert (result.affected, result.total) == (3, 3)++ def test_dedupe_sampling_predicate_reaches_raw_person_prefilter(self):+ # Same guard as the person-count variant below, for the group-hash predicate.+ cleaned_filter = replace_proxy_properties(self.team, FILTERS)+ query = build_dedupe_count_query(self.team, cleaned_filter, sample_modulus=64)+ response = execute_hogql_query(query=query, team=self.team, settings=bounded_memory_settings())++ clickhouse_sql = response.clickhouse+ assert clickhouse_sql is not None+ assert "AS where_optimization" in clickhouse_sql+ assert "cityHash64" in clickhouse_sql.split("AS where_optimization", 1)[1]++ def test_sampling_predicate_reaches_raw_person_prefilter(self):+ # The memory bound depends on WhereClauseExtractor pushing the call-form sampling+ # predicate into the raw person scan. If that push stops (for example the predicate+ # becomes an arithmetic node, which the extractor refuses), the sampled query+ # silently degrades to a full-team dedup and large teams hit the memory limit again.+ query = build_person_count_query(self.team, None, sample_modulus=64)+ response = execute_hogql_query(query=query, team=self.team, settings=bounded_memory_settings())++ clickhouse_sql = response.clickhouse+ assert clickhouse_sql is not None+ assert "AS where_optimization" in clickhouse_sql+ inner_scan = clickhouse_sql.split("AS where_optimization", 1)[1]+ assert "cityHash64" in inner_scan+ assert "optimize_aggregation_in_order" in clickhouse_sql+ assert "max_bytes_before_external_group_by=4294967296" in clickhouse_sql