Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(marketing-analytics): warm flagged teams and let background warms write (#105636)

Lucas Ricoy5db83a61522f
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index b00398af4848..696b6c248677 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -52,6 +52,7 @@ from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precomput
BACKGROUND_WARMING_TRIGGERS,
handle_not_ready,
handle_stale_served,
+ is_on_demand_revalidation,
marketing_ensure_precomputed,
)
from products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_name
@@ -1244,7 +1245,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
# Build the cost source. When cost precompute is enabled, read the native materialized table
# (no S3); fall back to the live S3 adapter union if not enabled or jobs aren't ready.
union_subquery: ast.SelectQuery | ast.SelectSetQuery | None = None
- if self.config.costs_precomputation_enabled:
+ if self.config.costs_precomputation_enabled and not is_on_demand_revalidation():
with self.timings.measure("ma_build_costs_precompute"):
try:
union_subquery = self._build_costs_from_precompute(self.query_date_range)
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
index e229a27907c0..246952433459 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_config.py
@@ -50,6 +50,9 @@ MULTI_TOUCH_MODES: frozenset[AttributionMode] = frozenset(
}
)
+# Conversion-goal reads serve from the precompute for a team with this flag on.
+CONVERSION_PRECOMPUTE_FLAG = "marketing-analytics-precomputation"
+
# Mutable by design: `from_team` builds a default instance and then overwrites the
# team-derived fields on it, rather than threading them all through the constructor.
@@ -133,7 +136,7 @@ class MarketingAnalyticsConfig:
group_properties = {"organization": {"id": str(team.organization.id)}}
flags = {
"conversion": feature_enabled_or_false(
- "marketing-analytics-precomputation",
+ CONVERSION_PRECOMPUTE_FLAG,
str(team.uuid),
groups=groups,
group_properties=group_properties,
@@ -154,6 +157,23 @@ class MarketingAnalyticsConfig:
team._ma_precompute_flags = flags # type: ignore[attr-defined]
return flags
+ @staticmethod
+ def conversion_precompute_enabled_without_exposure(team: "Team") -> bool:
+ """Evaluate only the conversion read flag, and record no exposure for it.
+
+ For a background inventory scan that reads the flag to pick an audience, which is not a user
+ read of marketing analytics. It must not count as an exposure, because synthetic exposures
+ distort the flag's own rollout numbers, and it has no use for the cost and session flags that
+ `_precompute_flags` evaluates alongside the conversion one.
+ """
+ return feature_enabled_or_false(
+ CONVERSION_PRECOMPUTE_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization.id)},
+ group_properties={"organization": {"id": str(team.organization.id)}},
+ send_feature_flag_events=False,
+ )
+
@staticmethod
def _multi_touch_enabled(team: "Team") -> bool:
"""Evaluate the multi-touch attribution flag once per team instance.
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py
index 8d9fc658b4ea..c57c41bc4ef2 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py
@@ -28,7 +28,7 @@ import structlog
from prometheus_client import Counter
from posthog import redis
-from posthog.clickhouse.query_tagging import tag_queries
+from posthog.clickhouse.query_tagging import get_query_tag_value, tag_queries
from posthog.models import Team
from posthog.token_bucket import BucketDecision, Budget, consume
@@ -150,6 +150,16 @@ def _scope_to_revalidation(query: Any) -> Any:
return scoped
+def is_on_demand_revalidation() -> bool:
+ """True inside the Celery revalidation task, which a user read can trigger.
+
+ It materializes userless with warehouse access control bypassed, so it must not write cost rows: the
+ precomputed costs table holds every source's spend, and a user without access to a source could then
+ read it. The Dagster warmer still builds costs.
+ """
+ return get_query_tag_value("trigger") == REVALIDATION_TRIGGER
+
+
def enqueue_stale_revalidation(*, team: Team, query: Any) -> None:
"""Schedule a background re-run so the next read of this query shape is fresh.
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
index 1e65259e839c..27ab6d4a29c2 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_costs_precompute.py
@@ -18,6 +18,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.execute import sync_execute
from posthog.clickhouse.preaggregation.marketing_costs_sql import DISTRIBUTED_MARKETING_COSTS_TABLE
+from posthog.clickhouse.query_tagging import tags_context
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from products.marketing_analytics.backend.hogql_queries.adapters.base import (
@@ -30,6 +31,7 @@ from products.marketing_analytics.backend.hogql_queries.adapters.google_ads impo
from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (
MarketingAnalyticsTableQueryRunner,
)
+from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import REVALIDATION_TRIGGER
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
TEST_BUCKET = "test_marketing_costs"
@@ -307,6 +309,26 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):
f"deduped row should carry the latest {label_column} '{post_value}', not the stale '{pre_value}'"
)
+ @parameterized.expand([("user_read", None, True), ("on_demand_revalidation", REVALIDATION_TRIGGER, False)])
+ def test_on_demand_revalidation_never_builds_costs(self, _name, trigger, expect_costs_build):
+ # The Celery revalidation runs userless with warehouse access control bypassed, and a user read
+ # can trigger it. Cost rows it wrote would expose every source's spend to users denied a source.
+ runner = MarketingAnalyticsTableQueryRunner(
+ query=MarketingAnalyticsTableQuery(
+ dateRange=DateRange(date_from="2023-01-01", date_to="2023-01-31"), limit=100, offset=0, properties=[]
+ ),
+ team=self.team,
+ )
+ runner.config.costs_precomputation_enabled = True
+
+ with (
+ tags_context(trigger=trigger),
+ patch.object(runner, "_build_costs_from_precompute", return_value=None) as build_costs,
+ ):
+ runner.to_query()
+
+ assert build_costs.called is expect_costs_build
+
def test_one_unmaterializable_source_does_not_force_all_to_s3(self):
# One source materializes, one can't. The result must read the native table for the materialized
# source and keep only the other on the live S3 union — not fall back to S3 for everything.
diff --git a/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.py b/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.py
index d9d7da42221a..e82591dcd990 100644
--- a/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.py
+++ b/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.py
@@ -74,14 +74,15 @@ def revalidate_marketing_analytics_precompute(team_id: int, query: dict) -> None
started = time.monotonic()
try:
# Tag BEFORE building the runner: tags live in a contextvar that the runner's construction-time
- # I/O inherits. The trigger and the CACHE_WARMUP feature both classify this re-run as a
- # refresher, so its ensures get no serve-stale grace (it must not serve stale to itself, or the
- # data would never refresh) and keep the framework's full wait budget. Celery resets query tags
- # on task_postrun, so this never leaks across tasks.
+ # I/O inherits. The trigger classifies this re-run as a refresher, so its ensures get no
+ # serve-stale grace (it must not serve stale to itself, or the data would never refresh) and keep
+ # the framework's full wait budget. Not CACHE_WARMUP: in Celery that feature routes queries to the
+ # read-only cache_warmup ClickHouse user, which refuses every precompute INSERT. Celery resets
+ # query tags on task_postrun, so this never leaks across tasks.
tag_queries(
team_id=team_id,
trigger=REVALIDATION_TRIGGER,
- feature=Feature.CACHE_WARMUP,
+ feature=Feature.PREAGGREGATION,
product=Product.MARKETING_ANALYTICS,
)
runner = get_query_runner(query=query, team=team, limit_context=LimitContext.QUERY_ASYNC)
diff --git a/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.py b/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.py
index b29b32cb5b60..013f5e37e662 100644
--- a/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.py
+++ b/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.py
@@ -5,7 +5,8 @@ from posthog.schema import DateRange, MarketingAnalyticsTableQuery
from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset_query_tags
-from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import REVALIDATION_TRIGGER
+from products.analytics_platform.backend.lazy_computation.stale_policy import is_background_warming_request
+from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import BACKGROUND_WARMING_TRIGGERS
from products.marketing_analytics.backend.tasks.lazy_precompute_revalidation import (
revalidate_marketing_analytics_precompute,
)
@@ -33,19 +34,20 @@ class TestMarketingLazyPrecomputeRevalidation(BaseTest):
# It must build (to_query) but NOT execute (run): a full run of this userless, access-control-
# bypassed runner would write an all-sources response into the shared per-team result cache, which
# a warehouse-restricted user could then read.
- tags_at_build = {}
+ tags_at_build: dict[str, object] = {}
runner = mock.MagicMock()
def capture(**_kwargs):
+ tags_at_build["refresher"] = is_background_warming_request(BACKGROUND_WARMING_TRIGGERS)
tags_at_build["feature"] = get_query_tag_value("feature")
- tags_at_build["trigger"] = get_query_tag_value("trigger")
return runner
get_runner.side_effect = capture
revalidate_marketing_analytics_precompute(team_id=self.team.pk, query=self.query)
- assert tags_at_build == {"feature": Feature.CACHE_WARMUP, "trigger": REVALIDATION_TRIGGER}
+ # CACHE_WARMUP would route the INSERTs to the read-only cache_warmup ClickHouse user.
+ assert tags_at_build == {"refresher": True, "feature": Feature.PREAGGREGATION}
runner.to_query.assert_called_once_with()
runner.run.assert_not_called()
diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.py
index d420befc9ff8..47f1a90b50e6 100644
--- a/products/marketing_analytics/dags/marketing_precompute.py
+++ b/products/marketing_analytics/dags/marketing_precompute.py
@@ -27,8 +27,8 @@ poisoning and no access-control bypass.
The audience is `MARKETING_PRECOMPUTE_TEAM_IDS`: comma-separated team IDs, empty to disable warming, or
`auto` to warm every team that has a conversion goal AND has opened marketing analytics recently
-(query_log). Unset, it falls back to `DEFAULT_ROLLOUT_TEAM_IDS` on PostHog Cloud and to no teams
-elsewhere. `MARKETING_PRECOMPUTE_ACTIVE_DAYS` tunes the `auto` activity window.
+(query_log). Unset, it warms the teams with a conversion goal and the read flag on, on PostHog Cloud
+only. `MARKETING_PRECOMPUTE_ACTIVE_DAYS` tunes the `auto` activity window.
"""
import os
@@ -106,9 +106,6 @@ COST_MATERIALIZATION_GRAINS = (
MarketingAnalyticsDrillDownLevel.AD,
)
-# Teams warmed on PostHog Cloud when the env var is unset. Kept to the dogfood team until the fleet-wide
-# `auto` audience is validated.
-DEFAULT_ROLLOUT_TEAM_IDS = [2]
# Comma-separated team IDs to warm, empty to disable warming, or `auto` to discover the audience.
SELECTED_TEAM_IDS_ENV_VAR = "MARKETING_PRECOMPUTE_TEAM_IDS"
AUTO_AUDIENCE = "auto"
@@ -178,12 +175,33 @@ def _recently_active_team_ids(days: int) -> set[int] | None:
return None
+def _goal_team_ids() -> set[int]:
+ return set(
+ TeamMarketingAnalyticsConfig.objects.exclude(_conversion_goals=[])
+ .exclude(_conversion_goals__isnull=True)
+ .values_list("team_id", flat=True)
+ )
+
+
+def _read_flag_team_ids() -> list[int]:
+ """Goal teams that have the `marketing-analytics-precomputation` read flag on.
+
+ Only that flag is evaluated, and without an exposure event: this hourly scan picks an audience, so
+ it must not look like every goal team read marketing analytics behind the flag.
+ """
+ teams = Team.objects.filter(pk__in=_goal_team_ids()).select_related("organization")
+ return sorted(
+ team.pk for team in teams if MarketingAnalyticsConfig.conversion_precompute_enabled_without_exposure(team)
+ )
+
+
def get_selected_team_ids() -> list[int]:
"""Resolve which teams to warm.
- Unset, the env var falls back to DEFAULT_ROLLOUT_TEAM_IDS on PostHog Cloud only, so self-hosted never
- warms unrelated teams that share those IDs. Set, it wins (even when empty, as a kill switch): a
- comma-separated list with blank or invalid entries skipped.
+ Unset, it warms every team that has a conversion goal and the `marketing-analytics-precomputation`
+ read flag on. Those reads are precompute-only, so a flagged team the warmer skips reads not-ready.
+ Cloud only: self-hosted has no flag rollout to follow. Set, the env var wins (even when empty, as a
+ kill switch): a comma-separated list with blank or invalid entries skipped.
`auto` warms every team that both has a conversion goal (`TeamMarketingAnalyticsConfig`) and has
opened marketing analytics recently (query_log), which keeps the rolling warm set to the active
@@ -191,15 +209,11 @@ def get_selected_team_ids() -> list[int]:
"""
raw = os.getenv(SELECTED_TEAM_IDS_ENV_VAR)
if raw is None:
- return list(DEFAULT_ROLLOUT_TEAM_IDS) if is_cloud() else []
+ return _read_flag_team_ids() if is_cloud() else []
if raw.strip().lower() != AUTO_AUDIENCE:
return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]
- goal_team_ids = set(
- TeamMarketingAnalyticsConfig.objects.exclude(_conversion_goals=[])
- .exclude(_conversion_goals__isnull=True)
- .values_list("team_id", flat=True)
- )
+ goal_team_ids = _goal_team_ids()
if not goal_team_ids:
return []
diff --git a/products/marketing_analytics/dags/tests/test_marketing_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_precompute.py
index f040e922a50d..3b5051f27878 100644
--- a/products/marketing_analytics/dags/tests/test_marketing_precompute.py
+++ b/products/marketing_analytics/dags/tests/test_marketing_precompute.py
@@ -126,12 +126,6 @@ class TestGetSelectedTeamIds:
with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):
assert get_selected_team_ids() == []
- @parameterized.expand([("cloud", True, [2]), ("self_hosted", False, [])])
- def test_unset_defaults_to_rollout_teams_on_cloud_only(self, _name, cloud, expected):
- with patch.dict(os.environ, {}, clear=False), patch(_IS_CLOUD, return_value=cloud):
- os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)
- assert get_selected_team_ids() == expected
-
class TestConversionWarming(APIBaseTest):
"""Touchpoints + conversions orchestration; ensure_precomputed is patched so no ClickHouse traffic."""
@@ -144,6 +138,32 @@ class TestConversionWarming(APIBaseTest):
team.marketing_analytics_config.save()
return team
+ @parameterized.expand([("cloud", True), ("self_hosted", False)])
+ def test_unset_audience_is_goal_teams_with_the_read_flag(self, _name, cloud):
+ # Reads are precompute-only for flagged teams, so the default audience must follow the flag.
+ flagged = self._make_team("flagged", goals=[_PRECOMPUTABLE_GOAL])
+ unflagged = self._make_team("unflagged", goals=[_PRECOMPUTABLE_GOAL])
+ flagged_no_goals = self._make_team("flagged_no_goals", goals=[])
+ flagged_uuids = {str(flagged.uuid), str(flagged_no_goals.uuid)}
+
+ def read_flag(flag, distinct_id, *args, **kwargs):
+ return flag == "marketing-analytics-precomputation" and distinct_id in flagged_uuids
+
+ with (
+ patch.dict(os.environ, {}, clear=False),
+ patch(_IS_CLOUD, return_value=cloud),
+ patch(_FF, side_effect=read_flag) as feature_enabled,
+ ):
+ os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)
+ selected = get_selected_team_ids()
+
+ assert selected == ([flagged.pk] if cloud else [])
+ assert unflagged.pk not in selected
+ # Picking an audience is not a read, so the scan evaluates the read flag alone and records no
+ # exposure. Otherwise every goal team looks exposed to three flags, every hour.
+ assert {call.args[0] for call in feature_enabled.call_args_list} <= {"marketing-analytics-precomputation"}
+ assert all(call.kwargs["send_feature_flag_events"] is False for call in feature_enabled.call_args_list)
+
def test_auto_audience_is_recently_active_teams_with_goals(self):
# The rolling warm set is bounded to the active population: a team must both have a conversion goal
# and have opened marketing analytics recently. A team with goals but no recent activity drops out