: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
feat(logs): add custom column expression module (#67727)
Jon McCallum6d29c3198404
diff --git a/products/logs/backend/column_expressions.py b/products/logs/backend/column_expressions.pynew file mode 100644index 000000000000..b58335db5202--- /dev/null+++ b/products/logs/backend/column_expressions.py@@ -0,0 +1,98 @@+import hashlib++from posthog.hogql import ast+from posthog.hogql.functions.mapping import find_hogql_aggregation+from posthog.hogql.parser import parse_expr+from posthog.hogql.visitor import TraversingVisitor++# A recognized source prefix selects the lowering strategy (source-driven):+# flat map lookup for attribute maps, JSON dig for the body string.+FLAT_MAP_SOURCES = ("attributes", "resource_attributes")+JSON_BODY_SOURCE = "body"+++def path_to_expr(source: str, path: str) -> ast.Expr:+ """Lower a custom-column descriptor `(source, path)` into a HogQL AST expression.++ - `attributes` / `resource_attributes`: the whole `path` is a single map key+ (dots are part of the OTel key, never split) -> `attributes['http.url']`.+ - `body`: `path` is a dot-separated JSON path -> `JSONExtractString(body, 'user', 'id')`.++ `path` is always carried as a bound chain member / Constant, so it cannot escape+ the map-index or JSONExtract boundary as interpolated SQL.+ """+ if source in FLAT_MAP_SOURCES:+ return ast.Field(chain=[source, path])++ if source == JSON_BODY_SOURCE:+ segments = path.split(".")+ if any(segment == "" for segment in segments):+ raise ValueError(f"Body path {path!r} contains an empty segment")+ keys = [ast.Constant(value=segment) for segment in segments]+ return ast.Call(name="JSONExtractString", args=[ast.Field(chain=[JSON_BODY_SOURCE]), *keys])++ raise ValueError(f"Unknown custom-column source: {source!r}")+++def parse_shorthand(text: str) -> ast.Expr | None:+ """Lower `<source>.<path>` shorthand, or return `None` if `text` has no recognized prefix.++ A bare source name with no path (`attributes`) is not shorthand — it falls through+ to full-expression parsing like any other field.+ """+ source, dot, path = text.partition(".")+ if not dot or not path:+ return None+ if source not in FLAT_MAP_SOURCES and source != JSON_BODY_SOURCE:+ return None+ return path_to_expr(source, path)+++class _ScalarValidator(TraversingVisitor):+ def visit_select_query(self, node: ast.SelectQuery) -> None:+ raise ValueError("Custom columns cannot contain subqueries")++ def visit_select_set_query(self, node: ast.SelectSetQuery) -> None:+ raise ValueError("Custom columns cannot contain subqueries")++ def visit_placeholder(self, node: ast.Placeholder) -> None:+ raise ValueError("Custom columns cannot contain placeholders")++ def visit_call(self, node: ast.Call) -> None:+ if find_hogql_aggregation(node.name) is not None:+ raise ValueError(f"Custom columns must be per-row: aggregation {node.name!r} is not allowed")+ super().visit_call(node)+++def _validate_scalar(expr: ast.Expr) -> None:+ """Reject subqueries, aggregations, and unresolved placeholders anywhere in `expr`.++ Scalar function calls, field access, arithmetic, conditionals, and constants all+ pass. This is an AST check — the expression is never inspected as a string.+ """+ _ScalarValidator().visit(expr)+++def column_to_expr(text: str) -> ast.Expr:+ """Resolve a custom-column string into a validated per-row HogQL AST expression.++ Recognized source prefix -> shorthand lowering; otherwise the whole string is+ parsed as HogQL (`parse_expr`, so input is never interpolated as SQL). Raises+ `ValueError` for non-scalar expressions and HogQL syntax errors for unparsable input.+ """+ text = text.strip()+ expr = parse_shorthand(text)+ if expr is None:+ expr = parse_expr(text)+ _validate_scalar(expr)+ return expr+++def canonical_key(text: str) -> str:+ """Derive a stable `col_<hash>` alias from the expression string.++ Independent of any client-generated uuid so identical column setups hash to the+ same query (and therefore the same query cache key).+ """+ digest = hashlib.sha256(text.strip().encode()).hexdigest()+ return f"col_{digest[:12]}"diff --git a/products/logs/backend/test/test_column_expressions.py b/products/logs/backend/test/test_column_expressions.pynew file mode 100644index 000000000000..671a387e7ddf--- /dev/null+++ b/products/logs/backend/test/test_column_expressions.py@@ -0,0 +1,140 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.hogql import ast+from posthog.hogql.errors import SyntaxError as HogQLSyntaxError+from posthog.hogql.visitor import clear_locations++from products.logs.backend.column_expressions import canonical_key, column_to_expr, path_to_expr+++class TestPathToExpr(SimpleTestCase):+ @parameterized.expand(+ [+ ("flat_attribute_key", "attributes", "http.url"),+ ("flat_resource_attribute_key", "resource_attributes", "service.name"),+ ]+ )+ def test_flat_map_key_lowers_to_field_chain(self, _name, source, path):+ # attributes / resource_attributes: the whole path is a single map key (dots included)+ assert path_to_expr(source, path) == ast.Field(chain=[source, path])++ def test_dotted_attribute_path_stays_a_single_flat_key(self):+ # source-driven: a dotted attribute path is NOT split into a nested dig+ assert path_to_expr("attributes", "a.b.c") == ast.Field(chain=["attributes", "a.b.c"])++ def test_body_nested_json_path_lowers_to_jsonextractstring(self):+ assert path_to_expr("body", "user.id") == ast.Call(+ name="JSONExtractString",+ args=[ast.Field(chain=["body"]), ast.Constant(value="user"), ast.Constant(value="id")],+ )++ def test_body_single_segment_path_lowers_to_jsonextractstring(self):+ assert path_to_expr("body", "message") == ast.Call(+ name="JSONExtractString",+ args=[ast.Field(chain=["body"]), ast.Constant(value="message")],+ )++ @parameterized.expand(+ [+ ("double_dot", "a..b"),+ ("leading_dot", ".a"),+ ("trailing_dot", "a."),+ ]+ )+ def test_body_path_with_empty_segment_is_rejected(self, _name, path):+ # an empty segment is a user typo, not a valid JSON key -> surface it instead of digging ''+ with self.assertRaises(ValueError):+ path_to_expr("body", path)++ def test_injection_in_attribute_key_is_kept_as_bound_string(self):+ malicious = "x'] AS y, (SELECT 1) --"+ expr = path_to_expr("attributes", malicious)+ # the malicious input survives verbatim as a chain member, never parsed as SQL+ assert isinstance(expr, ast.Field)+ assert expr.chain == ["attributes", malicious]++ def test_injection_in_body_path_is_kept_as_bound_constants(self):+ malicious = "') OR 1=1 --"+ expr = path_to_expr("body", malicious)+ # no dots -> one segment, carried as a bound Constant, not interpolated SQL+ assert isinstance(expr, ast.Call)+ assert expr.name == "JSONExtractString"+ assert expr.args[0] == ast.Field(chain=["body"])+ assert expr.args[1] == ast.Constant(value=malicious)+++class TestColumnToExpr(SimpleTestCase):+ @parameterized.expand(+ [+ ("attributes_flat_key", "attributes.http.url", ast.Field(chain=["attributes", "http.url"])),+ (+ "resource_attributes_flat_key",+ "resource_attributes.service.name",+ ast.Field(chain=["resource_attributes", "service.name"]),+ ),+ (+ "body_json_dig",+ "body.user.id",+ ast.Call(+ name="JSONExtractString",+ args=[ast.Field(chain=["body"]), ast.Constant(value="user"), ast.Constant(value="id")],+ ),+ ),+ ]+ )+ def test_recognized_prefix_routes_to_shorthand(self, _name, text, expected):+ assert column_to_expr(text) == expected++ def test_bare_source_name_is_not_shorthand(self):+ # "attributes" with no path falls through to HogQL as a plain field+ assert clear_locations(column_to_expr("attributes")) == ast.Field(chain=["attributes"])++ def test_unrecognized_prefix_parses_as_hogql(self):+ # a top-level field with dots but no recognized source is HogQL field access, not shorthand+ expr = clear_locations(column_to_expr("upper(level)"))+ assert expr == ast.Call(name="upper", args=[ast.Field(chain=["level"])])++ def test_scalar_functions_and_map_access_are_allowed(self):+ # coalesce over map indexing exercises the validator's allow path on a compound expression+ expr = column_to_expr("coalesce(attributes['a'], attributes['b'])")+ assert isinstance(expr, ast.Call)+ assert expr.name == "coalesce"++ @parameterized.expand(+ [+ ("top_level_aggregate", "count()"),+ ("case_insensitive_aggregate", "COUNT()"),+ ("nested_aggregate", "upper(toString(sum(1)))"),+ ("subquery", "(SELECT 1)"),+ ("placeholder", "{cursor}"),+ ]+ )+ def test_non_scalar_expressions_are_rejected(self, _name, text):+ with self.assertRaises(ValueError):+ column_to_expr(text)++ def test_unparsable_input_raises_instead_of_passing_through(self):+ # tier 2 goes through parse_expr: junk is a syntax error, never interpolated SQL+ with self.assertRaises(HogQLSyntaxError):+ column_to_expr("level; DROP TABLE logs")+++class TestCanonicalKey(SimpleTestCase):+ @parameterized.expand(+ [+ ("attributes_http_url", "attributes.http.url", "col_7284f0d699a5"),+ ("body_user_id", "body.user.id", "col_d26ac1a56e8b"),+ ("upper_level", "upper(level)", "col_ec05982ca9de"),+ ]+ )+ def test_canonical_key_is_stable(self, _name, text, expected):+ assert canonical_key(text) == expected++ def test_canonical_key_differs_by_expression(self):+ assert canonical_key("attributes.http.url") != canonical_key("attributes.http.method")++ def test_canonical_key_ignores_surrounding_whitespace(self):+ # column_to_expr strips input, so the alias must too — else identical columns miss the cache+ assert canonical_key(" upper(level) ") == canonical_key("upper(level)")