: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
refactor(hogql): split literal folding helpers (#100089)
Paul D'Ambra7f64c1ca669d
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.pyindex 37c73558616a..ded2c3f27120 100644--- a/posthog/hogql/test/test_type_system.py+++ b/posthog/hogql/test/test_type_system.py@@ -1,5 +1,6 @@from datetime import datefrom typing import Optional, cast+from uuid import UUIDimport pytest@@ -1243,6 +1244,8 @@ class TestHogQLTypeSystem:"accurateCast('42', 'Int64') AS number, ""toFloat(1) AS score, ""toBool('true') AS flag, "+ "accurateCast('2024-01-01', 'Date') AS day, "+ "accurateCast('00000000-0000-0000-0000-000000000001', 'UUID') AS identifier, ""ifNull(NULL, 4) AS if_null, ""ifNull(5, NULL) AS if_not_null, ""coalesce(NULL, NULL, 6) AS coalesced, "@@ -1260,7 +1263,19 @@ class TestHogQLTypeSystem:)values = [cast(ast.Constant, cast(ast.Alias, select_expr).expr).value for select_expr in simplified.select]- assert values == [42, 1.0, True, 4, 5, 6, 2.5, 1, '{"a":1}']+ assert values == [+ 42,+ 1.0,+ True,+ date(2024, 1, 1),+ UUID("00000000-0000-0000-0000-000000000001"),+ 4,+ 5,+ 6,+ 2.5,+ 1,+ '{"a":1}',+ ]types: list[ast.ConstantType] = []for select_expr in simplified.select:@@ -1272,6 +1287,8 @@ class TestHogQLTypeSystem:ast.IntegerType(nullable=False),ast.FloatType(nullable=False),ast.BooleanType(nullable=False),+ ast.DateType(nullable=False),+ ast.UUIDType(nullable=False),ast.IntegerType(nullable=False),ast.IntegerType(nullable=False),ast.IntegerType(nullable=False),@@ -1280,6 +1297,46 @@ class TestHogQLTypeSystem:ast.StringType(nullable=False),]+ def test_type_aware_simplification_folds_literal_json_helper_variants(self) -> None:+ resolved = cast(+ ast.SelectQuery,+ resolve_types(+ self._select(+ "SELECT "+ "JSONExtractString('{\"users\": [{\"name\": \"Ada\"}]}', 'users', 1, 'name') AS name, "+ "JSONExtractInt('{\"count\": 2}', 'count') AS count, "+ "JSONExtractFloat('{\"score\": 2}', 'score') AS score, "+ "JSONExtractBool('{\"active\": true}', 'active') AS active, "+ "JSONLength('{\"items\": [1, 2]}', 'items') AS length, "+ "JSONExtract('{\"tags\": [\"a\"]}', 'tags', 'Array(String)') AS tags, "+ "JSONExtract('{\"labels\": {\"a\": \"b\"}}', 'labels', 'Map(String, String)') AS labels"+ ),+ self.context,+ dialect="clickhouse",+ ),+ )+ simplified = cast(+ ast.SelectQuery,+ simplify_redundant_type_operations(resolved, self.context, dialect="clickhouse"),+ )++ expressions = [cast(ast.Alias, select_expr).expr for select_expr in simplified.select]++ assert [cast(ast.Constant, expr).value for expr in expressions] == ["Ada", 2, 2.0, True, 2, ["a"], {"a": "b"}]+ assert [cast(ast.Constant, expr).type for expr in expressions] == [+ ast.StringType(nullable=False),+ ast.IntegerType(nullable=False),+ ast.FloatType(nullable=False),+ ast.BooleanType(nullable=False),+ ast.IntegerType(nullable=False),+ ast.ArrayType(nullable=False, item_type=ast.StringType(nullable=False)),+ ast.MapType(+ nullable=False,+ key_type=ast.StringType(nullable=False),+ value_type=ast.StringType(nullable=False),+ ),+ ]+def test_type_aware_simplification_keeps_unsafe_casts(self) -> None:resolved = cast(ast.SelectQuery,@@ -1331,6 +1388,14 @@ class TestHogQLTypeSystem:assert isinstance(expr, ast.Call)assert expr.name.lower() == "accuratecast"+ for query, function_name in (+ ("SELECT JSONExtractString('{\"count\": 1}', 'count') AS x", "jsonextractstring"),+ ("SELECT JSONLength('{\"count\": 1}', 'count') AS x", "jsonlength"),+ ):+ expr = _simplified_expr(query)+ assert isinstance(expr, ast.Call)+ assert expr.name.lower() == function_name+# A nullable input keeps its null-fallback / null-assertion wrapper.if_null_expr = _simplified_expr("SELECT ifNull(nullIf(5, 3), 0) AS x")assert isinstance(if_null_expr, ast.Call)diff --git a/posthog/hogql/transforms/type_aware_simplification.py b/posthog/hogql/transforms/type_aware_simplification.pyindex 45793681b330..80a6317f3b6f 100644--- a/posthog/hogql/transforms/type_aware_simplification.py+++ b/posthog/hogql/transforms/type_aware_simplification.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport math+from collections.abc import Callablefrom datetime import date, datetime, timedeltafrom typing import castfrom uuid import UUID@@ -383,52 +384,93 @@ def _fold_constant_cast(source: ast.Expr, target_type: RuntimeType, allow_numeridef _convert_literal_to_runtime_type(value: object, target_type: RuntimeType) -> object | None:+ converter = _LITERAL_RUNTIME_TYPE_CONVERTERS.get(target_type.family)+ if converter is None:+ return None+try:- if target_type.family == "integer":- if isinstance(value, bool):- return None- if isinstance(value, int):- return value- if isinstance(value, str):- return int(value)- return None- if target_type.family == "float":- if isinstance(value, bool):- return None- if isinstance(value, (int, float, str)):- result = float(value)- return result if math.isfinite(result) else None- return None- if target_type.family == "boolean":- if isinstance(value, bool):- return value- if isinstance(value, int) and value in (0, 1):- return bool(value)- if isinstance(value, str) and value.lower() in {"true", "false"}:- return value.lower() == "true"- return None- if target_type.family == "uuid":- if isinstance(value, UUID):- return value- if isinstance(value, str):- return UUID(value)- return None- if target_type.family == "date":- if isinstance(value, datetime):- return value.date()- if isinstance(value, date):- return value- if isinstance(value, str):- return date.fromisoformat(value)- return None+ return converter(value)except (TypeError, ValueError, OverflowError):return None+++def _convert_integer_literal(value: object) -> int | None:+ if isinstance(value, int) and not isinstance(value, bool):+ return value+ if isinstance(value, str):+ return int(value)+ return None+++def _convert_float_literal(value: object) -> float | None:+ if not isinstance(value, (int, float, str)) or isinstance(value, bool):+ return None+ result = float(value)+ return result if math.isfinite(result) else None+++def _convert_boolean_literal(value: object) -> bool | None:+ if isinstance(value, bool):+ return value+ if isinstance(value, int) and value in (0, 1):+ return bool(value)+ if isinstance(value, str) and value.lower() in {"true", "false"}:+ return value.lower() == "true"+ return None+++def _convert_uuid_literal(value: object) -> UUID | None:+ if isinstance(value, UUID):+ return value+ if isinstance(value, str):+ return UUID(value)+ return None+++def _convert_date_literal(value: object) -> date | None:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ return date.fromisoformat(value)return None+_LITERAL_RUNTIME_TYPE_CONVERTERS: dict[str, Callable[[object], object | None]] = {+ "integer": _convert_integer_literal,+ "float": _convert_float_literal,+ "boolean": _convert_boolean_literal,+ "uuid": _convert_uuid_literal,+ "date": _convert_date_literal,+}++def _fold_literal_json_call(node: ast.Call, dialect: HogQLDialect) -> ast.Constant | None:normalized_name = node.name.lower()- if normalized_name not in {+ if normalized_name not in _LITERAL_JSON_FUNCTIONS or not node.args:+ return None+ document = _literal_json_document(node.args[0])+ if document is _JSON_PATH_MISSING:+ return None+ path_and_type = _literal_json_path_and_type(node, normalized_name, dialect)+ if path_and_type is None:+ return None+ path, target_type = path_and_type+ path_value = _literal_json_path_value(document, path)+ if path_value is _JSON_PATH_MISSING:+ return None++ if normalized_name == "jsonextract":+ return _fold_typed_json_extract(node, path_value, target_type)++ return _LITERAL_JSON_VALUE_FOLDERS[normalized_name](node, path_value)+++_JSON_PATH_MISSING = object()++_LITERAL_JSON_FUNCTIONS = frozenset(+ {"jsonextract","jsonextractuint","jsonextractint",@@ -439,95 +481,105 @@ def _fold_literal_json_call(node: ast.Call, dialect: HogQLDialect) -> ast.Consta"jsonhas","jsonlength","jsonarraylength",- }:- return None- if not node.args:- return None+ }+)- raw_json = _constant_string_value(node.args[0])- if raw_json is None:- return None+def _literal_json_document(node: ast.Expr) -> object:+ raw_json = _constant_string_value(node)+ if raw_json is None:+ return _JSON_PATH_MISSINGtry:- document = json.loads(raw_json)+ return json.loads(raw_json)except json.JSONDecodeError:- return None+ return _JSON_PATH_MISSING- if normalized_name == "jsonextract":++def _literal_json_path_and_type(+ node: ast.Call, normalized_name: str, dialect: HogQLDialect+) -> tuple[list[str | int], RuntimeType | None] | None:+ if normalized_name != "jsonextract":+ path_args = node.args[1:]+ target_type = None+ else:if len(node.args) < 2:return Nonetype_name = _constant_string_value(node.args[-1])if type_name is None:return None- target_type = parse_sql_runtime_type(type_name, dialect=dialect)path_args = node.args[1:-1]- else:- target_type = None- path_args = node.args[1:]+ target_type = parse_sql_runtime_type(type_name, dialect=dialect)path = [_constant_json_path_component(arg) for arg in path_args]if any(component is None for component in path):return None+ return cast(list[str | int], path), target_type- path_value = _literal_json_path_value(document, cast(list[str | int], path))- if path_value is _JSON_PATH_MISSING:++def _fold_typed_json_extract(+ node: ast.Call, path_value: object, target_type: RuntimeType | None+) -> ast.Constant | None:+ if target_type is None:+ return None+ converted_value = _convert_json_literal_to_runtime_type(path_value, target_type)+ if converted_value is None:return None+ return _json_constant(node, converted_value, constant_type_from_runtime_type(target_type.with_nullable(False)))- if normalized_name == "jsonhas":- return ast.Constant(value=1, type=ast.IntegerType(nullable=False), start=node.start, end=node.end)- if normalized_name in {"jsonlength", "jsonarraylength"}:- if isinstance(path_value, (dict, list)):- return ast.Constant(- value=len(path_value), type=ast.IntegerType(nullable=False), start=node.start, end=node.end- )+def _fold_json_has(node: ast.Call, _: object) -> ast.Constant:+ return _json_constant(node, 1, ast.IntegerType(nullable=False))+++def _fold_json_length(node: ast.Call, value: object) -> ast.Constant | None:+ if not isinstance(value, (dict, list)):return None+ return _json_constant(node, len(value), ast.IntegerType(nullable=False))- if normalized_name == "jsonextractraw":- return ast.Constant(- value=json.dumps(path_value, separators=(",", ":")),- type=ast.StringType(nullable=False),- start=node.start,- end=node.end,- )- if normalized_name == "jsonextractstring":- if isinstance(path_value, str):- return ast.Constant(value=path_value, type=ast.StringType(nullable=False), start=node.start, end=node.end)+def _fold_json_raw(node: ast.Call, value: object) -> ast.Constant:+ return _json_constant(node, json.dumps(value, separators=(",", ":")), ast.StringType(nullable=False))+++def _fold_json_string(node: ast.Call, value: object) -> ast.Constant | None:+ if not isinstance(value, str):return None+ return _json_constant(node, value, ast.StringType(nullable=False))- if normalized_name in {"jsonextractuint", "jsonextractint"}:- if isinstance(path_value, int) and not isinstance(path_value, bool):- return ast.Constant(value=path_value, type=ast.IntegerType(nullable=False), start=node.start, end=node.end)++def _fold_json_integer(node: ast.Call, value: object) -> ast.Constant | None:+ if not isinstance(value, int) or isinstance(value, bool):return None+ return _json_constant(node, value, ast.IntegerType(nullable=False))+- if normalized_name == "jsonextractfloat":- if isinstance(path_value, (int, float)) and not isinstance(path_value, bool):- return ast.Constant(- value=float(path_value), type=ast.FloatType(nullable=False), start=node.start, end=node.end- )+def _fold_json_float(node: ast.Call, value: object) -> ast.Constant | None:+ if not isinstance(value, (int, float)) or isinstance(value, bool):return None+ return _json_constant(node, float(value), ast.FloatType(nullable=False))- if normalized_name == "jsonextractbool":- if isinstance(path_value, bool):- return ast.Constant(value=path_value, type=ast.BooleanType(nullable=False), start=node.start, end=node.end)++def _fold_json_boolean(node: ast.Call, value: object) -> ast.Constant | None:+ if not isinstance(value, bool):return None+ return _json_constant(node, value, ast.BooleanType(nullable=False))- if normalized_name == "jsonextract" and target_type is not None:- converted_value = _convert_json_literal_to_runtime_type(path_value, target_type)- if converted_value is None:- return None- return ast.Constant(- value=converted_value,- type=constant_type_from_runtime_type(target_type.with_nullable(False)),- start=node.start,- end=node.end,- )- return None+def _json_constant(node: ast.Call, value: object, constant_type: ast.ConstantType) -> ast.Constant:+ return ast.Constant(value=value, type=constant_type, start=node.start, end=node.end)-_JSON_PATH_MISSING = object()+_LITERAL_JSON_VALUE_FOLDERS: dict[str, Callable[[ast.Call, object], ast.Constant | None]] = {+ "jsonhas": _fold_json_has,+ "jsonlength": _fold_json_length,+ "jsonarraylength": _fold_json_length,+ "jsonextractraw": _fold_json_raw,+ "jsonextractstring": _fold_json_string,+ "jsonextractuint": _fold_json_integer,+ "jsonextractint": _fold_json_integer,+ "jsonextractfloat": _fold_json_float,+ "jsonextractbool": _fold_json_boolean,+}def _literal_json_path_value(document: object, path: list[str | int]) -> object:@@ -535,8 +587,8 @@ def _literal_json_path_value(document: object, path: list[str | int]) -> object:for component in path:if isinstance(current, dict) and isinstance(component, str) and component in current:current = current[component]- elif isinstance(current, list) and isinstance(component, int) and 0 <= component < len(current):- current = current[component]+ elif isinstance(current, list) and isinstance(component, int) and 0 < component <= len(current):+ current = current[component - 1]else:return _JSON_PATH_MISSINGreturn current