: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(hogql): record skipped range rewrites on string materialized columns (#63216)
George Munyoro31c5d3c88e6c
diff --git a/posthog/hogql/observability.py b/posthog/hogql/observability.pyindex a50881a873df..12f8e1d63525 100644--- a/posthog/hogql/observability.py+++ b/posthog/hogql/observability.py@@ -96,6 +96,7 @@ MATERIALIZED_PROPERTY_USAGE_TOTAL = PromCounter(MATERIALIZED_RANGE_REWRITE_TOTAL = PromCounter("hogql_materialized_range_rewrite_total","Range comparisons on materialized property columns by rewrite outcome. "+ "'fired_compare' rewrote to a bare column comparison; 'fired_if_null' rewrote with an isNotNull(col) guard; ""'skipped' means a materialized source was identified but the bare (minmax-eligible) rewrite was unsafe.",labelnames=[*_BASE_LABELS, "result"],)diff --git a/posthog/hogql/test/test_property_skip_indexes.py b/posthog/hogql/test/test_property_skip_indexes.pyindex e08e99b35b79..718e2ba375ba 100644--- a/posthog/hogql/test/test_property_skip_indexes.py+++ b/posthog/hogql/test/test_property_skip_indexes.py@@ -752,7 +752,8 @@ class TestEventPropertySkipIndexes(_PropertySkipIndexTestBase):with patch("posthog.hogql.printer.utils.create_hogql_type_observability", return_value=stats):self._filter_to_sql(self._filter(PropertyOperator.LT, "5"))- assert stats.materialized_range_rewrite["fired_compare"] >= 1+ # The column is nullable, so the bare comparison is guarded by isNotNull(col): a "fired_if_null" outcome.+ assert stats.materialized_range_rewrite["fired_if_null"] >= 1assert stats.materialized_property_usage["materialized_column"] >= 1def test_observability_records_json_property_usage(self) -> None:diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pyindex 8dffd8bca325..76ec20dcdf90 100644--- a/posthog/hogql/transforms/clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -393,11 +393,16 @@ _OPTIMIZER_COMPATIBLE_COMPARISONS = {}+# The fired subset of the range-rewrite outcomes (`_RANGE_REWRITE_RESULTS` in observability.py). Kept explicit so a+# future outcome label opts into the usage side effect below deliberately rather than via a name prefix.+_FIRED_RANGE_REWRITE_RESULTS = frozenset({"fired_compare", "fired_if_null"})++def _record_range_rewrite(context: HogQLContext, result: str) -> None:if context.type_observability is None:returncontext.type_observability.record_materialized_range_rewrite(result)- if result.startswith("fired"):+ if result in _FIRED_RANGE_REWRITE_RESULTS:# A fired rewrite reads the materialized column directly, bypassing the value-substitution path that normally# accounts for the materialized access, so record the usage here.context.type_observability.record_materialized_property_usage("materialized_column")@@ -836,7 +841,7 @@ class ClickHousePropertyResolver(CloningVisitor):cmp = _call(op_name, [prop.bare_column(), _const(node.right.value)])if prop.source.is_nullable:- _record_range_rewrite(self.context, "fired_compare")+ _record_range_rewrite(self.context, "fired_if_null")return _call("and", [cmp, prop.is_not_null()])# Non-nullable: exclude the '' / 'null' sentinels inline so the bare comparison stays index-eligible._record_range_rewrite(self.context, "fired_compare")@@ -859,7 +864,13 @@ class ClickHousePropertyResolver(CloningVisitor):return Nonefield_type, property_name = singlesource = resolve_materialized_property_source(field_type, property_name, self.context)- if source is None or source.kind != "materialized_column" or _is_string_column(source):+ if source is None:+ return None # no backing column — not a rewrite candidate, nothing to record+ if source.kind != "materialized_column" or _is_string_column(source):+ # The backing column stores the value as a string (string mat column, dmat, or property-group map), where a+ # bare range comparison would order lexicographically — unsafe, so the rewrite is skipped. This is the+ # common shape: numeric/datetime properties materialize to string columns unless a typed column was created.+ _record_range_rewrite(self.context, "skipped")return Nonephysical = _column_constant_type(source)@@ -897,7 +908,7 @@ class ClickHousePropertyResolver(CloningVisitor):column = _OptimizableProperty(field_type=field_type, key=property_name, source=source)cmp = _call(op_name, [column.bare_column(), right_expr])- _record_range_rewrite(self.context, "fired_compare")+ _record_range_rewrite(self.context, "fired_if_null") # always nullable here, so the rewrite is null-guardedreturn _call("and", [cmp, column.is_not_null()])def _operand_semantic_type(self, expr: ast.Expr) -> ast.ConstantType | None:diff --git a/posthog/hogql/transforms/test/test_range_rewrite_observability.py b/posthog/hogql/transforms/test/test_range_rewrite_observability.pynew file mode 100644index 000000000000..27748267dfa7--- /dev/null+++ b/posthog/hogql/transforms/test/test_range_rewrite_observability.py@@ -0,0 +1,147 @@+"""Integration coverage for the materialized-range-rewrite observability counter.++These run the real ClickHouse property-resolution transform (not the record_* hooks in isolation) so they pin the+counter to the query shapes that reach it. The accumulator is injected in place of the sampling draw. The dominant+production shape — a numeric/datetime property range filter, which materializes to a string column — must record+"skipped"; before the fix it recorded nothing, which is why the counter never emitted.+"""++from posthog.test.base import APIBaseTest, ClickhouseTestMixin, cleanup_materialized_columns+from unittest.mock import patch++from parameterized import parameterized+from prometheus_client import REGISTRY++from posthog.schema import HogQLQueryModifiers, MaterializationMode++from posthog.hogql.context import HogQLContext+from posthog.hogql.observability import HogQLTypeObservability+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_and_print_ast++from posthog.models import PropertyDefinition++from products.event_definitions.backend.models.property_definition import PropertyType++from ee.clickhouse.materialized_columns.columns import materialize+++class TestMaterializedRangeRewriteObservability(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ cleanup_materialized_columns()+ self.addCleanup(cleanup_materialized_columns)++ def _range_rewrite_counts(+ self,+ sql: str,+ *,+ property_name: str,+ property_type: PropertyType | None,+ materialized: bool = True,+ column_type: str | None = None,+ is_nullable: bool = True,+ ) -> dict[str, int]:+ """Run the full prepare+print pass over `sql` and return what the range-rewrite counter recorded."""+ if materialized:+ materialize(+ "events",+ property_name,+ column_name=f"mat_{property_name}",+ is_nullable=is_nullable,+ column_type=column_type,+ )+ if property_type is not None:+ PropertyDefinition.objects.get_or_create(+ team=self.team,+ project_id=self.team.project_id,+ name=property_name,+ type=PropertyDefinition.Type.EVENT,+ defaults={"property_type": property_type},+ )+ context = HogQLContext(+ team_id=self.team.pk,+ team=self.team,+ enable_select_queries=True,+ modifiers=HogQLQueryModifiers(materializationMode=MaterializationMode.AUTO),+ )+ # Inject the accumulator in place of the sampling draw; the pass's finally-block emit also flushes it to+ # Prometheus, so every test here exercises the full record → emit flow.+ stats = HogQLTypeObservability(dialect="clickhouse", source="probe")+ with patch("posthog.hogql.printer.utils.create_hogql_type_observability", return_value=stats):+ prepare_and_print_ast(parse_select(sql), context, "clickhouse")+ return dict(stats.materialized_range_rewrite)++ @parameterized.expand(+ [+ ("numeric", "SELECT count() FROM events WHERE properties.revenue > 10", "revenue", PropertyType.Numeric),+ (+ "datetime",+ "SELECT count() FROM events WHERE properties.signup_at > '2024-01-01'",+ "signup_at",+ PropertyType.Datetime,+ ),+ ]+ )+ def test_range_over_string_column_records_skipped(+ self, _name: str, sql: str, property_name: str, property_type: PropertyType+ ) -> None:+ # The regression guard: a numeric/datetime property range filter materializes to a string column, the bare+ # range rewrite is unsafe (lexicographic), so it is "skipped" — not silently dropped, which left the counter+ # empty.+ counts = self._range_rewrite_counts(sql, property_name=property_name, property_type=property_type)+ self.assertEqual(counts, {"skipped": 1})++ def test_range_over_typed_nullable_column_records_fired_if_null(self):+ # A typed (non-string) nullable materialized column can be compared bare with a null guard.+ counts = self._range_rewrite_counts(+ "SELECT count() FROM events WHERE properties.revenue > 10",+ property_name="revenue",+ column_type="Nullable(Float64)",+ property_type=PropertyType.Numeric,+ )+ self.assertEqual(counts, {"fired_if_null": 1})++ def test_range_over_non_nullable_string_column_records_fired_compare(self):+ # A string/untyped property over a non-nullable string materialized column rewrites bare (sentinels excluded+ # inline), so it fires without a null guard.+ counts = self._range_rewrite_counts(+ "SELECT count() FROM events WHERE properties.untyped_tag > 'abc'",+ property_name="untyped_tag",+ is_nullable=False,+ property_type=None,+ )+ self.assertEqual(counts, {"fired_compare": 1})++ def test_range_over_unmaterialized_property_records_nothing(self):+ # No backing column: not a materialized range comparison, so the counter must stay untouched.+ counts = self._range_rewrite_counts(+ "SELECT count() FROM events WHERE properties.not_materialized > 10",+ property_name="not_materialized",+ property_type=PropertyType.Numeric,+ materialized=False,+ )+ self.assertEqual(counts, {})++ def test_skipped_outcome_flows_through_to_prometheus(self):+ labels = {"engine": "current", "dialect": "clickhouse", "source": "probe", "result": "skipped"}+ before = REGISTRY.get_sample_value("hogql_materialized_range_rewrite_total", labels) or 0.0++ self._range_rewrite_counts(+ "SELECT count() FROM events WHERE properties.revenue > 10",+ property_name="revenue",+ property_type=PropertyType.Numeric,+ )++ after = REGISTRY.get_sample_value("hogql_materialized_range_rewrite_total", labels) or 0.0+ self.assertEqual(after - before, 1)++ def test_every_range_operator_records(self):+ # All four range operators in one WHERE: each comparison reaches the optimizer and records independently.+ counts = self._range_rewrite_counts(+ "SELECT count() FROM events WHERE properties.revenue < 10 AND properties.revenue <= 10"+ " AND properties.revenue > 10 AND properties.revenue >= 10",+ property_name="revenue",+ property_type=PropertyType.Numeric,+ )+ self.assertEqual(counts, {"skipped": 4})