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(endpoints): materialization conditions and reason for rejection (#61344)

Jovan Sakovic0fa854a17a22
diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
index 4c08424d649d..4d81dc6a2021 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
@@ -736,7 +736,7 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
LEFT JOIN
- (SELECT person.id AS id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email
+ (SELECT person.id AS id, nullIf(nullIf(person.pmat_email, ''), 'null') AS properties___email
FROM person
WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
(SELECT person.id AS id, max(person.version) AS version
@@ -1122,7 +1122,7 @@
WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,
(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id
FROM events
- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))
+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))
GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')
HAVING 1
ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESC
diff --git a/products/endpoints/backend/materialization.py b/products/endpoints/backend/materialization.py
index dca275099e34..82df60b0c1f1 100644
--- a/products/endpoints/backend/materialization.py
+++ b/products/endpoints/backend/materialization.py
@@ -337,6 +337,29 @@ def analyze_variables_for_materialization(
continue
downstream = _downstream_ctes(graph, var.cte_name)
propagating = downstream | {var.cte_name}
+
+ # Propagation adds a column + GROUP BY to propagating CTEs, breaking any
+ # top-level scalar usage of them (`WHERE x = (SELECT col FROM cte)` ends up
+ # returning N rows × 2 cols). No correct rewrite exists — ClickHouse doesn't
+ # support correlated subqueries. Hide the outer WITH so the finder doesn't
+ # treat propagating CTEs as shadowed by their own definitions.
+ original_ctes = ast_node.ctes
+ ast_node.ctes = None
+ try:
+ has_unsafe_reference = _body_has_non_top_from_propagating_reference(ast_node, propagating)
+ finally:
+ ast_node.ctes = original_ctes
+ if has_unsafe_reference:
+ return (
+ False,
+ (
+ "Scalar subquery in top-level query references a CTE downstream of "
+ "the variable-carrying CTE; the transformer cannot rewrite it to "
+ "carry the variable column. Move the reference to the top-level FROM."
+ ),
+ [],
+ )
+
plans: dict[str, DownstreamCTEPlan] = {}
for d_cte_name in _topological_order(graph, downstream):
d_cte = ast_node.ctes[d_cte_name]
@@ -1228,7 +1251,7 @@ class MaterializationTransformer(CloningVisitor):
else:
node.select = select_additions
- if node.group_by is not None or self._current_cte_name is None:
+ if node.group_by is not None or self._has_aggregate_functions(node):
self._add_group_by(node, vars_for_context)
if node.where:
diff --git a/products/endpoints/backend/tests/__snapshots__/test_variable_materialization.ambr b/products/endpoints/backend/tests/__snapshots__/test_variable_materialization.ambr
index 1415b9317df6..78e3f5f6dd01 100644
--- a/products/endpoints/backend/tests/__snapshots__/test_variable_materialization.ambr
+++ b/products/endpoints/backend/tests/__snapshots__/test_variable_materialization.ambr
@@ -153,8 +153,6 @@
event AS event_name
FROM
cte
- GROUP BY
- event
LIMIT 50000
'''
# ---
diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.py
index f06794e3705b..d43dfd2f7253 100644
--- a/products/endpoints/backend/tests/test_variable_materialization.py
+++ b/products/endpoints/backend/tests/test_variable_materialization.py
@@ -2789,3 +2789,52 @@ class TestDownstreamTransformSnapshots(APIBaseTest):
)
== self.snapshot
)
+
+
+class TestMaterializationAnalyzerGaps(APIBaseTest):
+ def test_top_level_scalar_subquery_consuming_propagating_cte_rejected(self):
+ query = {
+ "kind": "HogQLQuery",
+ "query": (
+ "WITH org_events AS ("
+ " SELECT timestamp, distinct_id FROM events WHERE event = {variables.event_name}"
+ "), latest_ts AS ("
+ " SELECT max(timestamp) AS ts FROM org_events"
+ ") "
+ "SELECT distinct_id FROM org_events "
+ "WHERE timestamp = (SELECT ts FROM latest_ts)"
+ ),
+ "variables": {
+ "var-1": {"variableId": "var-1", "code_name": "event_name", "value": "$pageview"},
+ },
+ }
+
+ can_materialize, reason, _ = analyze_variables_for_materialization(query)
+
+ assert can_materialize is False, (
+ f"Expected rejection — scalar subquery in top-level query consumes a propagating "
+ f"CTE, which the transformer can't rewrite to a per-variable-value form. "
+ f"Got reason={reason!r}."
+ )
+ assert "subquery" in reason.lower() or "scalar" in reason.lower(), (
+ f"Rejection reason should mention the scalar-subquery pattern. Got: {reason!r}"
+ )
+
+ def test_top_level_variable_does_not_force_group_by_on_non_aggregate_select(self):
+ query = {
+ "kind": "HogQLQuery",
+ "query": "SELECT distinct_id, event, timestamp FROM events WHERE event = {variables.event_name}",
+ "variables": {
+ "var-1": {"variableId": "var-1", "code_name": "event_name", "value": "$pageview"},
+ },
+ }
+
+ _, _, var_infos = analyze_variables_for_materialization(query)
+ transformed = transform_query_for_materialization(query, var_infos, self.team)
+ transformed_sql = transformed["query"]
+
+ assert "GROUP BY" not in transformed_sql.upper(), (
+ "Transformer must not add GROUP BY for a non-aggregating top-level SELECT — "
+ "doing so makes the other projected columns invalid (not aggregated, not grouped). "
+ f"Got:\n{transformed_sql}"
+ )