: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(marketing-analytics): serve stale precomputes instead of materializing inline (#72060)
Javier Bahamondes5e22f0e5fec5
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex da35391135ba..a0e8e850dbcc 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -34,11 +34,11 @@ from products.actions.backend.models.action import Actionfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,LazyComputationTable,- ensure_precomputed,)from .adapters.factory import MarketingSourceFactoryfrom .marketing_analytics_config import MarketingAnalyticsConfig+from .marketing_lazy_precompute import marketing_ensure_precomputedfrom .metrics import CONVERSION_GOAL_PRECOMPUTE_FALLBACK_COUNTERDAY_IN_SECONDS = 86400@@ -181,7 +181,7 @@ class SharedTouchpointsPrecompute:if self._result is None:window = timedelta(days=self._config.attribution_window_days)self._range = (date_from, date_to)- self._result = ensure_precomputed(+ self._result = marketing_ensure_precomputed(team=self._team,insert_query=build_touchpoints_precompute_query(),time_range_start=date_from - window,@@ -221,6 +221,9 @@ class ConversionGoalProcessor:# processor owns a clone (see HogQLTimings.clone_for_subquery); the runner merges them back once# the pool has joined. Defaults to a standalone instance for callers outside the read path.timings: HogQLTimings = dataclass_field(default_factory=HogQLTimings)+ # Set when this goal's precompute was served from expired-within-grace rows instead of rebuilt. Read+ # by the runner after the goal pool joins, to schedule one background revalidation for the read.+ precompute_stale: bool = False_UTM_LEVEL_FIELD_MAP: ClassVar[dict[MarketingAnalyticsDrillDownLevel, str]] = {MarketingAnalyticsDrillDownLevel.MEDIUM: "medium",@@ -568,7 +571,7 @@ class ConversionGoalProcessor:return Nonewith self.timings.measure("ma_ensure_conversions"):- conversions_result = ensure_precomputed(+ conversions_result = marketing_ensure_precomputed(team=self.team,insert_query=self.build_conversions_precompute_query(),time_range_start=date_from,@@ -579,6 +582,11 @@ class ConversionGoalProcessor:if not conversions_result.ready:return None+ # Either ensure may have been served from expired-within-grace rows rather than rebuilt. The+ # runner collects this once the goal pool has joined and schedules the revalidation.+ if touchpoints_result.stale or conversions_result.stale:+ self.precompute_stale = True+with self.timings.measure("ma_attribution_pipeline_precomputed"):array_collection = self._build_array_collection_from_precomputes(touchpoints_result.job_ids, conversions_result.job_ids, date_from, date_to, windowdiff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.pyindex c3ab3c545a29..2f55b9d40841 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py@@ -1,4 +1,7 @@+import contextvars+from collections.abc import Callablefrom concurrent.futures import ThreadPoolExecutor+from typing import TypeVarfrom posthog.schema import MarketingAnalyticsBaseColumns, MarketingAnalyticsDrillDownLevel@@ -19,6 +22,27 @@ from .marketing_analytics_config import MarketingAnalyticsConfig# case. Bump only after measuring PG/Redis pressure under realistic concurrency._GOAL_PARALLELISM_LIMIT = 8+_T = TypeVar("_T")+_R = TypeVar("_R")+++def _map_in_caller_context(build: Callable[[_T], _R], items: list[_T]) -> list[_R]:+ """`pool.map` each item, but with the caller's contextvars carried into the worker threads.++ `ThreadPoolExecutor` workers don't inherit the submitting thread's contextvars, so the query tags+ (team_id, feature, trigger) set on the read path would be lost inside the pool — silently un-tagging+ every ClickHouse query these goals emit, and breaking serve-stale: a background revalidation tags its+ own ensures CACHE_WARMUP so they skip the grace and actually recompute, and dropping that tag makes+ the revalidation serve itself stale and never refresh. A Context can't be entered concurrently, so+ each worker gets its own copy.+ """+ contexts = [contextvars.copy_context() for _ in items]+ with ThreadPoolExecutor(+ max_workers=min(len(items), _GOAL_PARALLELISM_LIMIT),+ thread_name_prefix="ma_cte",+ ) as pool:+ return list(pool.map(lambda ctx, item: ctx.run(build, item), contexts, items))+class ConversionGoalsAggregator:"""@@ -60,11 +84,7 @@ class ConversionGoalsAggregator:# Skip the pool in TEST: Django's per-thread DB connections don't see# fixtures created in the main test thread.if not TEST and len(self.processors) > 1:- with ThreadPoolExecutor(- max_workers=min(len(self.processors), _GOAL_PARALLELISM_LIMIT),- thread_name_prefix="ma_cte",- ) as pool:- base_queries = list(pool.map(_build_base_query, self.processors))+ base_queries = _map_in_caller_context(_build_base_query, self.processors)else:base_queries = [_build_base_query(p) for p in self.processors]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.pyindex e373a26ffedc..813c5d5e355d 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@@ -29,14 +29,17 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRangefrom posthog.models.team.team import DEFAULT_CURRENCY-from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (- LazyComputationTable,- ensure_precomputed,-)+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationTable+from products.analytics_platform.backend.lazy_computation.stale_policy import is_background_warming_requestfrom products.marketing_analytics.backend.hogql_queries.constants import (DRILL_DOWN_LEVEL_CONFIG,UNIFIED_CONVERSION_GOALS_CTE_ALIAS,)+from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (+ BACKGROUND_WARMING_TRIGGERS,+ handle_stale_served,+ marketing_ensure_precomputed,+)from products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_namefrom .adapters.base import MarketingSourceAdapter, QueryContext@@ -78,6 +81,9 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,self._costs_precompute_used: bool = Falseself._costs_sources_materialized: int = 0self._costs_grain: Optional[str] = None+ # Set when any read-path ensure (costs, touchpoints, conversions) was served from+ # expired-within-grace rows rather than rebuilt inline. Reset on each to_query.+ self._precompute_stale: bool = Falsedef calculate(self) -> ResponseType:start = time.perf_counter()@@ -153,6 +159,13 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,filtering). Built with the runner's user+modifiers so it's valid for resolving the finalquery, not just the factory's warehouse-name lookup."""modifiers = create_default_modifiers_for_team(self.team, self.modifiers)+ # Background materialization (Dagster warmer, stale-while-revalidate task) runs userless, so under+ # warehouse access control a userless database fails closed and hides every warehouse table — the+ # cost adapters then enumerate empty and the ensure never fires, so warehouse-backed costs would+ # never refresh. Bypass access control for these background writers exactly as the warmer does+ # (the materialization INSERT is printed userless either way); user-facing reads keep self.user and+ # the access-controlled path.+ bypass_access_control = is_background_warming_request(BACKGROUND_WARMING_TRIGGERS)# Pass the runner's timings so create_for's internal spans (data_warehouse_tables,# filter_system_tables_for_user, saved queries, revenue views, …) surface in the query's# timings instead of a discarded HogQLTimings — otherwise this whole build shows as an@@ -163,6 +176,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,modifiers=modifiers,timings=self.timings,build_postgres_foreign_keys=False,+ bypass_warehouse_access_control=bypass_access_control,)@cached_property@@ -269,7 +283,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,s3_fallback_adapters.append(adapter)continuewith self.timings.measure("ma_precompute_ensure"):- result = ensure_precomputed(+ result = marketing_ensure_precomputed(team=self.team,insert_query=insert_query,time_range_start=date_range.date_from(),@@ -277,6 +291,8 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,ttl_seconds=ttl_seconds,table=LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,)+ if result.stale:+ self._precompute_stale = Trueif not result.ready:logger.info("marketing_costs_precompute",@@ -855,9 +871,12 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,# For table queries, use the normal conversion goals CTEunified_cte = conversion_aggregator.generate_unified_cte(date_range, self._get_where_conditions)- # The per-goal pool has joined, so folding each processor's cloned timings back in is safe here.+ # The per-goal pool has joined, so folding each processor's cloned timings — and whether its+ # precompute was served stale — back in is safe here.for processor in processors:self.timings.timings.update(processor.timings.timings)+ if processor.precompute_stale:+ self._precompute_stale = Trueif unified_cte:ctes[UNIFIED_CONVERSION_GOALS_CTE_ALIAS] = unified_cte@@ -913,6 +932,10 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,def to_query(self) -> ast.SelectQuery:"""Generate the HogQL query using the new adapter architecture"""with self.timings.measure("marketing_analytics_base_query"):+ # Reset per build. Any read-path ensure served from expired-within-grace rows flips this, and+ # the read schedules exactly one background revalidation once the query is built.+ self._precompute_stale = False+# Apply drill-down level from query to configself._apply_drill_down_level()@@ -958,7 +981,13 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,# Build the complete query with CTEs using ASTwith self.timings.measure("ma_build_complete_query"):- return self._build_complete_query_ast(union_subquery, processors, self.query_date_range)+ query = self._build_complete_query_ast(union_subquery, processors, self.query_date_range)++ # One revalidation per read, not per stale ensure: costs, touchpoints and conversions all expire+ # together, and rebuilding the query refreshes every one of them.+ if self._precompute_stale:+ handle_stale_served(team=self.team, query=self.query)+ return querydef _generate_aggregated_conversion_goals_cte(self, conversion_aggregator, date_range) -> Optional[ast.CTE]:"""Generate aggregated conversion goals CTE without GROUP BY for aggregated queries"""diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.pynew file mode 100644index 000000000000..de2a5d47eb7c--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/marketing_lazy_precompute.py@@ -0,0 +1,206 @@+"""Stale-while-revalidate (RFC 5861) for the marketing analytics read path.++Every precompute the dashboard reads — touchpoints, conversions, costs — is materialized by+`ensure_precomputed`, and when a window is stale that materialization runs *inline*: Postgres, Redis and+a synchronous ClickHouse INSERT, on the request thread. Instrumentation put ~10s of a ~13s dashboard load+there, with ClickHouse itself only ~1.2s.++It is stale on most loads by construction. The today-slice's TTL is 15 minutes+(`PRECOMPUTE_TTL_SECONDS["0d"]`) while the Dagster warmer runs hourly, so for roughly 45 of every 60+minutes a read finds it expired and rebuilds it before answering.++This module is the *serve* half: a user-facing read whose windows expired within the grace gets its+complete-but-stale rows back immediately instead of rebuilding them. `enqueue_stale_revalidation` is the+*revalidate* half: a stale hit schedules a background re-run so the next read is fresh, rather than+leaving freshness to the hourly warmer — which only covers the teams on its allowlist.++Requests that ARE a refresh mechanism must never take the grace: served their own stale rows they would+never recompute, and the data would never refresh again. `resolve_stale_while_revalidate_seconds` gates+that on the CACHE_WARMUP feature tag (which the Dagster warmer already sets) plus the trigger below.+"""++import json+import hashlib+from contextlib import suppress+from typing import Any++import structlog+from prometheus_client import Counter++from posthog import redis+from posthog.clickhouse.query_tagging import tag_queries+from posthog.models import Team+from posthog.ph_client import feature_enabled_or_false++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationResult,+ ensure_precomputed,+)+from products.analytics_platform.backend.lazy_computation.stale_policy import resolve_stale_while_revalidate_seconds++logger = structlog.get_logger(__name__)++# Gates the whole mechanism, so it can be rolled out gradually and killed without a deploy. Off means a+# read materializes inline exactly as it did before this existed — and with no grace the executor never+# reports `stale`, so no revalidation is enqueued either. Fail-safe: `feature_enabled_or_false` returns+# False if flag evaluation breaks, which degrades to that same pre-existing behaviour.+SERVE_STALE_FLAG = "marketing-analytics-serve-stale"++# The trigger the revalidation task runs under. Lives next to the trigger set so the two cannot drift.+REVALIDATION_TRIGGER = "marketingAnalyticsStaleRevalidation"++# Marketing's own refreshers. The Dagster warmer is already caught by the CACHE_WARMUP feature tag it+# sets, so it does not need naming here; this set is the belt for the revalidation task, which would+# otherwise serve itself stale and never recompute.+BACKGROUND_WARMING_TRIGGERS = frozenset({REVALIDATION_TRIGGER})++# How far past expiry a user-facing read may still be served from existing rows. Refresh normally lands+# within minutes via the revalidation task (plus the hourly warmer for allowlisted teams); this grace is+# the ceiling for when both of those fail. Must stay well under the framework's 48h ClickHouse expiry+# buffer, so the underlying rows are guaranteed to still exist.+STALE_WHILE_REVALIDATE_SECONDS = 6 * 60 * 60++# One revalidation per (team, query shape) per window. A dashboard renders several tiles off the same+# query shape and they all go stale together; without this they would each enqueue a rebuild of the same+# windows.+REVALIDATION_DEBOUNCE_SECONDS = 10 * 60++# If the enqueue itself fails (broker blip), hold the debounce slot only this long instead of the full+# window. Long enough not to retry `.delay()` on every stale read during an outage — each failed publish+# adds latency to a user-facing read — short enough that revalidation resumes soon after the broker heals,+# rather than staying suppressed for 10 minutes with no rebuild in flight.+ENQUEUE_FAILURE_BACKOFF_SECONDS = 30++# Fields that shape only the final read, never what gets materialized, so they must not split the debounce+# key — paging or re-sorting a stale table would otherwise enqueue a rebuild per interaction. Kept+# deliberately narrow: excluding a field that *does* select precomputes (`select` gates which conversion+# goals are built) would debounce away a revalidation that was actually needed.+FINAL_READ_ONLY_FIELDS = frozenset({"limit", "offset", "orderBy", "response", "tags", "dataColorTheme"})++MARKETING_PRECOMPUTE_STALE_SERVED = Counter(+ "marketing_analytics_precompute_stale_served_total",+ "Reads served from expired-within-grace jobs instead of materializing inline (stale-while-revalidate).",+)++MARKETING_PRECOMPUTE_REVALIDATION_ENQUEUED = Counter(+ "marketing_analytics_precompute_revalidation_enqueued_total",+ "Background revalidation tasks enqueued after a stale-served read.",+)++MARKETING_PRECOMPUTE_REVALIDATION_ENQUEUE_FAILED = Counter(+ "marketing_analytics_precompute_revalidation_enqueue_failed_total",+ "Revalidation enqueues that failed (e.g. broker unavailable); the stale read is still served.",+)+++def serve_stale_enabled(team: Team) -> bool:+ """Whether this team may be served stale precomputes, cached on the team instance.++ A single dashboard load calls the ensures several times (touchpoints, per-goal conversions, costs,+ plus a previous-period runner when comparing), so caching here keeps it to one evaluation per load+ without leaking across requests — a fresh team is loaded per request. Mirrors the caching the+ precompute flags already do in `MarketingAnalyticsConfig`.++ Test authors: the cache lives on `team._ma_serve_stale_flag`; clear it if you reuse a team across+ cases with different flag mocks.+ """+ cached = getattr(team, "_ma_serve_stale_flag", None)+ if cached is not None:+ return cached+ enabled = feature_enabled_or_false(+ SERVE_STALE_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization.id)},+ group_properties={"organization": {"id": str(team.organization.id)}},+ )+ team._ma_serve_stale_flag = enabled # type: ignore[attr-defined]+ return enabled+++def marketing_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResult:+ """`ensure_precomputed` for the marketing read path, with the product's serve-stale policy applied.++ User-facing calls get the grace; refreshers get none, and so does everyone when the flag is off. Every+ read-path ensure (touchpoints, conversions, costs) must go through here — one left on the raw call+ still blocks the request thread on a stale window, which is the whole problem.+ """+ if "stale_while_revalidate_seconds" not in kwargs:+ kwargs["stale_while_revalidate_seconds"] = (+ resolve_stale_while_revalidate_seconds(STALE_WHILE_REVALIDATE_SECONDS, BACKGROUND_WARMING_TRIGGERS)+ if serve_stale_enabled(team)+ else None+ )+ return ensure_precomputed(team=team, **kwargs)+++def _query_shape_key(query: Any) -> str:+ payload = json.dumps(+ query.model_dump(mode="json", exclude_none=True, exclude=set(FINAL_READ_ONLY_FIELDS)),+ sort_keys=True,+ default=str,+ )+ return hashlib.sha256(payload.encode()).hexdigest()[:16]+++def _scope_to_revalidation(query: Any) -> Any:+ """Drop compare mode so the revalidation rebuilds only the window that actually went stale.++ A compare read runs two independent runners (current + previous), each of which detects its own+ staleness and enqueues its own window. Leaving compare on would make the task re-derive a second,+ un-requested comparison window on top of the one it needs — double the ensure work per task.+ """+ compare_filter = getattr(query, "compareFilter", None)+ if compare_filter is None or not getattr(compare_filter, "compare", False):+ return query+ # Drop the filter entirely rather than just flipping compare off, so a compare read and a plain read+ # of the same window collapse onto one debounce slot instead of scheduling near-identical rebuilds.+ scoped = query.model_copy(deep=True)+ scoped.compareFilter = None+ return scoped+++def enqueue_stale_revalidation(*, team: Team, query: Any) -> None:+ """Schedule a background re-run so the next read of this query shape is fresh.++ Best-effort by design: this runs on the user-facing read path, before the stale rows are read, so a+ Redis or broker outage must degrade to "serve stale, warmer converges" and never fail the read.+ """+ # The task module imports this one for the trigger, so the reverse import stays local.+ from products.marketing_analytics.backend.tasks.lazy_precompute_revalidation import ( # noqa: PLC0415+ revalidate_marketing_analytics_precompute,+ )++ query = _scope_to_revalidation(query)+ claimed = False+ debounce_key: str | None = None+ try:+ debounce_key = f"ma_swr_reval:{team.id}:{_query_shape_key(query)}"+ claimed = bool(redis.get_client().set(debounce_key, "1", ex=REVALIDATION_DEBOUNCE_SECONDS, nx=True))+ if not claimed:+ return+ revalidate_marketing_analytics_precompute.delay(+ team_id=team.id, query=query.model_dump(mode="json", exclude_none=True)+ )+ except Exception:+ # We may have claimed the debounce slot before the enqueue failed. Shrink it to a brief backoff so+ # the next stale read retries soon, rather than being suppressed for the full window with no+ # rebuild in flight — while not retrying on every read during a broker outage.+ if claimed and debounce_key is not None:+ with suppress(Exception):+ redis.get_client().set(debounce_key, "1", ex=ENQUEUE_FAILURE_BACKOFF_SECONDS)+ MARKETING_PRECOMPUTE_REVALIDATION_ENQUEUE_FAILED.inc()+ logger.warning("marketing_precompute.swr_revalidation_enqueue_failed", team_id=team.id, exc_info=True)+ return+ MARKETING_PRECOMPUTE_REVALIDATION_ENQUEUED.inc()+ logger.info("marketing_precompute.swr_revalidation_enqueued", team_id=team.id)+++def handle_stale_served(*, team: Team, query: Any) -> None:+ """Everything the read path does once any of its ensures came back stale.++ Counts it, tags the upcoming read so query_log can separate stale-served from fresh reads, and+ enqueues the background revalidation.+ """+ MARKETING_PRECOMPUTE_STALE_SERVED.inc()+ tag_queries(precompute_stale=True)+ enqueue_stale_revalidation(team=team, query=query)diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.pyindex 067b5d5f9c98..b90de5a0f070 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py@@ -7,6 +7,8 @@ import pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import patch+from django.test import SimpleTestCase+from posthog.schema import (BaseMathType,ConversionGoalFilter1,@@ -21,6 +23,7 @@ from posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.clickhouse.client.execute import sync_executefrom posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL+from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset_query_tags, tag_queriesfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.actions.backend.models.action import Action@@ -31,7 +34,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execufrom products.analytics_platform.backend.models.preaggregation_job import PreaggregationJobfrom .conversion_goal_processor import ConversionGoalProcessor, SharedTouchpointsPrecompute-from .conversion_goals_aggregator import ConversionGoalsAggregator+from .conversion_goals_aggregator import ConversionGoalsAggregator, _map_in_caller_contextfrom .marketing_analytics_config import MarketingAnalyticsConfig@@ -637,7 +640,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):aggregator = ConversionGoalsAggregator(processors, self.config)with patch(- "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.ensure_precomputed",+ "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.marketing_ensure_precomputed",side_effect=lambda **kwargs: LazyComputationResult(ready=True, job_ids=[uuid.uuid4()]),) as ensure:aggregator.generate_unified_cte(self.date_range, self._create_mock_additional_conditions_getter())@@ -656,7 +659,7 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):date_to = datetime(2024, 1, 31, tzinfo=UTC)with patch(- "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.ensure_precomputed",+ "products.marketing_analytics.backend.hogql_queries.conversion_goal_processor.marketing_ensure_precomputed",side_effect=lambda **kwargs: LazyComputationResult(ready=True, job_ids=[uuid.uuid4()]),) as ensure:first = shared.get(date_from, date_to)@@ -666,3 +669,29 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):shared.get(date_from, date_to + timedelta(days=1))assert ensure.call_count == 1+++class TestGoalParallelismContextPropagation(SimpleTestCase):+ def tearDown(self):+ reset_query_tags()+ super().tearDown()++ def test_query_tags_survive_into_the_goal_worker_threads(self):+ # Multi-goal reads build each goal's precompute in a thread pool. ThreadPoolExecutor workers do+ # not inherit the caller's contextvars, so a bare pool.map drops the query tags — and with them+ # the CACHE_WARMUP tag a background revalidation sets on itself, which is the only thing stopping+ # that revalidation from serving itself stale and never refreshing. Guards that regression.+ tag_queries(feature=Feature.CACHE_WARMUP, trigger="marketingAnalyticsStaleRevalidation")+ seen: dict[int, tuple] = {}++ def build(item: int) -> int:+ seen[item] = (get_query_tag_value("feature"), get_query_tag_value("trigger"))+ return item * 10++ # 3 items > 1 forces the real pool rather than the serial path.+ result = _map_in_caller_context(build, [1, 2, 3])++ assert result == [10, 20, 30]+ assert all(tags == (Feature.CACHE_WARMUP, "marketingAnalyticsStaleRevalidation") for tags in seen.values()), (+ seen+ )diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.pyindex 9e8e0a41782c..6ba18880235a 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py@@ -21,6 +21,7 @@ from posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_in_tests+from posthog.clickhouse.query_tagging import Feature, reset_query_tags, tags_contextfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.marketing_analytics.backend.hogql_queries.adapters.base import MarketingSourceAdapter@@ -28,8 +29,11 @@ from products.marketing_analytics.backend.hogql_queries.constants import DEFAULTfrom 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_TRIGGERfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable+_BASE_RUNNER = "products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner"+class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):"""@@ -52,6 +56,10 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):properties=[],)+ def tearDown(self):+ reset_query_tags()+ super().tearDown()+def _create_query_runner(self, query: MarketingAnalyticsTableQuery | None = None) -> MarketingAnalyticsTableQueryRunner:@@ -60,6 +68,27 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):query = self.default_queryreturn MarketingAnalyticsTableQueryRunner(query=query, team=self.team)+ @parameterized.expand(+ [+ # A user-facing read is access-controlled; only background writers bypass. Getting this wrong+ # either freezes warehouse-backed costs for access-control teams (no bypass on the userless+ # revalidation) or leaks tables into a user read (bypass when it shouldn't).+ ("user_facing", None, False),+ ("dagster_warmer", {"feature": Feature.CACHE_WARMUP}, True),+ ("revalidation_task", {"trigger": REVALIDATION_TRIGGER}, True),+ ]+ )+ @patch(f"{_BASE_RUNNER}.Database.create_for")+ def test_background_warming_bypasses_warehouse_access_control(self, _name, tags, expected_bypass, create_for):+ runner = self._create_query_runner() # no user — mirrors the background task's userless runner+ if tags is None:+ _ = runner._shared_hogql_database+ else:+ with tags_context(**tags):+ _ = runner._shared_hogql_database++ assert create_for.call_args.kwargs["bypass_warehouse_access_control"] is expected_bypass+def _create_mock_adapter(self, name: str, validation_result: bool = True) -> Mock:"""Create a mock adapter for testing"""mock_adapter = Mock(spec=MarketingSourceAdapter)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.pyindex 1e85a7d8b0c0..a074358e1e42 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@@ -248,7 +248,7 @@ class TestMarketingCostsPrecompute(ClickhouseTestMixin, BaseTest):patch.object(MarketingSourceFactory, "create_adapters", lambda self: [good, bad]),patch.object(MarketingSourceFactory, "get_valid_adapters", lambda self, adapters: adapters),patch(- "products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner.ensure_precomputed",+ "products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner.marketing_ensure_precomputed",return_value=ready,),):diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.pynew file mode 100644index 000000000000..3204886fc040--- /dev/null+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_lazy_precompute.py@@ -0,0 +1,163 @@+from posthog.test.base import BaseTest+from unittest import mock++from parameterized import parameterized++from posthog.schema import CompareFilter, DateRange, MarketingAnalyticsTableQuery++from posthog import redis+from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset_query_tags, tags_context++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult+from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import (+ ENQUEUE_FAILURE_BACKOFF_SECONDS,+ REVALIDATION_TRIGGER,+ STALE_WHILE_REVALIDATE_SECONDS,+ _query_shape_key,+ handle_stale_served,+ marketing_ensure_precomputed,+)++_MODULE = "products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute"+_DELAY = (+ "products.marketing_analytics.backend.tasks.lazy_precompute_revalidation"+ ".revalidate_marketing_analytics_precompute.delay"+)+++class TestMarketingLazyPrecompute(BaseTest):+ def setUp(self):+ super().setUp()+ self.query = MarketingAnalyticsTableQuery(dateRange=DateRange(date_from="-7d"), properties=[])+ redis.get_client().delete(f"ma_swr_reval:{self.team.id}:{_query_shape_key(self.query)}")+ reset_query_tags()+ # Flag on by default here; the flag's own behaviour is covered by test_flag_gates_serve_stale.+ # Cached on the team instance, so it must be cleared between cases that mock it differently.+ self.team._ma_serve_stale_flag = True # type: ignore[attr-defined]++ def tearDown(self):+ reset_query_tags()+ super().tearDown()++ @parameterized.expand(+ [+ ("user_facing", None),+ # The Dagster warmer, which tags CACHE_WARMUP. Served its own stale rows it would persist+ # them as fresh and never rebuild, and marketing data would stop refreshing entirely.+ ("dagster_warmer", {"feature": Feature.CACHE_WARMUP}),+ ("revalidation_task", {"trigger": REVALIDATION_TRIGGER, "feature": Feature.CACHE_WARMUP}),+ # Belt: should the feature tag ever be clobbered before the ensure (web hit exactly this),+ # the trigger alone must still classify the revalidation task as a refresher.+ ("revalidation_task_feature_clobbered", {"trigger": REVALIDATION_TRIGGER, "feature": Feature.QUERY}),+ ]+ )+ @mock.patch(f"{_MODULE}.ensure_precomputed")+ def test_serve_stale_grace_by_caller(self, _name, tags, mock_ensure):+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])+ if tags is None:+ marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)+ else:+ with tags_context(**tags):+ marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)++ grace = mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"]+ if tags is None:+ assert grace == STALE_WHILE_REVALIDATE_SECONDS+ else:+ assert grace is None, f"refresher {tags} must not be served stale"++ @parameterized.expand([("flag_on", True, STALE_WHILE_REVALIDATE_SECONDS), ("flag_off", False, None)])+ @mock.patch(f"{_MODULE}.ensure_precomputed")+ @mock.patch(f"{_MODULE}.feature_enabled_or_false")+ def test_flag_gates_serve_stale(self, _name, flag, expected_grace, flag_eval, mock_ensure):+ # The kill switch. Off must hand the executor no grace at all, so the read materializes inline+ # exactly as it did before serve-stale existed (and, getting no `stale`, enqueues no revalidation).+ del self.team._ma_serve_stale_flag # type: ignore[attr-defined]+ flag_eval.return_value = flag+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])++ marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)++ assert mock_ensure.call_args.kwargs["stale_while_revalidate_seconds"] == expected_grace++ @mock.patch(f"{_MODULE}.ensure_precomputed")+ @mock.patch(f"{_MODULE}.feature_enabled_or_false")+ def test_flag_is_evaluated_once_per_team_across_the_reads_ensures(self, flag_eval, mock_ensure):+ # One load fires this several times (touchpoints, per-goal conversions, costs); each evaluation+ # would otherwise be a flag call plus a $feature_flag_called event on the read path.+ del self.team._ma_serve_stale_flag # type: ignore[attr-defined]+ flag_eval.return_value = True+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])++ for _ in range(4):+ marketing_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)++ assert flag_eval.call_count == 1++ @mock.patch(_DELAY)+ def test_handle_stale_served_tags_read_and_debounces_same_shape(self, delay):+ # A dashboard renders several tiles off one query shape and they go stale together. Each stale+ # ensure must tag the read, but they must collapse to a single background rebuild.+ for _ in range(3):+ handle_stale_served(team=self.team, query=self.query)++ assert get_query_tag_value("precompute_stale") is True+ assert delay.call_count == 1+ payload = delay.call_args.kwargs+ assert payload["team_id"] == self.team.pk+ assert payload["query"]["kind"] == "MarketingAnalyticsTableQuery"++ @parameterized.expand(+ [+ # Paging or re-sorting a stale table is a normal interaction; each one must not buy its own+ # rebuild of the exact same windows.+ ("pagination", {"limit": 500, "offset": 100}, 1),+ ("sort", {"orderBy": [["cost", "DESC"]]}, 1),+ # `select` gates which conversion goals get built, and a different window is different data.+ ("select", {"select": ["campaign", "cost"]}, 2),+ ("date_range", {"dateRange": DateRange(date_from="-30d")}, 2),+ # Compare is stripped before revalidation (it drives a separate runner + window), so toggling+ # it collapses onto the same rebuild rather than buying a second one.+ ("compare_toggle", {"compareFilter": CompareFilter(compare=True)}, 1),+ ]+ )+ @mock.patch(_DELAY)+ def test_debounce_splits_only_on_precompute_identity(self, _name, overrides, expected_enqueues, delay):+ variant = self.query.model_copy(update=overrides)+ redis.get_client().delete(f"ma_swr_reval:{self.team.id}:{_query_shape_key(variant)}")++ handle_stale_served(team=self.team, query=self.query)+ handle_stale_served(team=self.team, query=variant)++ assert delay.call_count == expected_enqueues++ @mock.patch(_DELAY)+ @mock.patch(f"{_MODULE}.redis.get_client", side_effect=Exception("redis down"))+ def test_enqueue_failure_still_serves_the_stale_read(self, _redis, delay):+ # The enqueue runs on the user-facing read path. A Redis or broker outage must degrade to+ # "serve stale, warmer converges" — never raise into the read and force the slow live fallback.+ handle_stale_served(team=self.team, query=self.query)++ assert delay.call_count == 0+ assert get_query_tag_value("precompute_stale") is True++ @mock.patch(_DELAY, side_effect=Exception("broker down"))+ def test_broker_failure_shrinks_the_debounce_slot_to_a_backoff(self, _delay):+ # The slot is claimed before the enqueue is confirmed. If the enqueue fails, holding it the full+ # window would suppress every retry for 10 minutes with no rebuild in flight — release it to a+ # short backoff so revalidation resumes soon after the broker recovers.+ key = f"ma_swr_reval:{self.team.id}:{_query_shape_key(self.query)}"++ handle_stale_served(team=self.team, query=self.query)++ assert 0 < redis.get_client().ttl(key) <= ENQUEUE_FAILURE_BACKOFF_SECONDS++ @mock.patch(_DELAY)+ def test_compare_is_stripped_from_the_revalidation_query(self, delay):+ # A compare read runs a separate previous-period runner that revalidates its own window; leaving+ # compare on would make the task re-derive a second, un-requested comparison window.+ query = self.query.model_copy(update={"compareFilter": CompareFilter(compare=True)})++ handle_stale_served(team=self.team, query=query)++ assert "compareFilter" not in delay.call_args.kwargs["query"]diff --git a/products/marketing_analytics/backend/tasks/__init__.py b/products/marketing_analytics/backend/tasks/__init__.pynew file mode 100644index 000000000000..7d6f94011876--- /dev/null+++ b/products/marketing_analytics/backend/tasks/__init__.py@@ -0,0 +1,3 @@+from . import lazy_precompute_revalidation++__all__ = ["lazy_precompute_revalidation"]diff --git a/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.py b/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.pynew file mode 100644index 000000000000..d9d7da42221a--- /dev/null+++ b/products/marketing_analytics/backend/tasks/lazy_precompute_revalidation.py@@ -0,0 +1,107 @@+"""Background revalidation for stale-served marketing analytics reads.++The revalidate half of stale-while-revalidate (RFC 5861). When a user-facing read is served from+expired-within-grace jobs, the read path enqueues this task (see+`marketing_lazy_precompute.enqueue_stale_revalidation`) to re-run the query in the background, so the+next fetch is fresh instead of waiting on the hourly Dagster warmer — which only covers the teams on its+allowlist, so for everyone else this task is the *only* refresh mechanism.++Building the query via `to_query()`, rather than driving each `ensure_precomputed` by hand, is+deliberate: it fires exactly the ensures the read fires (touchpoints, conversions, costs), so the two+cannot drift apart. We build but do NOT execute the query — see the warehouse-access note on the+`to_query()` call for why executing would be a data-access leak.++Duplicate tasks are tolerated rather than deduped: the framework's PENDING-job unique index collapses+concurrent recomputes to one insert, and once the first task has refreshed the windows the rest are cheap+warm reads on a queue that paces ClickHouse work anyway.+"""++import time++import structlog+from celery import shared_task+from prometheus_client import Counter++from posthog.hogql.constants import LimitContext++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.hogql_queries.query_runner import get_query_runner+from posthog.models import Team+from posthog.scoping_audit import skip_team_scope_audit+from posthog.tasks.utils import CeleryQueue++from products.marketing_analytics.backend.hogql_queries.marketing_lazy_precompute import REVALIDATION_TRIGGER++logger = structlog.get_logger(__name__)++REVALIDATION_RUN = Counter(+ "marketing_analytics_precompute_revalidation_total",+ "Background stale-while-revalidate re-runs of marketing analytics queries.",+ labelnames=["outcome", "query_kind"],+)++# A cold rebuild drives touchpoints, per-goal conversions and per-source costs, each with the framework's+# 180s wait budget, plus the read itself. Mirrors the web analytics revalidation task's limits.+REVALIDATION_SOFT_TIME_LIMIT = 600+REVALIDATION_TIME_LIMIT = REVALIDATION_SOFT_TIME_LIMIT + 30++# Discard tasks that sat in the queue this long: by then a sibling task, the warmer, or a newer stale hit+# has already covered it. The queue's shedding valve against enqueue bursts on a hot shape.+REVALIDATION_EXPIRES_SECONDS = 15 * 60+++@shared_task(+ ignore_result=True,+ # Same queue insight cache warming uses — keeps ClickHouse from being overwhelmed.+ queue=CeleryQueue.ANALYTICS_LIMITED.value,+ expires=REVALIDATION_EXPIRES_SECONDS,+ # No retries: the next stale hit re-enqueues, and the warmer converges regardless.+ max_retries=0,+ soft_time_limit=REVALIDATION_SOFT_TIME_LIMIT,+ time_limit=REVALIDATION_TIME_LIMIT,+)+@skip_team_scope_audit+def revalidate_marketing_analytics_precompute(team_id: int, query: dict) -> None:+ query_kind = str(query.get("kind"))+ try:+ team = Team.objects.get(pk=team_id)+ except Team.DoesNotExist:+ logger.warning("marketing_analytics_swr_revalidation_team_missing", team_id=team_id, query_kind=query_kind)+ REVALIDATION_RUN.labels(outcome="failed", query_kind=query_kind).inc()+ return++ logger.info("marketing_analytics_swr_revalidation_started", team_id=team_id, query_kind=query_kind)+ 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.+ tag_queries(+ team_id=team_id,+ trigger=REVALIDATION_TRIGGER,+ feature=Feature.CACHE_WARMUP,+ product=Product.MARKETING_ANALYTICS,+ )+ runner = get_query_runner(query=query, team=team, limit_context=LimitContext.QUERY_ASYNC)+ # Build the query only — do NOT execute it. to_query() drives every read-path ensure (touchpoints,+ # conversions, costs), rebuilding the expired precompute windows, which is the whole job. We stop+ # short of executing because this runner is userless with warehouse access control bypassed (so it+ # can materialize every source's costs): a full run would write that all-sources aggregated+ # response into the per-team result cache, which a user without access to some of those warehouse+ # sources could then read. Leaving the result cache alone, the next user read recomputes the+ # response under its own access — now over hot precomputes — and caches it correctly.+ runner.to_query()+ except Exception:+ logger.exception("marketing_analytics_swr_revalidation_failed", team_id=team_id, query_kind=query_kind)+ REVALIDATION_RUN.labels(outcome="failed", query_kind=query_kind).inc()+ return++ REVALIDATION_RUN.labels(outcome="succeeded", query_kind=query_kind).inc()+ logger.info(+ "marketing_analytics_swr_revalidation_finished",+ team_id=team_id,+ query_kind=query_kind,+ duration_seconds=round(time.monotonic() - started, 3),+ )diff --git a/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.py b/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.pynew file mode 100644index 000000000000..b29b32cb5b60--- /dev/null+++ b/products/marketing_analytics/backend/tasks/test_lazy_precompute_revalidation.py@@ -0,0 +1,62 @@+from posthog.test.base import BaseTest+from unittest import mock++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.marketing_analytics.backend.tasks.lazy_precompute_revalidation import (+ revalidate_marketing_analytics_precompute,+)++_MODULE = "products.marketing_analytics.backend.tasks.lazy_precompute_revalidation"+++class TestMarketingLazyPrecomputeRevalidation(BaseTest):+ def setUp(self):+ super().setUp()+ self.query = MarketingAnalyticsTableQuery(dateRange=DateRange(date_from="-7d"), properties=[]).model_dump(+ mode="json", exclude_none=True+ )+ reset_query_tags()++ def tearDown(self):+ reset_query_tags()+ super().tearDown()++ @mock.patch(f"{_MODULE}.get_query_runner")+ def test_materializes_precomputes_as_a_refresher_without_executing(self, get_runner):+ # The tags must already be set while the runner is built, since its construction-time ensures read+ # them. Classified as a refresher it gets no serve-stale grace — served its own stale rows it would+ # never recompute and marketing data would stop refreshing.+ # 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 = {}+ runner = mock.MagicMock()++ def capture(**_kwargs):+ 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}+ runner.to_query.assert_called_once_with()+ runner.run.assert_not_called()++ @mock.patch(f"{_MODULE}.get_query_runner")+ def test_deleted_team_does_not_raise_into_the_worker(self, get_runner):+ revalidate_marketing_analytics_precompute(team_id=self.team.pk + 10_000, query=self.query)++ assert get_runner.call_count == 0++ @mock.patch(f"{_MODULE}.get_query_runner", side_effect=Exception("clickhouse down"))+ def test_query_failure_is_swallowed(self, _get_runner):+ # Best-effort by design: the next stale hit re-enqueues and the warmer converges, so a failure here+ # must not surface as a task error.+ revalidate_marketing_analytics_precompute(team_id=self.team.pk, query=self.query)