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): fix conversion goal precompute materialization (#60585)

Javier Bahamondesd5d0109004b2
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index 3b34693079ea..000ef61959a5 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -23,6 +23,7 @@ from posthog.hogql.constants import HogQLQuerySettings, get_default_hogql_global
from posthog.hogql.context import HogQLContext
from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_select
+from posthog.hogql.placeholders import replace_placeholders
from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client import sync_execute
@@ -985,7 +986,7 @@ class LazyComputationExecutor:
def ensure_precomputed(
team: Team,
- insert_query: str,
+ insert_query: str | ast.SelectQuery,
time_range_start: datetime,
time_range_end: datetime,
ttl_seconds: int | dict[str, int] = DEFAULT_TTL_SECONDS,
@@ -1014,8 +1015,9 @@ def ensure_precomputed(
Args:
team: The team to create lazy-computed data for
- insert_query: A SELECT query string with placeholders. Use {time_window_min}
- and {time_window_max} for time filtering.
+ insert_query: A SELECT query, either a string template with {time_window_min} /
+ {time_window_max} placeholders, or a prebuilt SelectQuery AST using
+ ast.Placeholder nodes for those names.
time_range_start: Start of the overall time range (inclusive)
time_range_end: End of the overall time range (exclusive)
ttl_seconds: How long before the data expires. Either:
@@ -1082,8 +1084,7 @@ def ensure_precomputed(
"time_window_max": ast.Constant(value="__TIME_WINDOW_MAX__"),
**caller_sentinels,
}
- parsed_for_hash = parse_select(insert_query, placeholders=hash_placeholders)
- assert isinstance(parsed_for_hash, ast.SelectQuery)
+ parsed_for_hash = _resolve_insert_query(insert_query, hash_placeholders)
query_info = QueryInfo(
query=parsed_for_hash,
@@ -1115,10 +1116,25 @@ def ensure_precomputed(
return executor.execute(team, query_info, time_range_start, time_range_end, run_insert=_run_manual_insert)
+def _resolve_insert_query(insert_query: str | ast.SelectQuery, placeholders: dict[str, ast.Expr]) -> ast.SelectQuery:
+ """Resolve an insert query into a SelectQuery AST with its placeholders filled.
+
+ String callers (web analytics, experiments) carry `{time_window_min/max}` as text; AST callers
+ (conversion goals) carry `ast.Placeholder` nodes. `parse_select` substitutes placeholders via the
+ same `replace_placeholders`, so both inputs resolve identically.
+ """
+ if isinstance(insert_query, str):
+ resolved: ast.Expr = parse_select(insert_query, placeholders=placeholders)
+ else:
+ resolved = replace_placeholders(insert_query, placeholders)
+ assert isinstance(resolved, ast.SelectQuery)
+ return resolved
+
+
def _build_manual_insert_sql(
team: Team,
job: PreaggregationJob,
- insert_query: str,
+ insert_query: str | ast.SelectQuery,
table: LazyComputationTable,
base_placeholders: dict[str, ast.Expr] | None = None,
) -> tuple[str, dict]:
@@ -1141,9 +1157,8 @@ def _build_manual_insert_sql(
"time_window_max": ast.Constant(value=job.time_range_end),
}
- # Parse the query with all placeholders — returns a fresh AST we can mutate
- query = parse_select(insert_query, placeholders=all_placeholders)
- assert isinstance(query, ast.SelectQuery)
+ # Resolve the query with all placeholders — returns a fresh AST we can mutate
+ query = _resolve_insert_query(insert_query, all_placeholders)
assert query.select is not None, "SelectQuery must have select expressions"
# Add team_id as the first column
diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
index 3d31d7077646..24758ede0fdf 100644
--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py
@@ -1,9 +1,8 @@
-import re
import math
import uuid
from collections.abc import Sequence
from dataclasses import dataclass
-from datetime import UTC, datetime
+from datetime import datetime
from typing import ClassVar, Optional, Union
import structlog
@@ -21,7 +20,6 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.database.schema.channel_type import ChannelTypeExprs, create_channel_type_expr
from posthog.hogql.modifiers import create_default_modifiers_for_team
-from posthog.hogql.printer import to_printed_hogql
from posthog.hogql.property import action_to_expr, property_to_expr
from posthog.models import PropertyDefinition, Team, User
@@ -40,10 +38,6 @@ LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) *
# This follows the industry standard (Google Analytics, Adobe, Mixpanel all use 7-day half-life).
TIME_DECAY_HALF_LIFE_DIVISOR = 4
-# Sentinel datetimes swapped for {time_window_min/max} placeholders after HogQL printing.
-_PRECOMPUTE_TIME_WINDOW_MIN_SENTINEL = datetime(2099, 12, 31, 23, 59, 58, 123456, tzinfo=UTC)
-_PRECOMPUTE_TIME_WINDOW_MAX_SENTINEL = datetime(2099, 12, 31, 23, 59, 59, 654321, tzinfo=UTC)
-
logger = structlog.get_logger(__name__)
@@ -371,11 +365,11 @@ class ConversionGoalProcessor:
ensure_precomputed,
)
- query_string, placeholders = self.get_attributed_query_for_precomputation()
+ insert_select = self.get_attributed_query_for_precomputation()
result = ensure_precomputed(
team=self.team,
- insert_query=query_string,
+ insert_query=insert_select,
time_range_start=date_from,
time_range_end=date_to,
ttl_seconds={
@@ -385,7 +379,6 @@ class ConversionGoalProcessor:
"default": 7 * 24 * 60 * 60,
},
table=LazyComputationTable.CONVERSION_GOAL_ATTRIBUTED_PREAGGREGATED,
- placeholders=placeholders,
)
if not result.ready:
@@ -397,12 +390,12 @@ class ConversionGoalProcessor:
date_to=date_to,
)
- def get_attributed_query_for_precomputation(self) -> tuple[str, dict[str, ast.Expr]]:
- """Build the INSERT template that materialises one job's pre-attributed rows.
+ def get_attributed_query_for_precomputation(self) -> ast.SelectQuery:
+ """Build the INSERT SELECT AST that materialises one job's pre-attributed rows.
- Uses {time_window_min}/{time_window_max} placeholders resolved by the framework.
- Single-touch emits weight=1.0; multi-touch emits N rows per conversion with
- fractional weights that sum to 1.
+ The time window is left as ``time_window_min``/``time_window_max`` placeholders that the lazy
+ framework resolves per job. Single-touch emits weight=1.0; multi-touch emits N rows per
+ conversion with fractional weights that sum to 1.
"""
if self.goal.kind not in ("EventsNode", "ActionsNode"):
raise NotImplementedError(f"Precompute is not supported for goal kind {self.goal.kind!r}")
@@ -415,12 +408,12 @@ class ConversionGoalProcessor:
ast.CompareOperation(
left=ast.Field(chain=["events", "timestamp"]),
op=ast.CompareOperationOp.GtEq,
- right=ast.Constant(value=_PRECOMPUTE_TIME_WINDOW_MIN_SENTINEL),
+ right=ast.Placeholder(expr=ast.Field(chain=["time_window_min"])),
),
ast.CompareOperation(
left=ast.Field(chain=["events", "timestamp"]),
op=ast.CompareOperationOp.LtEq,
- right=ast.Constant(value=_PRECOMPUTE_TIME_WINDOW_MAX_SENTINEL),
+ right=ast.Placeholder(expr=ast.Field(chain=["time_window_max"])),
),
]
array_collection = self.build_array_collection_query(additional_conditions)
@@ -428,24 +421,9 @@ class ConversionGoalProcessor:
attribution_window_seconds = self.config.attribution_window_days * DAY_IN_SECONDS
if self.config.is_multi_touch:
array_join = self._build_multi_touch_array_join_subquery(array_collection, attribution_window_seconds)
- insert_select = self._build_multi_touch_attribution_subquery(array_join, for_precompute=True)
- else:
- array_join = self._build_single_touch_array_join_subquery(array_collection, attribution_window_seconds)
- insert_select = self._build_single_touch_attribution_subquery(array_join, for_precompute=True)
-
- printed = to_printed_hogql(insert_select, team=self.team)
- for sentinel, placeholder in (
- (_PRECOMPUTE_TIME_WINDOW_MIN_SENTINEL, "{time_window_min}"),
- (_PRECOMPUTE_TIME_WINDOW_MAX_SENTINEL, "{time_window_max}"),
- ):
- printed = _replace_sentinel_datetime(printed, sentinel, placeholder)
-
- if _PRECOMPUTE_SENTINEL_LITERAL_RE.search(printed):
- raise RuntimeError(
- "Failed to substitute precompute time-window sentinels — printer format may have changed"
- )
-
- return printed, {}
+ return self._build_multi_touch_attribution_subquery(array_join, for_precompute=True)
+ array_join = self._build_single_touch_array_join_subquery(array_collection, attribution_window_seconds)
+ return self._build_single_touch_attribution_subquery(array_join, for_precompute=True)
def build_attributed_source_from_precomputed(
self,
@@ -2088,16 +2066,6 @@ class ConversionGoalProcessor:
return False
-# Matches both HogQL toDateTime and ClickHouse toDateTime64 forms.
-_PRECOMPUTE_SENTINEL_LITERAL_RE = re.compile(r"toDateTime(?:64)?\(\s*'2099-12-31 23:59:5[89]\.\d+'")
-
-
-def _replace_sentinel_datetime(printed: str, sentinel: datetime, replacement: str) -> str:
- literal = re.escape(sentinel.strftime("%Y-%m-%d %H:%M:%S.%f"))
- pattern = re.compile(rf"toDateTime(?:64)?\(\s*'{literal}'(?:\s*,\s*6(?:\s*,\s*'[^']+')?)?\s*\)")
- return pattern.sub(replacement, printed)
-
-
def add_conversion_goal_property_filters(
conditions: list[ast.Expr],
conversion_goal: ConversionGoalFilter1 | ConversionGoalFilter2 | ConversionGoalFilter3,
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
index 3eb89e0ed8a9..c0d7c52df453 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_precompute_e2e.py
@@ -215,6 +215,36 @@ class TestConversionGoalPrecomputeEquivalence(ClickhouseTestMixin, APIBaseTest):
f"{attribution_mode}: precompute diverged from direct path.\ndirect: {direct_rows}\npreagg: {preagg_rows}"
)
+ @parameterized.expand(
+ [
+ (AttributionMode.LAST_TOUCH,),
+ (AttributionMode.FIRST_TOUCH,),
+ (AttributionMode.LINEAR,),
+ (AttributionMode.TIME_DECAY,),
+ (AttributionMode.POSITION_BASED,),
+ ]
+ )
+ def test_precompute_matches_direct_in_non_utc_timezone(self, attribution_mode: AttributionMode):
+ self.team.timezone = "US/Pacific"
+ self.team.save()
+ self._seed_events()
+
+ date_from = datetime(2025, 1, 1, tzinfo=UTC)
+ date_to = datetime(2025, 1, 31, tzinfo=UTC)
+
+ direct_processor = self._make_processor(precompute=False, attribution_mode=attribution_mode)
+ direct_rows = sorted(self._execute(direct_processor.generate_cte_query(additional_conditions=[])))
+
+ preagg_processor = self._make_processor(precompute=True, attribution_mode=attribution_mode)
+ preagg_rows = sorted(
+ self._execute(
+ preagg_processor.generate_cte_query(additional_conditions=[], date_from=date_from, date_to=date_to)
+ )
+ )
+
+ assert preagg_rows, f"{attribution_mode}: precompute returned no rows for a non-UTC team"
+ assert _round_rows(direct_rows) == _round_rows(preagg_rows)
+
def _round_rows(rows: list[tuple]) -> list[tuple]:
"""Round floats to avoid weight-multiplication rounding noise between paths."""
diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
index 76928c133183..780665191c07 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor_refactor.py
@@ -18,7 +18,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
-from posthog.hogql.parser import parse_select
+from posthog.hogql.placeholders import find_placeholders, replace_placeholders
from posthog.hogql.printer import prepare_and_print_ast, to_printed_hogql
from posthog.hogql.test.utils import pretty_print_in_tests
@@ -56,6 +56,19 @@ def _make_data_warehouse_goal() -> ConversionGoalFilter3:
)
+def _resolve_precompute_select(select_ast: ast.SelectQuery) -> ast.SelectQuery:
+ """Resolve the time-window placeholders the way the lazy framework does per job."""
+ resolved = replace_placeholders(
+ select_ast,
+ {
+ "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),
+ "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),
+ },
+ )
+ assert isinstance(resolved, ast.SelectQuery)
+ return resolved
+
+
class TestConversionGoalProcessorRefactor(BaseTest):
"""Tests for the public refactor surface.
@@ -159,32 +172,21 @@ class TestConversionGoalProcessorRefactor(BaseTest):
assert first.get_precompute_hash_inputs() != last.get_precompute_hash_inputs()
- def test_precompute_template_contains_time_window_placeholders(self):
+ def test_precompute_query_exposes_time_window_placeholders(self):
processor = self._processor()
- template, _ = processor.get_attributed_query_for_precomputation()
- assert "{time_window_min}" in template
- assert "{time_window_max}" in template
+ select_ast = processor.get_attributed_query_for_precomputation()
+ placeholder_fields = find_placeholders(select_ast).placeholder_fields
+ assert ["time_window_min"] in placeholder_fields
+ assert ["time_window_max"] in placeholder_fields
- def test_precompute_template_parses_with_framework_placeholders(self):
+ def test_precompute_query_resolves_with_framework_placeholders(self):
processor = self._processor()
- template, custom_placeholders = processor.get_attributed_query_for_precomputation()
- placeholders = {
- **custom_placeholders,
- "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),
- "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),
- }
- parsed = parse_select(template, placeholders=placeholders)
- assert isinstance(parsed, ast.SelectQuery)
+ resolved = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())
+ assert isinstance(resolved, ast.SelectQuery)
- def test_precompute_template_matches_preagg_table_columns(self):
+ def test_precompute_query_matches_preagg_table_columns(self):
processor = self._processor()
- template, _ = processor.get_attributed_query_for_precomputation()
- placeholders: dict[str, ast.Expr] = {
- "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),
- "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),
- }
- write_template = parse_select(template, placeholders=placeholders)
- assert isinstance(write_template, ast.SelectQuery)
+ write_template = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())
aliases = [e.alias for e in write_template.select if isinstance(e, ast.Alias)]
for col in write_template.select:
assert isinstance(col, ast.Alias), f"SELECT column not aliased: {col}"
@@ -229,16 +231,10 @@ class TestConversionGoalProcessorRefactor(BaseTest):
with patch(target, return_value={"utm_source"}):
assert processor._should_use_precompute(date_from, date_to) is False
- def test_precompute_template_supports_multi_touch(self):
+ def test_precompute_query_supports_multi_touch(self):
processor = self._processor()
processor.config.attribution_mode = AttributionMode.LINEAR
- template, _ = processor.get_attributed_query_for_precomputation()
- placeholders: dict[str, ast.Expr] = {
- "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),
- "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),
- }
- parsed = parse_select(template, placeholders=placeholders)
- assert isinstance(parsed, ast.SelectQuery)
+ parsed = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())
aliases = [e.alias for e in parsed.select if isinstance(e, ast.Alias)]
assert "touchpoint_weight" in aliases
assert "touchpoint_timestamp" in aliases
@@ -284,12 +280,7 @@ class TestConversionGoalProcessorRefactor(BaseTest):
@pytest.mark.usefixtures("unittest_snapshot")
def test_precompute_insert_template_sql_snapshot(self):
processor = self._processor()
- template, _ = processor.get_attributed_query_for_precomputation()
- placeholders: dict[str, ast.Expr] = {
- "time_window_min": ast.Constant(value=datetime(2025, 1, 1, tzinfo=UTC)),
- "time_window_max": ast.Constant(value=datetime(2025, 1, 2, tzinfo=UTC)),
- }
- parsed = parse_select(template, placeholders=placeholders)
+ parsed = _resolve_precompute_select(processor.get_attributed_query_for_precomputation())
assert pretty_print_in_tests(to_printed_hogql(parsed, team=self.team), self.team.pk) == self.snapshot
@pytest.mark.usefixtures("unittest_snapshot")