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(flags): use materialized columns in flag and enrollment queries (#62789)

Phil Haack4c54e2cb03b6
diff --git a/posthog/tasks/early_access_feature.py b/posthog/tasks/early_access_feature.py
index efc1f7efa4bf..dee88d5f0044 100644
--- a/posthog/tasks/early_access_feature.py
+++ b/posthog/tasks/early_access_feature.py
@@ -42,17 +42,19 @@ def send_events_for_early_access_feature_stage_change(feature_id: str, from_stag
if not feature_flag:
return
- # Get the unique persons enrolled in the feature along with their distinct ID
+ # Get the unique persons enrolled in the feature along with their distinct ID.
+ # Property access (rather than JSONExtractString) lets the HogQL printer use
+ # materialized person-property columns when available.
response = execute_hogql_query(
"""
SELECT
argMax(id, created_at) AS id,
- JSONExtractString(properties, 'email') AS email,
+ properties.email AS email,
argMax(pdi.distinct_id, created_at) as distinct_id
FROM persons
- WHERE JSONExtractString(properties, {enrollment_key}) = 'true'
- AND notEmpty(JSONExtractString(properties, 'email'))
- GROUP BY JSONExtractString(properties, 'email')
+ WHERE properties[{enrollment_key}] = 'true'
+ AND notEmpty(properties.email)
+ GROUP BY properties.email
LIMIT {limit}
""",
placeholders={
diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.py
index f4b3c677d50b..22aee49eb2a4 100644
--- a/posthog/test/test_feature_flag_analytics.py
+++ b/posthog/test/test_feature_flag_analytics.py
@@ -24,6 +24,7 @@ from posthog.models.team.team import Team
from products.feature_flags.backend.api.feature_flag import _create_usage_dashboard
from products.feature_flags.backend.flag_analytics import (
SDK_LIBRARIES,
+ _enriched_flag_key_expr_sql,
_extract_sdk_breakdown_from_redis,
_flag_key_filter_sql,
capture_team_decide_usage,
@@ -1086,7 +1087,7 @@ class TestFlagKeyFilterSQL(BaseTest):
sql = _flag_key_filter_sql()
assert "JSONExtractString(properties, '$feature_flag')" in sql
- def test_uses_materialized_column_when_available(self):
+ def test_uses_escaped_materialized_column_when_available(self):
fake_column = MagicMock()
fake_column.name = "mat_$feature_flag"
with patch(
@@ -1094,5 +1095,37 @@ class TestFlagKeyFilterSQL(BaseTest):
return_value=fake_column,
):
sql = _flag_key_filter_sql()
- assert "mat_$feature_flag" in sql
+ assert "`mat_$feature_flag` = %(flag_key)s" in sql
assert "JSONExtractString" not in sql
+
+
+class TestEnrichedFlagKeyExprSQL(BaseTest):
+ def test_falls_back_to_json_extract_when_not_materialized(self):
+ with patch(
+ "products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",
+ return_value=None,
+ ):
+ sql = _enriched_flag_key_expr_sql()
+ assert sql == "JSONExtractString(properties, 'feature_flag')"
+
+ def test_uses_escaped_materialized_column_when_available(self):
+ fake_column = MagicMock()
+ fake_column.name = "mat_feature_flag"
+ fake_column.is_nullable = False
+ with patch(
+ "products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",
+ return_value=fake_column,
+ ):
+ sql = _enriched_flag_key_expr_sql()
+ assert sql == "`mat_feature_flag`"
+
+ def test_coalesces_nullable_materialized_column(self):
+ fake_column = MagicMock()
+ fake_column.name = "mat_feature_flag"
+ fake_column.is_nullable = True
+ with patch(
+ "products.feature_flags.backend.flag_analytics.get_materialized_column_for_property",
+ return_value=fake_column,
+ ):
+ sql = _enriched_flag_key_expr_sql()
+ assert sql == "ifNull(`mat_feature_flag`, '')"
diff --git a/products/feature_flags/backend/flag_analytics.py b/products/feature_flags/backend/flag_analytics.py
index a9fec11da6e0..1eda0b105da5 100644
--- a/products/feature_flags/backend/flag_analytics.py
+++ b/products/feature_flags/backend/flag_analytics.py
@@ -231,17 +231,35 @@ def capture_team_decide_usage(ph_client: "Posthog", team_id: int, team_uuid: str
capture_exception(error)
-def find_flags_with_enriched_analytics(begin: datetime, end: datetime):
- tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.ENRICHMENT, name="find_flags_with_enriched_analytics")
- result = sync_execute(
- """
- SELECT team_id, JSONExtractString(properties, 'feature_flag') as flag_key
+def _enriched_flag_key_expr_sql() -> str:
+ """SQL expression for the `feature_flag` property, using the materialized column when available.
+
+ This query spans all teams so it can't go through the HogQL printer; the
+ materialized-column lookup has to be done by hand, with a JSONExtractString
+ fallback for instances where the property isn't materialized. Nullable
+ columns are coalesced to '' to match JSONExtractString's missing-property
+ behavior.
+ """
+ column = get_materialized_column_for_property("events", "properties", "feature_flag")
+ if column is None:
+ return "JSONExtractString(properties, 'feature_flag')"
+ if column.is_nullable:
+ return f"ifNull(`{column.name}`, '')"
+ return f"`{column.name}`"
+
+
+def _build_enriched_analytics_query() -> str:
+ return f"""
+ SELECT team_id, {_enriched_flag_key_expr_sql()} as flag_key
FROM events
WHERE timestamp between %(begin)s AND %(end)s AND event = '$feature_view'
GROUP BY team_id, flag_key
- """,
- {"begin": begin, "end": end},
- )
+ """
+
+
+def find_flags_with_enriched_analytics(begin: datetime, end: datetime):
+ tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.ENRICHMENT, name="find_flags_with_enriched_analytics")
+ result = sync_execute(_build_enriched_analytics_query(), {"begin": begin, "end": end})
for row in result:
team_id = row[0]
@@ -274,7 +292,10 @@ def _flag_key_filter_sql() -> str:
"""
column = get_materialized_column_for_property("events", "properties", "$feature_flag")
if column is not None:
- return f"{column.name} = %(flag_key)s"
+ # No ifNull for nullable columns: NULL never equals a real flag key,
+ # matching the JSONExtractString('') behavior, and the bare column
+ # keeps any skip index usable.
+ return f"`{column.name}` = %(flag_key)s"
return "JSONExtractString(properties, '$feature_flag') = %(flag_key)s"