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): Revert "Revert "perf(hogql): speed up cpp-json AST deserialization 14-20x"" (#58303)

Robbie308cc455b823
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)