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.

perf(hogql): speed up cpp-json AST deserialization 14-20x (#58267)

Robbie3aafe19087b9
diff --git a/posthog/hogql/json_ast.py b/posthog/hogql/json_ast.py
index ed9e66990044..f1ecf988d6cd 100644
--- a/posthog/hogql/json_ast.py
+++ b/posthog/hogql/json_ast.py
@@ -2,110 +2,138 @@
JSON AST Deserializer
Converts JSON strings returned by the C++ HogQL parser back into Python AST objects.
+
+Performance: enum-typed fields and dict-shaped fields are precomputed per class
+at import time. The hot loop uses orjson for JSON parsing and avoids
+`get_type_hints` / `hasattr` per node.
"""
-import json
import inspect
from typing import Any, get_type_hints
+import orjson
+
from posthog.hogql import ast
from posthog.hogql.errors import (
ExposedHogQLError,
SyntaxError as HogQLSyntaxError,
)
-
-def deserialize_ast(json_str: str) -> ast.AST:
- """Deserialize a JSON string into a Python AST object."""
- data = json.loads(json_str)
- return _deserialize_node(data)
-
-
-NODE_MAP = {
+NODE_MAP: dict[str, type[ast.AST]] = {
cls.__name__: cls
for _, cls in inspect.getmembers(ast, inspect.isclass)
if issubclass(cls, ast.AST) and cls is not ast.AST
}
+# Fields whose JSON values are dicts of {key: child_node} rather than child
+# nodes themselves. The C++ parser emits these for `window_exprs`, `ctes`
+# (when not list-encoded), and `replace`.
+_DICT_FIELDS = frozenset({"window_exprs", "ctes", "replace"})
+
+# Per-class enum-typed field map, built once at import. Saves a per-node
+# `get_type_hints(cls)` call and a `hasattr(t, "__members__")` check.
+_ENUM_FIELDS: dict[type, dict[str, Any]] = {}
+
+
+def _build_enum_fields() -> None:
+ for cls in NODE_MAP.values():
+ try:
+ hints = get_type_hints(cls)
+ except Exception:
+ continue
+ enum_map = {key: t for key, t in hints.items() if hasattr(t, "__members__")}
+ if enum_map:
+ _ENUM_FIELDS[cls] = enum_map
+
+
+_build_enum_fields()
+
+# Cheap canary: a future AST class whose `get_type_hints` fails at import would
+# be silently skipped above. Assert the known enum-bearing classes registered
+# so a regression to "no enum coercion" trips here rather than being noticed
+# only by a confused downstream consumer.
+assert ast.ArithmeticOperation in _ENUM_FIELDS, "_build_enum_fields did not register ArithmeticOperation"
+assert ast.CompareOperation in _ENUM_FIELDS, "_build_enum_fields did not register CompareOperation"
+
+
+_SPECIAL_FLOATS = {"Infinity": float("inf"), "-Infinity": float("-inf"), "NaN": float("nan")}
-def _convert_special_float(value: str) -> float:
- """Convert string representation of special float values to actual floats."""
- if value == "Infinity":
- return float("inf")
- elif value == "-Infinity":
- return float("-inf")
- elif value == "NaN":
- return float("nan")
- raise ValueError(f"Unknown special float value: {value}")
+
+def deserialize_ast(json_str: str) -> ast.AST:
+ """Deserialize a JSON string into a Python AST object."""
+ return _deserialize_node(orjson.loads(json_str))
def _deserialize_node(data: Any) -> Any:
- """Recursively deserialize a JSON node into an AST object."""
if data is None:
return None
-
if isinstance(data, list):
return [_deserialize_node(item) for item in data]
-
if not isinstance(data, dict):
return data
- if "error" in data and data["error"] is True:
+ if data.get("error") is True:
error_type = data.get("type", "Error")
message = data.get("message", "Unknown error")
- start = data.get("start", {})
- end = data.get("end", {})
-
+ start = data.get("start") or {}
+ end = data.get("end") or {}
if error_type == "SyntaxError" and "reserved keyword" in message:
raise HogQLSyntaxError(message, start=start.get("offset"), end=end.get("offset"))
- else:
- raise ExposedHogQLError(message, start=start.get("offset"), end=end.get("offset"))
+ raise ExposedHogQLError(message, start=start.get("offset"), end=end.get("offset"))
- if "node" not in data:
+ node_type = data.get("node")
+ if node_type is None:
raise ValueError(f"Invalid AST node: missing 'node' field in {data}")
-
- node_type = data["node"]
-
ast_class = NODE_MAP.get(node_type)
if ast_class is None:
raise ValueError(f"Unknown AST node type: {node_type}")
- try:
- type_hints = get_type_hints(ast_class)
- except Exception:
- type_hints = {}
+ enum_map = _ENUM_FIELDS.get(ast_class)
+ is_constant = node_type == "Constant"
+ value_type = data.get("value_type") if is_constant else None
- kwargs = {}
+ kwargs: dict[str, Any] = {}
for key, value in data.items():
- if key in ("node", "value_type"):
+ if key == "node" or key == "value_type":
continue
- if key in ("start", "end") and isinstance(value, dict) and "offset" in value:
- kwargs[key] = value["offset"]
- continue
+ # start/end are encoded as `{"offset": N}` envelopes.
+ if (key == "start" or key == "end") and isinstance(value, dict):
+ offset = value.get("offset")
+ if offset is not None:
+ kwargs[key] = offset
+ continue
- # Handle special float values for Constant nodes
- if node_type == "Constant" and key == "value" and data.get("value_type") == "number":
- if isinstance(value, str) and value in ("Infinity", "-Infinity", "NaN"):
- kwargs[key] = _convert_special_float(value)
+ # Non-finite floats on Constant nodes are emitted as strings.
+ if is_constant and key == "value" and value_type == "number" and isinstance(value, str):
+ special = _SPECIAL_FLOATS.get(value)
+ if special is not None:
+ kwargs[key] = special
continue
+ raise ValueError(f"Unknown special float value: {value}")
+ # `ctes` may be a list of nodes carrying a `name` (preserves order)
+ # — fold it into a dict keyed by the name.
if key == "ctes" and isinstance(value, list):
- # CTEs are emitted as an array to preserve declaration order
- deserialized_value: Any = {item["name"]: _deserialize_node(item) for item in value}
- elif isinstance(value, dict) and "node" not in value and key in ("window_exprs", "ctes", "replace"):
- deserialized_value = {k: _deserialize_node(v) for k, v in value.items()}
- else:
- deserialized_value = _deserialize_node(value)
-
- if key in type_hints:
- field_type = type_hints[key]
- if hasattr(field_type, "__members__") and isinstance(deserialized_value, str):
- try:
- deserialized_value = field_type[deserialized_value]
- except KeyError:
- pass
-
- kwargs[key] = deserialized_value
+ kwargs[key] = {item["name"]: _deserialize_node(item) for item in value}
+ continue
+
+ # Other dict-shaped fields: {key: child_node}.
+ if key in _DICT_FIELDS and isinstance(value, dict) and "node" not in value:
+ kwargs[key] = {k: _deserialize_node(v) for k, v in value.items()}
+ continue
+
+ deserialized = _deserialize_node(value)
+
+ # Coerce enum strings to their StrEnum members.
+ if enum_map is not None and isinstance(deserialized, str):
+ enum_type = enum_map.get(key)
+ if enum_type is not None:
+ try:
+ deserialized = enum_type[deserialized]
+ except KeyError:
+ pass
+
+ kwargs[key] = deserialized
return ast_class(**kwargs)
diff --git a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
index 6a5882b4952d..8d1db09c35d3 100644
--- a/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
+++ b/posthog/hogql_queries/web_analytics/test/__snapshots__/test_web_stats_table.ambr
@@ -947,13 +947,80 @@
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user.1
'''
-
- SELECT timestamp
- from events
- WHERE team_id = 99999
- AND timestamp > '2015-01-01'
- order by timestamp
- limit 1
+ SELECT counts.breakdown_value AS `context.columns.breakdown_value`,
+ tuple(counts.visitors, counts.previous_visitors) AS `context.columns.visitors`,
+ tuple(counts.views, counts.previous_views) AS `context.columns.views`,
+ tuple(bounce.bounce_rate, bounce.previous_bounce_rate) AS `context.columns.bounce_rate`,
+ divide(`context.columns.visitors`.1, sum(`context.columns.visitors`.1) OVER ()) AS `context.columns.ui_fill_fraction`
+ FROM
+ (SELECT breakdown_value AS breakdown_value,
+ uniqIf(filtered_person_id, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS visitors,
+ uniqIf(filtered_person_id, 0) AS previous_visitors,
+ sumIf(filtered_pageview_count, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS views,
+ sumIf(filtered_pageview_count, 0) AS previous_views
+ FROM
+ (SELECT any(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS filtered_person_id,
+ count() AS filtered_pageview_count,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '') AS breakdown_value,
+ events__session.session_id AS session_id,
+ min(events__session.`$start_timestamp`) AS start_timestamp
+ FROM events
+ LEFT JOIN
+ (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
+ raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ 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)
+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1))
+ GROUP BY session_id,
+ breakdown_value)
+ GROUP BY breakdown_value) AS counts
+ LEFT JOIN
+ (SELECT breakdown_value AS breakdown_value,
+ avgIf(is_bounce, and(ifNull(greaterOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), 0), ifNull(lessOrEquals(start_timestamp, assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC'))), 0))) AS bounce_rate,
+ avgIf(is_bounce, 0) AS previous_bounce_rate
+ FROM
+ (SELECT events__session.`$entry_pathname` AS breakdown_value,
+ any(events__session.`$is_bounce`) AS is_bounce,
+ events__session.session_id AS session_id,
+ min(events__session.`$start_timestamp`) AS start_timestamp
+ FROM events
+ LEFT JOIN
+ (SELECT path(nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '')) AS `$entry_pathname`,
+ if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'UTC')), max(toTimeZone(raw_sessions.max_timestamp, 'UTC'))), 10)))) AS `$is_bounce`,
+ toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
+ min(toTimeZone(raw_sessions.min_timestamp, 'UTC')) AS `$start_timestamp`,
+ raw_sessions.session_id_v7 AS session_id_v7
+ FROM raw_sessions
+ WHERE and(equals(raw_sessions.team_id, 99999), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC')), toIntervalDay(3))), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')), toIntervalDay(3))))
+ GROUP BY raw_sessions.session_id_v7) AS events__session ON equals(events.`$session_id_uuid`, events__session.session_id_v7)
+ WHERE and(equals(events.team_id, 99999), and(or(equals(events.event, '$pageview'), equals(events.event, '$screen')), or(and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-02 12:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2023-12-15 23:59:59', 'UTC')))), 0), 1, 1))
+ GROUP BY session_id,
+ breakdown_value)
+ GROUP BY breakdown_value) AS bounce ON equals(counts.breakdown_value, bounce.breakdown_value)
+ WHERE isNotNull(counts.breakdown_value)
+ ORDER BY `context.columns.visitors` DESC,
+ `context.columns.views` DESC,
+ `context.columns.breakdown_value` ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
'''
# ---
# name: TestWebStatsTableQueryRunner.test_bounce_rate_one_user.2