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.

refactor(hogql): preload materialized-column map into the property-metadata bundle (#72271)

George Munyorodc636f5f7eb3
diff --git a/posthog/clickhouse/materialized_column_types.py b/posthog/clickhouse/materialized_column_types.py
new file mode 100644
index 000000000000..391563da056c
--- /dev/null
+++ b/posthog/clickhouse/materialized_column_types.py
@@ -0,0 +1,30 @@
+"""Materialized-column types and constants the HogQL engine can import without booting Django.
+
+The Django-side lookups (instance settings, the EE column cache) live in
+posthog.clickhouse.materialized_columns, which re-exports these names for existing callers.
+"""
+
+from typing import Protocol
+
+from posthog.property_columns import TableWithProperties
+
+ColumnName = str
+TablesWithMaterializedColumns = TableWithProperties
+MATERIALIZATION_VALID_TABLES: frozenset[TablesWithMaterializedColumns] = frozenset({"events", "person", "groups"})
+
+DMAT_STRING_COLUMN_NAME_PREFIX = "dmat_string_"
+# Naming prefixes for physical materialized columns; mat_/pmat_ are minted by
+# _materialized_column_name in ee/clickhouse/materialized_columns/columns.py.
+MATERIALIZED_COLUMN_NAME_PREFIXES = ("mat_", "pmat_", DMAT_STRING_COLUMN_NAME_PREFIX)
+
+
+class MaterializedColumn(Protocol):
+ name: ColumnName
+ is_nullable: bool
+ has_minmax_index: bool
+ has_bloom_filter_index: bool
+ has_ngram_lower_index: bool
+ has_bloom_filter_lower_index: bool
+
+ @property
+ def type(self) -> str: ...
diff --git a/posthog/clickhouse/materialized_columns.py b/posthog/clickhouse/materialized_columns.py
index e48d2e5055c0..fb5dacce9a1a 100644
--- a/posthog/clickhouse/materialized_columns.py
+++ b/posthog/clickhouse/materialized_columns.py
@@ -1,30 +1,29 @@
-from typing import Protocol
-
+from collections.abc import Mapping
+
+from posthog.clickhouse.materialized_column_types import (
+ DMAT_STRING_COLUMN_NAME_PREFIX,
+ MATERIALIZATION_VALID_TABLES,
+ MATERIALIZED_COLUMN_NAME_PREFIXES,
+ ColumnName,
+ MaterializedColumn,
+ TablesWithMaterializedColumns,
+)
from posthog.models.instance_setting import get_instance_setting
-from posthog.models.property import PropertyName, TableColumn, TableWithProperties
+from posthog.models.property import PropertyName, TableColumn
+from posthog.property_columns import TableWithProperties
from posthog.settings import EE_AVAILABLE
-ColumnName = str
-TablesWithMaterializedColumns = TableWithProperties
-MATERIALIZATION_VALID_TABLES: frozenset[TablesWithMaterializedColumns] = frozenset({"events", "person", "groups"})
-
-DMAT_STRING_COLUMN_NAME_PREFIX = "dmat_string_"
-# Naming prefixes for physical materialized columns; mat_/pmat_ are minted by
-# _materialized_column_name in ee/clickhouse/materialized_columns/columns.py.
-MATERIALIZED_COLUMN_NAME_PREFIXES = ("mat_", "pmat_", DMAT_STRING_COLUMN_NAME_PREFIX)
-
-
-class MaterializedColumn(Protocol):
- name: ColumnName
- is_nullable: bool
- has_minmax_index: bool
- has_bloom_filter_index: bool
- has_ngram_lower_index: bool
- has_bloom_filter_lower_index: bool
-
- @property
- def type(self) -> str: ...
-
+__all__ = [
+ "DMAT_STRING_COLUMN_NAME_PREFIX",
+ "MATERIALIZATION_VALID_TABLES",
+ "MATERIALIZED_COLUMN_NAME_PREFIXES",
+ "ColumnName",
+ "MaterializedColumn",
+ "TableWithProperties",
+ "TablesWithMaterializedColumns",
+ "get_enabled_materialized_columns_by_table",
+ "get_materialized_column_for_property",
+]
if EE_AVAILABLE:
from ee.clickhouse.materialized_columns.columns import get_enabled_materialized_columns
@@ -36,9 +35,28 @@ if EE_AVAILABLE:
return None
return get_enabled_materialized_columns(table).get((property_name, table_column))
+
+ def get_enabled_materialized_columns_by_table() -> Mapping[
+ TablesWithMaterializedColumns, Mapping[tuple[PropertyName, TableColumn], MaterializedColumn]
+ ]:
+ """Enabled materialized columns for every materialization-valid table, or empty when disabled.
+
+ Registry fetch behind the HogQL property-metadata bundle: memoized per query and invoked
+ lazily on the first materialized-column lookup, so the engine's lookups are pure map reads
+ and property-free compiles issue no registry queries (see PropertyMetadata's docstring).
+ """
+ if not get_instance_setting("MATERIALIZED_COLUMNS_ENABLED"):
+ return {}
+
+ return {table: get_enabled_materialized_columns(table) for table in MATERIALIZATION_VALID_TABLES}
else:
def get_materialized_column_for_property(
table: TablesWithMaterializedColumns, table_column: TableColumn, property_name: PropertyName
) -> MaterializedColumn | None:
return None
+
+ def get_enabled_materialized_columns_by_table() -> Mapping[
+ TablesWithMaterializedColumns, Mapping[tuple[PropertyName, TableColumn], MaterializedColumn]
+ ]:
+ return {}
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index f8f6580ee642..5089a765212f 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -3142,29 +3142,30 @@ class TestPrinter(BaseTest):
"hogql_val_8": "Bool",
}
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
- def test_ai_trace_id_optimizations(self, mock_get_mat_col):
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_ai_trace_id_optimizations(self, mock_matcols_by_table):
"""Test that $ai_trace_id uses the active storage path without wrappers that block skip indexes."""
+ from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
+
+ # The column is in the registry either way; JSON-backed event properties must ignore it.
+ mat_col = MaterializedColumn(
+ name="mat_$ai_trace_id",
+ details=MaterializedColumnDetails(
+ table_column="properties", property_name="$ai_trace_id", is_disabled=False
+ ),
+ is_nullable=True,
+ )
+ mock_matcols_by_table.return_value = {"events": {("$ai_trace_id", "properties"): mat_col}}
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.side_effect = AssertionError(
- "JSON-backed event properties should not use materialized columns"
- )
expected_expr = "events.properties.`$ai_trace_id`"
else:
- from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
-
- mock_get_mat_col.return_value = MaterializedColumn(
- name="mat_$ai_trace_id",
- details=MaterializedColumnDetails(
- table_column="properties", property_name="$ai_trace_id", is_disabled=False
- ),
- is_nullable=True,
- )
expected_expr = "events.`mat_$ai_trace_id`"
context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
sql = self._select("SELECT * FROM events WHERE properties.$ai_trace_id = 'trace123'", context)
+ if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
+ self.assertNotIn("mat_$ai_trace_id", sql)
# Find the placeholder that holds our value (index varies with number of joins)
trace_param_key = next((k for k, v in context.values.items() if v == "trace123"), None)
@@ -3204,10 +3205,7 @@ class TestPrinter(BaseTest):
self.assertNotIn("ifNull(notIn", sql)
# Dynamic properties use JSON subcolumns under the new schema and JSON extraction under legacy.
- if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.assert_not_called()
- else:
- mock_get_mat_col.return_value = None
+ # `other_prop` is not in the materialized-column registry, so it stays on the JSON path.
context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
sql = self._select("SELECT * FROM events WHERE properties.other_prop = 'value'", context)
@@ -3218,7 +3216,6 @@ class TestPrinter(BaseTest):
other_prop_expr = self._json_dynamic_property_expr("other_prop")
self.assertIn(f"ifNull(equals({other_prop_expr}, %({value_param_key})s), 0)", sql)
self.assertNotIn("JSONExtractRaw(events.properties,", sql)
- mock_get_mat_col.assert_not_called()
else:
other_prop_param_key = next((k for k, v in context.values.items() if v == "other_prop"), None)
assert other_prop_param_key is not None, "Expected 'other_prop' to be recorded as a parameter value"
@@ -3227,25 +3224,24 @@ class TestPrinter(BaseTest):
sql,
)
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
- def test_ai_session_id_optimizations(self, mock_get_mat_col):
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_ai_session_id_optimizations(self, mock_matcols_by_table):
"""Test that $ai_session_id uses the active storage path without wrappers that block skip indexes."""
+ from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
+
+ # The column is in the registry either way; JSON-backed event properties must ignore it.
+ mat_col = MaterializedColumn(
+ name="mat_$ai_session_id",
+ details=MaterializedColumnDetails(
+ table_column="properties", property_name="$ai_session_id", is_disabled=False
+ ),
+ is_nullable=True,
+ )
+ mock_matcols_by_table.return_value = {"events": {("$ai_session_id", "properties"): mat_col}}
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.side_effect = AssertionError(
- "JSON-backed event properties should not use materialized columns"
- )
expected_expr = "events.properties.`$ai_session_id`"
else:
- from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
-
- mock_get_mat_col.return_value = MaterializedColumn(
- name="mat_$ai_session_id",
- details=MaterializedColumnDetails(
- table_column="properties", property_name="$ai_session_id", is_disabled=False
- ),
- is_nullable=True,
- )
expected_expr = "events.`mat_$ai_session_id`"
context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
@@ -3276,57 +3272,53 @@ class TestPrinter(BaseTest):
self.assertIn(f"in({expected_expr}, tuple(%({session1_param_key})s, %({session2_param_key})s))", sql)
self.assertNotIn("ifNull(in", sql)
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.assert_not_called()
+ self.assertNotIn("mat_$ai_session_id", sql)
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
- def test_materialized_property_through_column_aliased_table(self, mock_get_mat_col):
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_materialized_property_through_column_aliased_table(self, mock_matcols_by_table):
# A property read through a column-renamed table (`FROM events AS e (...)`, a ColumnAliasedTableType) must still
# resolve to the active storage path. Property resolution has to unwrap that table type to reach the real table; if
# it doesn't, the read silently falls back to a slow JSONExtract over the raw blob.
- if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.side_effect = AssertionError(
- "JSON-backed event properties should not use materialized columns"
- )
- else:
- from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
+ from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
- mock_get_mat_col.return_value = MaterializedColumn(
- name="mat_foo",
- details=MaterializedColumnDetails(table_column="properties", property_name="foo", is_disabled=False),
- is_nullable=False,
- )
+ # The column is in the registry either way; JSON-backed event properties must ignore it.
+ mat_col = MaterializedColumn(
+ name="mat_foo",
+ details=MaterializedColumnDetails(table_column="properties", property_name="foo", is_disabled=False),
+ is_nullable=False,
+ )
+ mock_matcols_by_table.return_value = {"events": {("foo", "properties"): mat_col}}
context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
sql = self._select("SELECT e.properties.foo FROM events AS e (a, b)", context)
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
self.assertIn(self._json_dynamic_property_expr("foo", "e"), sql)
self.assertIn("FROM events_json AS e", sql)
self.assertNotIn("mat_foo", sql)
- mock_get_mat_col.assert_not_called()
else:
self.assertIn("mat_foo", sql)
self.assertNotIn("JSONExtractRaw(events.properties", sql)
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
- def test_deep_key_materialized_read_prints_shared_json_extract_shape(self, mock_get_mat_col):
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_deep_key_materialized_read_prints_shared_json_extract_shape(self, mock_matcols_by_table):
# Legacy materialized columns store the first key as a raw JSON string, so deeper reads must extract the tail
# keys with the same SQL shape as ingest and backfill. JSON subcolumns can address the full string-key path
# directly.
from posthog.clickhouse.kafka_engine import json_extract_trim_quotes
+ from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
+
+ # The column is in the registry either way; JSON-backed event properties must ignore it.
+ mat_col = MaterializedColumn(
+ name="mat_foo",
+ details=MaterializedColumnDetails(table_column="properties", property_name="foo", is_disabled=False),
+ is_nullable=False,
+ )
+ mock_matcols_by_table.return_value = {"events": {("foo", "properties"): mat_col}}
+
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.side_effect = AssertionError(
- "JSON-backed event properties should not use materialized columns"
- )
expected = self._json_dynamic_subcolumn_path_expr("events.properties", ["foo", "bar"])
expected_values = {}
else:
- from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
-
- mock_get_mat_col.return_value = MaterializedColumn(
- name="mat_foo",
- details=MaterializedColumnDetails(table_column="properties", property_name="foo", is_disabled=False),
- is_nullable=False,
- )
head = "nullIf(nullIf(events.mat_foo, ''), 'null')"
expected = json_extract_trim_quotes(head, "%(hogql_val_0)s")
expected_values = {"hogql_val_0": "bar"}
@@ -3335,7 +3327,7 @@ class TestPrinter(BaseTest):
self.assertEqual(printed, expected)
self.assertEqual(context.values, expected_values)
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
- mock_get_mat_col.assert_not_called()
+ self.assertNotIn("mat_foo", printed)
def _print_constant(self, node: ast.Constant) -> str:
return print_prepared_ast(
@@ -5387,11 +5379,8 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
assert f"less(parseDateTime64BestEffortOrNull(events.{mat_col.name}," in printed
assert f"less(events.{mat_col.name}," not in printed
- @patch("posthog.hogql.property_planner.get_materialized_column_for_property")
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
- def test_materialized_column_range_comparison_uses_typed_numeric_source(
- self, mock_resolution_get_mat_col, mock_planner_get_mat_col
- ) -> None:
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_materialized_column_range_comparison_uses_typed_numeric_source(self, mock_matcols_by_table) -> None:
from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
PropertyDefinition.objects.create(
@@ -5410,8 +5399,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
column_type="Nullable(Float64)",
has_minmax_index=True,
)
- mock_resolution_get_mat_col.return_value = mock_mat_col
- mock_planner_get_mat_col.return_value = mock_mat_col
+ mock_matcols_by_table.return_value = {"events": {("numeric_test_prop", "properties"): mock_mat_col}}
printed = self._expr("properties.numeric_test_prop < 5")
@@ -5424,11 +5412,8 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
assert "mat_numeric_test_prop" in printed
assert "accurateCastOrNull" not in printed
- @patch("posthog.hogql.property_planner.get_materialized_column_for_property")
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
- def test_materialized_column_range_comparison_uses_typed_datetime_source(
- self, mock_resolution_get_mat_col, mock_planner_get_mat_col
- ) -> None:
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_materialized_column_range_comparison_uses_typed_datetime_source(self, mock_matcols_by_table) -> None:
from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
PropertyDefinition.objects.create(
@@ -5447,8 +5432,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
column_type="Nullable(DateTime64(6, 'UTC'))",
has_minmax_index=True,
)
- mock_resolution_get_mat_col.return_value = mock_mat_col
- mock_planner_get_mat_col.return_value = mock_mat_col
+ mock_matcols_by_table.return_value = {"events": {("datetime_test_prop", "properties"): mock_mat_col}}
printed = self._expr("properties.datetime_test_prop < '2024-01-15'")
@@ -5462,10 +5446,9 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
assert "toDateTime64(" in printed
assert "parseDateTime64BestEffortOrNull" not in printed
- @patch("posthog.hogql.property_planner.get_materialized_column_for_property")
- @patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
def test_materialized_column_range_comparison_skips_non_nullable_numeric_source(
- self, mock_resolution_get_mat_col, mock_planner_get_mat_col
+ self, mock_matcols_by_table
) -> None:
from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
@@ -5485,8 +5468,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
column_type="Float64",
has_minmax_index=True,
)
- mock_resolution_get_mat_col.return_value = mock_mat_col
- mock_planner_get_mat_col.return_value = mock_mat_col
+ mock_matcols_by_table.return_value = {"events": {("numeric_test_prop", "properties"): mock_mat_col}}
printed = self._expr("properties.numeric_test_prop < 5")
@@ -6442,13 +6424,13 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
else:
assert printed == f"nullIf(nullIf(events.{mat_col.name}, ''), 'null')"
- @patch("posthog.hogql.transforms.property_types.get_materialized_column_for_property")
- def test_jsonextractstring_not_rewritten_for_non_string_mat_column(self, mock_get_mat_col) -> None:
+ @patch("posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table")
+ def test_jsonextractstring_not_rewritten_for_non_string_mat_column(self, mock_matcols_by_table) -> None:
from ee.clickhouse.materialized_columns.columns import MaterializedColumn, MaterializedColumnDetails
# JSONExtractString has string semantics, so a numeric-typed materialized column must not be
# substituted for it — that would emit a bare Float64 column where a string is expected.
- mock_get_mat_col.return_value = MaterializedColumn(
+ mat_col = MaterializedColumn(
name="mat_numeric_prop",
details=MaterializedColumnDetails(
table_column="properties", property_name="numeric_prop", is_disabled=False
@@ -6457,6 +6439,7 @@ class TestMaterializedColumnOptimization(ClickhouseTestMixin, APIBaseTest):
column_type="Nullable(Float64)",
has_minmax_index=True,
)
+ mock_matcols_by_table.return_value = {"events": {("numeric_prop", "properties"): mat_col}}
printed = self._expr("JSONExtractString(properties, 'numeric_prop')")
assert "mat_numeric_prop" not in printed
diff --git a/posthog/hogql/property_metadata.py b/posthog/hogql/property_metadata.py
index f9bb4ecea3fc..6b34834ad496 100644
--- a/posthog/hogql/property_metadata.py
+++ b/posthog/hogql/property_metadata.py
@@ -5,24 +5,57 @@ Django-side loader. The ORM reads stay behind the function call (the `Database.c
pattern), so this module imports without booting Django (no settings or app registry).
"""
+from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING
+from functools import cache
+from typing import TYPE_CHECKING, cast
+
+from posthog.clickhouse.materialized_column_types import (
+ MATERIALIZATION_VALID_TABLES,
+ MaterializedColumn,
+ TablesWithMaterializedColumns,
+)
+from posthog.property_columns import PropertyName, TableColumn
if TYPE_CHECKING:
from posthog.hogql.context import HogQLContext
+MaterializedColumnsByTable = Mapping[
+ TablesWithMaterializedColumns, Mapping[tuple[PropertyName, TableColumn], MaterializedColumn]
+]
+
+
+def _no_materialized_columns() -> MaterializedColumnsByTable:
+ return {}
+
@dataclass(frozen=True)
class PropertyMetadata:
- """Property-definition types for the properties a query touches.
+ """Property-definition types for the properties a query touches, plus the enabled
+ materialized-column registry.
- Values are `{"type": <PropertyType value>}` dicts, plus a `"dmat"` key when a READY
+ Property values are `{"type": <PropertyType value>}` dicts, plus a `"dmat"` key when a READY
materialized-column slot backs an event property. Group keys are `"{group_type_index}_{name}"`.
+ `materialized_columns` is a loader for the instance-wide enabled-column registry (keyed by
+ table name then `(property_name, table_column)`), memoized per bundle by the Django-side
+ builder. It MUST stay lazy: it is invoked only on the first lookup against a
+ materialization-valid table, so queries that never resolve a property (SELECT 1, logs/spans
+ attribute reads, bare-blob selects) never touch the registry — assertNumQueries and
+ query_log-ordering tests depend on those compiles issuing zero registry queries.
"""
event_properties: dict[str, dict[str, str | None]] = field(default_factory=dict)
person_properties: dict[str, dict[str, str | None]] = field(default_factory=dict)
group_properties: dict[str, dict[str, str | None]] = field(default_factory=dict)
+ materialized_columns: Callable[[], MaterializedColumnsByTable] = _no_materialized_columns
+
+ def materialized_column(self, table_name: str, table_column: str, property_name: str) -> MaterializedColumn | None:
+ if table_name not in MATERIALIZATION_VALID_TABLES:
+ return None
+ columns = self.materialized_columns().get(cast(TablesWithMaterializedColumns, table_name))
+ if columns is None:
+ return None
+ return columns.get((property_name, cast(TableColumn, table_column)))
def load_property_metadata(
@@ -42,7 +75,10 @@ def load_property_metadata(
from django.db import models # noqa: PLC0415
from django.db.models.functions.comparison import Coalesce # noqa: PLC0415
- from posthog.clickhouse.materialized_columns import DMAT_STRING_COLUMN_NAME_PREFIX # noqa: PLC0415
+ from posthog.clickhouse.materialized_columns import ( # noqa: PLC0415
+ DMAT_STRING_COLUMN_NAME_PREFIX,
+ get_enabled_materialized_columns_by_table,
+ )
from posthog.models import PropertyDefinition, Team # noqa: PLC0415
from posthog.models.materialized_column_slots import ( # noqa: PLC0415
MaterializedColumnSlot,
@@ -138,4 +174,7 @@ def load_property_metadata(
event_properties=event_properties,
person_properties=person_properties,
group_properties=group_properties,
+ # functools.cache on a fresh wrapper = one registry fetch per bundle (per query), and only
+ # if a materialized-column lookup actually happens (see the field docstring on laziness).
+ materialized_columns=cache(get_enabled_materialized_columns_by_table),
)
diff --git a/posthog/hogql/property_planner.py b/posthog/hogql/property_planner.py
index 5794d99dd533..ebf2a8d813e8 100644
--- a/posthog/hogql/property_planner.py
+++ b/posthog/hogql/property_planner.py
@@ -1,7 +1,7 @@
import dataclasses
from dataclasses import dataclass
from enum import StrEnum
-from typing import Literal, Optional, cast
+from typing import Literal, Optional
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
@@ -28,14 +28,8 @@ from posthog.clickhouse.events_json import (
EVENTS_PROPERTIES_JSON_SUBCOLUMNS,
PERSON_PROPERTIES_JSON_SUBCOLUMNS,
)
-from posthog.clickhouse.materialized_columns import (
- MATERIALIZATION_VALID_TABLES,
- MaterializedColumn,
- TablesWithMaterializedColumns,
- get_materialized_column_for_property,
-)
+from posthog.clickhouse.materialized_column_types import MATERIALIZATION_VALID_TABLES, MaterializedColumn
from posthog.clickhouse.property_groups import property_groups
-from posthog.property_columns import PropertyName, TableColumn
from posthog.schema_enums import PropertyGroupsMode
from products.event_definitions.backend.property_type import PropertyType
@@ -323,10 +317,10 @@ def _plan_property_source(
table_name=table_name, field_name=field_name, property_name=property_name, context=context
)
- materialized_column = get_materialized_column_for_property(
- cast(TablesWithMaterializedColumns, table_name),
- cast(TableColumn, field_name),
- cast(PropertyName, property_name),
+ materialized_column = (
+ context.property_metadata.materialized_column(table_name, field_name, property_name)
+ if context.property_metadata is not None
+ else None
)
if materialized_column is not None:
return PropertySourcePlan(
@@ -461,11 +455,11 @@ def _materialized_column_physical_type(materialized_column: MaterializedColumn)
def get_dmat_column(context: HogQLContext, table_name: str, field_name: str, property_name: str) -> str | None:
"""Dynamically materialized (dmat) column name for a property, if a slot is assigned."""
- if context.property_swapper is None:
+ if context.property_metadata is None:
return None
if table_name != "events" or field_name != "properties":
return None
- prop_info = context.property_swapper.event_properties.get(property_name)
+ prop_info = context.property_metadata.event_properties.get(property_name)
if prop_info is None:
return None
return prop_info.get("dmat")
@@ -498,20 +492,20 @@ def _semantic_type_from_property_definition_type(property_type: str | None) -> a
def _property_info_for_property_type(
property_type: ast.PropertyType, context: HogQLContext
) -> dict[str, str | None] | None:
- if context.property_swapper is None or len(property_type.chain) != 1:
+ if context.property_metadata is None or len(property_type.chain) != 1:
return None
property_name = str(property_type.chain[0])
scope = _property_scope(property_type, context)
if scope == PropertyScope.EVENT:
- return context.property_swapper.event_properties.get(property_name)
+ return context.property_metadata.event_properties.get(property_name)
if scope == PropertyScope.PERSON:
- return context.property_swapper.person_properties.get(property_name)
+ return context.property_metadata.person_properties.get(property_name)
if scope == PropertyScope.GROUP:
group_property_name = _group_property_name(property_type, context, property_name)
if group_property_name is None:
return None
- return context.property_swapper.group_properties.get(group_property_name)
+ return context.property_metadata.group_properties.get(group_property_name)
return None
diff --git a/posthog/hogql/test/test_no_django_imports.py b/posthog/hogql/test/test_no_django_imports.py
index 5d29e04720d8..6877ba5f4430 100644
--- a/posthog/hogql/test/test_no_django_imports.py
+++ b/posthog/hogql/test/test_no_django_imports.py
@@ -32,6 +32,11 @@ DJANGO_FREE_MODULES = [
"posthog.hogql.database.database",
"posthog.hogql.resolver",
"posthog.hogql.property_metadata",
+ "posthog.clickhouse.materialized_column_types",
+ "posthog.hogql.property_planner",
+ "posthog.hogql.transforms.property_types",
+ "posthog.hogql.transforms.lazy_tables",
+ "posthog.hogql.transforms.in_cohort",
]
_CHILD = f"""
diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.py
index 979531258398..a1ced916293a 100644
--- a/posthog/hogql/transforms/clickhouse_property_resolution.py
+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py
@@ -48,9 +48,7 @@ from posthog.clickhouse.events_json import (
EVENTS_PROPERTIES_JSON_SUBCOLUMNS,
PERSON_PROPERTIES_JSON_SUBCOLUMNS,
)
-from posthog.clickhouse.materialized_columns import TablesWithMaterializedColumns, get_materialized_column_for_property
from posthog.clickhouse.property_groups import property_groups
-from posthog.property_columns import PropertyName, TableColumn
from posthog.schema_enums import MaterializationMode, PropertyGroupsMode
# In non-nullable materialized columns these stored strings are treated as NULL.
@@ -137,10 +135,10 @@ def resolve_materialized_property_source(
return None
# 1) static materialized column (mat_* / pmat_*)
- materialized_column = get_materialized_column_for_property(
- cast(TablesWithMaterializedColumns, table_name),
- cast(TableColumn, field_name),
- cast(PropertyName, property_name),
+ materialized_column = (
+ context.property_metadata.materialized_column(table_name, field_name, property_name)
+ if context.property_metadata is not None
+ else None
)
if materialized_column is not None:
return MaterializedPropertySource(
@@ -154,9 +152,9 @@ def resolve_materialized_property_source(
has_bloom_filter_lower_index=materialized_column.has_bloom_filter_lower_index,
)
- # 2) dmat (dynamic materialized) slot — events.properties only, resolved from the property swapper
- if context.property_swapper is not None and table_name == "events" and field_name == "properties":
- property_info = context.property_swapper.event_properties.get(property_name)
+ # 2) dmat (dynamic materialized) slot — events.properties only, resolved from the property metadata
+ if context.property_metadata is not None and table_name == "events" and field_name == "properties":
+ property_info = context.property_metadata.event_properties.get(property_name)
if property_info and (dmat_column := property_info.get("dmat")):
return MaterializedPropertySource(kind="dmat", column=dmat_column, is_nullable=True)
@@ -1148,8 +1146,8 @@ class ClickHousePropertyResolver(CloningVisitor):
return None
is_dynamic_json_string_comparison = allow_dynamic_json and _is_dynamic_json_source(source)
- if self.context.property_swapper is not None:
- prop_info = self.context.property_swapper.event_properties.get(property_name)
+ if self.context.property_metadata is not None:
+ prop_info = self.context.property_metadata.event_properties.get(property_name)
if (
prop_info is not None
and prop_info.get("type") not in (None, "String")
diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.py
index e81996723ddd..2a217c7c1a01 100644
--- a/posthog/hogql/transforms/property_types.py
+++ b/posthog/hogql/transforms/property_types.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Literal, Optional, cast
+from typing import Literal, Optional
from posthog.hogql import ast
from posthog.hogql.constants import EXCEPTION_STRING_ARRAY_PROPERTIES
@@ -24,13 +24,7 @@ from posthog.hogql.type_system import normalized_runtime_type, parse_sql_runtime
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
from posthog.clickhouse.events_json import EVENTS_PROPERTIES_JSON_SUBCOLUMNS, PERSON_PROPERTIES_JSON_SUBCOLUMNS
-from posthog.clickhouse.materialized_columns import (
- MATERIALIZATION_VALID_TABLES,
- MaterializedColumn,
- TablesWithMaterializedColumns,
- get_materialized_column_for_property,
-)
-from posthog.property_columns import PropertyName, TableColumn
+from posthog.clickhouse.materialized_column_types import MATERIALIZATION_VALID_TABLES, MaterializedColumn
_JSON_EXTRACT_SCALAR_CASTS: dict[str, tuple[str, object]] = {
"JSONExtractString": ("String", ""),
@@ -369,11 +363,10 @@ class PropertySwapper(CloningVisitor):
if not isinstance(property_name, str):
return None
- field_name = cast(TableColumn, database_field.name)
- mat_col = get_materialized_column_for_property(
- cast(TablesWithMaterializedColumns, table_name),
- field_name,
- property_name,
+ mat_col = (
+ self.context.property_metadata.materialized_column(table_name, database_field.name, property_name)
+ if self.context.property_metadata is not None
+ else None
)
if mat_col is None:
return None
@@ -829,10 +822,3 @@ class PropertySwapper(CloningVisitor):
end=node.end,
message=message,
)
-
- def _get_materialized_column(
- self, table_name: str, property_name: PropertyName, field_name: TableColumn
- ) -> MaterializedColumn | None:
- return get_materialized_column_for_property(
- cast(TablesWithMaterializedColumns, table_name), field_name, property_name
- )
diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.py
index 6b590d263c59..e448839f36e3 100644
--- a/posthog/hogql/transforms/test/test_property_types.py
+++ b/posthog/hogql/transforms/test/test_property_types.py
@@ -394,7 +394,10 @@ class TestPropertyTypes(BaseTest):
has_minmax_index=True,
)
- with patch("posthog.hogql.property_planner.get_materialized_column_for_property", return_value=fake_column):
+ with patch(
+ "posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table",
+ return_value={"events": {("$screen_width", "properties"): fake_column}},
+ ):
plan = self._plan_where_comparison("select count() from events where properties.$screen_width < 5")
if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA:
@@ -465,7 +468,10 @@ class TestPropertyTypes(BaseTest):
has_minmax_index=True,
)
- with patch("posthog.hogql.property_planner.get_materialized_column_for_property", return_value=fake_column):
+ with patch(
+ "posthog.clickhouse.materialized_columns.get_enabled_materialized_columns_by_table",
+ return_value={"events": {("event_time_prop", "properties"): fake_column}},
+ ):
plan = self._plan_where_comparison(
"select count() from events where properties.event_time_prop < '2024-01-01'"
)