: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(logs): read Map attributes by logical key without JSONExtract (#65450)
Frank Hamand5dbdd31ab8d3
diff --git a/posthog/hogql/database/models.py b/posthog/hogql/database/models.pyindex f8ca90123f1c..cc285246ea7b 100644--- a/posthog/hogql/database/models.py+++ b/posthog/hogql/database/models.py@@ -120,6 +120,15 @@ class StringJSONDatabaseField(DatabaseField):return ""+class MapStringDatabaseField(StringJSONDatabaseField):+ """A physical ClickHouse `Map(String, String)` column presented like a JSON blob.++ Behaves as JSON for resolution, lowering, and property-group routing (suffix-keyed maps such as logs+ `attributes_map_str`), but a key with no precomputed column is read via a native Map subscript instead of+ JSONExtract — which ClickHouse rejects on a Map. See `clickhouse_property_resolution._substitute_value_read`.+ """++class StructDatabaseField(DatabaseField):fields: dict[str, "DatabaseField"] = PydanticField(default_factory=dict)diff --git a/posthog/hogql/database/schema/logs.py b/posthog/hogql/database/schema/logs.pyindex 6d92df7b74fe..715a20bfbe90 100644--- a/posthog/hogql/database/schema/logs.py+++ b/posthog/hogql/database/schema/logs.py@@ -3,6 +3,7 @@ from posthog.hogql.database.models import (DateTimeDatabaseField,FieldOrTable,IntegerDatabaseField,+ MapStringDatabaseField,StringDatabaseField,StringJSONDatabaseField,Table,@@ -24,14 +25,14 @@ class LogsTable(Table):"span_id": StringDatabaseField(name="span_id", nullable=False),"message": StringDatabaseField(name="body", nullable=False),"body": StringDatabaseField(name="body", nullable=False),- "attributes": StringJSONDatabaseField(name="attributes", nullable=False),+ "attributes": MapStringDatabaseField(name="attributes", nullable=False),"time_bucket": DateTimeDatabaseField(name="time_bucket", nullable=False),"timestamp": DateTimeDatabaseField(name="timestamp", nullable=False),"observed_timestamp": DateTimeDatabaseField(name="observed_timestamp", nullable=False),"severity_text": StringDatabaseField(name="severity_text", nullable=False),"severity_number": IntegerDatabaseField(name="severity_number", nullable=False),"level": StringDatabaseField(name="level", nullable=False),- "resource_attributes": StringJSONDatabaseField(name="resource_attributes", nullable=False),+ "resource_attributes": MapStringDatabaseField(name="resource_attributes", nullable=False),"resource_fingerprint": IntegerDatabaseField(name="resource_fingerprint", nullable=False),"instrumentation_scope": StringDatabaseField(name="instrumentation_scope", nullable=False),"event_name": StringDatabaseField(name="event_name", nullable=False),diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.pyindex bcceb024dc47..9ec2bf42b3b9 100644--- a/posthog/hogql/database/schema/metrics.py+++ b/posthog/hogql/database/schema/metrics.py@@ -5,6 +5,7 @@ from posthog.hogql.database.models import (FieldOrTable,FloatDatabaseField,IntegerDatabaseField,+ MapStringDatabaseField,StringDatabaseField,StringJSONDatabaseField,Table,@@ -37,10 +38,10 @@ class MetricsTable(Table):"unit": StringDatabaseField(name="unit", nullable=False),"aggregation_temporality": StringDatabaseField(name="aggregation_temporality", nullable=False),"is_monotonic": BooleanDatabaseField(name="is_monotonic", nullable=False),- "resource_attributes": StringJSONDatabaseField(name="resource_attributes", nullable=False),+ "resource_attributes": MapStringDatabaseField(name="resource_attributes", nullable=False),"resource_fingerprint": IntegerDatabaseField(name="resource_fingerprint", nullable=False),"instrumentation_scope": StringDatabaseField(name="instrumentation_scope", nullable=False),- "attributes": StringJSONDatabaseField(name="attributes", nullable=False),+ "attributes": MapStringDatabaseField(name="attributes", nullable=False),}def to_printed_clickhouse(self, context):diff --git a/posthog/hogql/database/schema/spans.py b/posthog/hogql/database/schema/spans.pyindex 71ce5eec3b9e..b5c86280617c 100644--- a/posthog/hogql/database/schema/spans.py+++ b/posthog/hogql/database/schema/spans.py@@ -3,8 +3,8 @@ from posthog.hogql.database.models import (DateTimeDatabaseField,FieldOrTable,IntegerDatabaseField,+ MapStringDatabaseField,StringDatabaseField,- StringJSONDatabaseField,Table,)@@ -29,9 +29,9 @@ class TraceSpansTable(Table):"duration_nano": IntegerDatabaseField(name="duration_nano", nullable=False),"status_code": IntegerDatabaseField(name="status_code", nullable=False),"service_name": StringDatabaseField(name="service_name", nullable=False),- "resource_attributes": StringJSONDatabaseField(name="resource_attributes", nullable=False),+ "resource_attributes": MapStringDatabaseField(name="resource_attributes", nullable=False),"resource_fingerprint": IntegerDatabaseField(name="resource_fingerprint", nullable=False),- "attributes": StringJSONDatabaseField(name="attributes", nullable=False),+ "attributes": MapStringDatabaseField(name="attributes", nullable=False),"instrumentation_scope": StringDatabaseField(name="instrumentation_scope", nullable=False),"time_bucket": DateTimeDatabaseField(name="time_bucket", nullable=False),}diff --git a/posthog/hogql/observability.py b/posthog/hogql/observability.pyindex 12f8e1d63525..d07fb187b46a 100644--- a/posthog/hogql/observability.py+++ b/posthog/hogql/observability.py@@ -173,6 +173,7 @@ _MATERIALIZED_PROPERTY_RESULTS = {"materialized_column","dynamic_materialized_column","property_group",+ "map_subscript","json",}diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pyindex 76ec20dcdf90..b4b3a91baf43 100644--- a/posthog/hogql/transforms/clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -27,7 +27,7 @@ from typing import Literal, castfrom posthog.hogql import astfrom posthog.hogql.base import _T_ASTfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.models import DatabaseField+from posthog.hogql.database.models import DatabaseField, MapStringDatabaseFieldfrom posthog.hogql.errors import QueryErrorfrom posthog.hogql.functions.mapping import HOGQL_COMPARISON_MAPPINGfrom posthog.hogql.printer.base import resolve_field_type@@ -41,7 +41,7 @@ from posthog.hogql.type_system import (runtime_type_from_constant_type,)from posthog.hogql.utils import ilike_matches, like_matches-from posthog.hogql.visitor import CloningVisitor+from posthog.hogql.visitor import CloningVisitor, clone_exprfrom posthog.clickhouse.materialized_columns import TablesWithMaterializedColumns, get_materialized_column_for_propertyfrom posthog.clickhouse.property_groups import property_groups@@ -301,6 +301,18 @@ def _materialized_head_expr(return ast.Call(name="nullIf", args=[scrubbed_empty, _sentinel("null")])+def _map_value_read(blob: ast.Expr, key: str) -> ast.Expr:+ """`has(map, key) ? map[key] : null` for a physical ClickHouse Map column — a missing key reads NULL, not ''."""+ return ast.Call(+ name="if",+ args=[+ ast.Call(name="has", args=[clone_expr(blob), ast.Constant(value=key)]),+ ast.ArrayAccess(array=clone_expr(blob), property=ast.Constant(value=key)),+ ast.Constant(value=None),+ ],+ )++def _substitute_value_read(node: ast.PropertyAccess, context: HogQLContext) -> ast.Expr | None:"""The backing-column read for a `PropertyAccess`, or None to leave it as the JSON extract.@@ -325,9 +337,19 @@ def _substitute_value_read(node: ast.PropertyAccess, context: HogQLContext) -> areturn ast.Constant(value=None, type=ast.StringType(nullable=True))source = resolve_materialized_property_source(field_type, first_key, context)- _record_property_usage(context, source.kind if source is not None else None)if source is None:+ # A physical Map column (logs/spans/metrics attributes) reads an un-grouped key via map subscript — the JSON+ # fallback would print JSONExtract, which ClickHouse rejects on a Map. Plain JSON blobs (events.properties)+ # keep the JSON fallback.+ if isinstance(field_type.resolve_database_field(context), MapStringDatabaseField):+ _record_property_usage(context, "map_subscript")+ map_head = _map_value_read(node.expr, first_key)+ if not deeper_keys:+ return map_head+ return ast.PropertyAccess(expr=map_head, keys=deeper_keys, type=ast.StringType(nullable=True))+ _record_property_usage(context, None)return None+ _record_property_usage(context, source.kind)head = _materialized_head_expr(source,@@ -412,6 +434,7 @@ _USAGE_BY_SOURCE_KIND = {"materialized_column": "materialized_column","dmat": "dynamic_materialized_column","property_group": "property_group",+ "map_subscript": "map_subscript",}diff --git a/products/logs/backend/test/test_logs_sql_panel.py b/products/logs/backend/test/test_logs_sql_panel.pyindex aa723f7b6ea0..675088bf90d6 100644--- a/products/logs/backend/test/test_logs_sql_panel.py+++ b/products/logs/backend/test/test_logs_sql_panel.py@@ -1,20 +1,28 @@from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from parameterized import parameterized+from posthog.schema import HogQLQueryfrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunnerclass TestLogsSqlPanel(ClickhouseTestMixin, APIBaseTest):- def test_attribute_filter_uses_map_not_json(self):- # Arbitrary HogQL from the SQL panel reads logs attributes via the `attributes_map_str` Map column.- # This relies on the LOGS workload forcing propertyGroupsMode=OPTIMIZED; without it the read falls- # back to JSONExtract, which is illegal on a Map and errors at execution time.- runner = HogQLQueryRunner(- query=HogQLQuery(query="SELECT count() FROM logs WHERE attributes.`log.iostream__str` = 'stderr'"),- team=self.team,- )+ @parameterized.expand(+ [+ # logical key (what a user writes) — reads the `attributes` Map ALIAS via map subscript+ ("dot_logical", "SELECT count() FROM logs WHERE attributes.tennis_session_id = 'x'"),+ ("subscript_logical", "SELECT count() FROM logs WHERE attributes['tennis_session_id'] = 'x'"),+ ("has_logical", "SELECT count() FROM logs WHERE has(attributes, 'tennis_session_id')"),+ ("resource_logical", "SELECT count() FROM logs WHERE resource_attributes['k8s.namespace'] = 'x'"),+ # suffixed key (internal filter form) — routed to the typed `attributes_map_str` via property groups+ ("dot_suffixed", "SELECT count() FROM logs WHERE attributes.`tennis_session_id__str` = 'x'"),+ ]+ )+ def test_attribute_access_never_uses_json_extract(self, _name, query):+ # Logs attributes are physical ClickHouse Map columns, not JSON blobs. Every access form must compile to a+ # map read (subscript or property-group column) — JSONExtract is illegal on a Map and errors at execution.+ runner = HogQLQueryRunner(query=HogQLQuery(query=query), team=self.team)response = runner.calculate()sql = response.clickhouse or ""assert "JSONExtract" not in sql- assert "attributes_map_str" in sql