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.

chore(hogql): compare positions in parser shadow comparison (#60226)

Robbie970c8ceb3024
diff --git a/posthog/hogql/json_ast.py b/posthog/hogql/json_ast.py
index 69623880e66c..6cf625167bd6 100644
--- a/posthog/hogql/json_ast.py
+++ b/posthog/hogql/json_ast.py
@@ -30,6 +30,18 @@ NODE_MAP: dict[str, type[ast.AST]] = {
# (when not list-encoded), and `replace`.
_DICT_FIELDS = frozenset({"window_exprs", "ctes", "replace"})
+# Per-node fields whose inner JSON arrays should land as Python `tuple` (not
+# `list`). JSON has no tuple type, so cpp / rust-json emit `[[k,v]]` for fields
+# the Python AST types as `list[tuple[...]]`. Without this map the deserialiser
+# would return `list[list]`, which doesn't `==` the `list[tuple]` that
+# `rust-py` and `CloningVisitor` build — surfacing as bogus "position-only"
+# shadow mismatches on every Hog program containing a dict literal or a
+# try/catch.
+_TUPLE_INNER_FIELDS: dict[str, frozenset[str]] = {
+ "Dict": frozenset({"items"}),
+ "TryCatchStatement": frozenset({"catches"}),
+}
+
# 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]] = {}
@@ -143,6 +155,18 @@ def _deserialize_node(data: Any) -> Any:
kwargs[key] = {item["name"]: _deserialize_node(item) for item in value}
continue
+ # Inner-array → tuple for fields the Python AST types as `list[tuple]`
+ # (see `_TUPLE_INNER_FIELDS`). JSON arrays default to `list` everywhere
+ # else; this targeted conversion keeps `==` parity with `rust-py` /
+ # `CloningVisitor`, which both build tuples.
+ node_tuple_fields = _TUPLE_INNER_FIELDS.get(node_type)
+ if node_tuple_fields is not None and key in node_tuple_fields and isinstance(value, list):
+ kwargs[key] = [
+ tuple(_deserialize_node(item) for item in row) if isinstance(row, list) else _deserialize_node(row)
+ for row 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()}
diff --git a/posthog/hogql/parser.py b/posthog/hogql/parser.py
index 5f9cc218b187..a8eba54e22a7 100644
--- a/posthog/hogql/parser.py
+++ b/posthog/hogql/parser.py
@@ -315,7 +315,8 @@ def _run_shadow_comparison(
`capture_exception`, not the logs.
Prod records divergences and shadow crashes without raising. TEST raises on a divergence or a shadow that rejects
- primary-accepted input; a packaging-class shadow failure (broken wheel, panic) is only counted.
+ primary-accepted input; a packaging-class shadow failure (broken wheel, panic) is only counted. ASTs are compared
+ INCLUDING per-node `start` / `end` positions — divergent spans are flagged "position-only" for triage.
"""
if random.random() >= _shadow_sample_rate():
return
@@ -352,19 +353,31 @@ def _run_shadow_comparison(
_count("shadow_error")
capture_exception(err, additional_properties={**divergence_properties, "hogql_parser_shadow_throw": "true"})
return
- # Structure-only: clearing locations drops `start`/`end`, which diverge widely between cpp and rust-py on real
- # queries. Source-position parity is left to the cross-backend parser test suite and a follow-up.
- primary_cleared = clear_locations(primary_node)
- shadow_cleared = clear_locations(shadow_node)
- # Dataclass `==` reports a false mismatch for NaN-bearing ASTs (`float("nan") != float("nan")`); repr is stable for NaN, so treat repr-equal as agreement too.
- if primary_cleared == shadow_cleared or repr(primary_cleared) == repr(shadow_cleared):
+ # Positions are part of the contract — the printer and planner consume cpp's per-node `start` / `end` spans, so a
+ # span divergence is a real divergence. Compare full nodes; `clear_locations` is only used to classify a mismatch
+ # as position-only vs structural for triage. Dataclass `==` reports a false mismatch for NaN-bearing ASTs
+ # (`float("nan") != float("nan")`); repr is stable for NaN, so treat repr-equal as agreement too.
+ if primary_node == shadow_node or repr(primary_node) == repr(shadow_node):
_count("agree")
return
+ primary_cleared = clear_locations(primary_node)
+ shadow_cleared = clear_locations(shadow_node)
+ position_only = primary_cleared == shadow_cleared or repr(primary_cleared) == repr(shadow_cleared)
+ kind = "position-only" if position_only else "structural"
_count("disagree")
- mismatch = HogQLParserShadowMismatch(f"{rule} parser AST mismatch: {primary_backend} vs {shadow_backend}")
+ # Include the offending statement so a failing test (or 1%-sample capture) is self-describing — the raised
+ # exception is otherwise just "rule + backends". Truncate to keep the message bounded; the full statement is
+ # also attached as a capture property via `divergence_properties`.
+ excerpt = statement if len(statement) <= 2000 else statement[:2000] + "…(truncated)"
+ mismatch = HogQLParserShadowMismatch(
+ f"{rule} parser AST mismatch ({kind}): {primary_backend} vs {shadow_backend}\nstatement: {excerpt!r}"
+ )
if test_mode:
raise mismatch
- capture_exception(mismatch, additional_properties=divergence_properties)
+ capture_exception(
+ mismatch,
+ additional_properties={**divergence_properties, "hogql_parser_position_only_mismatch": position_only},
+ )
# Two caches so a flood of unique user-generated queries can't displace the
diff --git a/posthog/hogql/test/__snapshots__/parser_ast.ambr b/posthog/hogql/test/__snapshots__/parser_ast.ambr
index 9c89156166d5..0a3206f2e535 100644
--- a/posthog/hogql/test/__snapshots__/parser_ast.ambr
+++ b/posthog/hogql/test/__snapshots__/parser_ast.ambr
@@ -1298,6 +1298,26 @@
}
'''
# ---
+# name: test_byte_order_mark_does_not_break_parse[let_x_1-bccdb443]
+ '''
+ {
+ declarations: [
+ {
+ end: 10
+ expr: {
+ end: 10
+ start: 9
+ value: 1
+ }
+ name: "x"
+ start: 0
+ }
+ ]
+ end: 10
+ start: 0
+ }
+ '''
+# ---
# name: test_call_arg_select_releases_when_followed_by_keyword_infix[f_SELECT_1-bc5c7d75]
'''
{
@@ -8376,6 +8396,62 @@
}
'''
# ---
+# name: test_limit_by_then_limit_offset_position_stops_before_outer_offset[select_1_from_events_LIMIT_1_BY_event_LIMIT_2_OFFSET_3-eea0b59d]
+ '''
+ {
+ end: 45
+ limit: {
+ end: 45
+ start: 44
+ value: 2
+ }
+ limit_by: {
+ end: 37
+ exprs: [
+ {
+ chain: [
+ "event"
+ ]
+ end: 37
+ from_asterisk: False
+ start: 32
+ }
+ ]
+ n: {
+ end: 28
+ start: 27
+ value: 1
+ }
+ start: 21
+ }
+ offset: {
+ end: 54
+ start: 53
+ value: 3
+ }
+ select: [
+ {
+ end: 8
+ start: 7
+ value: 1
+ }
+ ]
+ select_from: {
+ end: 20
+ start: 14
+ table: {
+ chain: [
+ "events"
+ ]
+ end: 20
+ from_asterisk: False
+ start: 14
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
# name: test_limit_offset_with_ties_must_precede_offset[SELECT_a_FROM_t_LIMIT_1_2_WITH_TIES-f7bf5a57]
'''
{
@@ -9791,7 +9867,7 @@
declarations: [
{
catches: [
- [
+ (
"e",
None,
{
@@ -9799,7 +9875,7 @@
end: 19
start: 17
}
- ]
+ )
]
end: 19
start: 0
@@ -9821,7 +9897,7 @@
declarations: [
{
catches: [
- [
+ (
"e",
"T",
{
@@ -9829,7 +9905,7 @@
end: 22
start: 20
}
- ]
+ )
]
end: 22
start: 0
@@ -14928,6 +15004,195 @@
}
'''
# ---
+# name: test_template_string_top_level_carries_outer_span[Hello_TypeScript_arrayMap_a_a_1_2_3-46be7f64]
+ '''
+ {
+ args: [
+ {
+ end: 20
+ start: 2
+ value: "Hello, TypeScript "
+ },
+ {
+ args: [
+ {
+ args: [
+ "a"
+ ]
+ end: 36
+ expr: {
+ chain: [
+ "a"
+ ]
+ end: 36
+ from_asterisk: False
+ start: 35
+ }
+ start: 30
+ },
+ {
+ end: 47
+ exprs: [
+ {
+ end: 40
+ start: 39
+ value: 1
+ },
+ {
+ end: 43
+ start: 42
+ value: 2
+ },
+ {
+ end: 46
+ start: 45
+ value: 3
+ }
+ ]
+ start: 38
+ }
+ ]
+ distinct: False
+ end: 48
+ name: "arrayMap"
+ start: 21
+ },
+ {
+ end: 50
+ start: 49
+ value: "!"
+ }
+ ]
+ distinct: False
+ end: 50
+ name: "concat"
+ start: 0
+ }
+ '''
+# ---
+# name: test_template_string_top_level_carries_outer_span[Hello_arrayMap_a_a_1_2_3-c722f938]
+ '''
+ {
+ args: [
+ {
+ end: 9
+ start: 2
+ value: "Hello, "
+ },
+ {
+ args: [
+ {
+ args: [
+ "a"
+ ]
+ end: 25
+ expr: {
+ chain: [
+ "a"
+ ]
+ end: 25
+ from_asterisk: False
+ start: 24
+ }
+ start: 19
+ },
+ {
+ end: 36
+ exprs: [
+ {
+ end: 29
+ start: 28
+ value: 1
+ },
+ {
+ end: 32
+ start: 31
+ value: 2
+ },
+ {
+ end: 35
+ start: 34
+ value: 3
+ }
+ ]
+ start: 27
+ }
+ ]
+ distinct: False
+ end: 37
+ name: "arrayMap"
+ start: 10
+ },
+ {
+ end: 39
+ start: 38
+ value: "!"
+ }
+ ]
+ distinct: False
+ end: 39
+ name: "concat"
+ start: 0
+ }
+ '''
+# ---
+# name: test_template_string_top_level_carries_outer_span[hello-aaf4c61d]
+ '''
+ {
+ end: 7
+ start: 2
+ value: "hello"
+ }
+ '''
+# ---
+# name: test_template_string_top_level_carries_outer_span[true-b8fd8208]
+ '''
+ {
+ end: 7
+ start: 3
+ value: True
+ }
+ '''
+# ---
+# name: test_template_string_top_level_carries_outer_span[v_event_properties_lib_version-3939e081]
+ '''
+ {
+ args: [
+ {
+ end: 4
+ start: 2
+ value: "v="
+ },
+ {
+ chain: [
+ "event",
+ "properties",
+ "$lib_version"
+ ]
+ end: 34
+ from_asterisk: False
+ start: 5
+ }
+ ]
+ distinct: False
+ end: 35
+ name: "concat"
+ start: 0
+ }
+ '''
+# ---
+# name: test_template_string_top_level_carries_outer_span[x-5d653e7f]
+ '''
+ {
+ chain: [
+ "x"
+ ]
+ end: 4
+ from_asterisk: False
+ start: 3
+ }
+ '''
+# ---
# name: test_trailing_comma_after_joined_table_chain[SELECT_FROM_a_JOIN_b_ON_1-43ece755]
'''
{
@@ -15937,6 +16202,153 @@
}
'''
# ---
+# name: test_values_clause_in_from_carries_positions[SELECT_FROM_VALUES_1_a-487411e6]
+ '''
+ {
+ end: 31
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 31
+ start: 14
+ table: {
+ end: 30
+ rows: [
+ [
+ {
+ end: 24
+ start: 23
+ value: 1
+ },
+ {
+ end: 29
+ start: 26
+ value: "a"
+ }
+ ]
+ ]
+ start: 15
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_values_clause_in_from_carries_positions[SELECT_FROM_VALUES_1_a_AS_v_id_name-49f6b2eb]
+ '''
+ {
+ end: 46
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ alias: "v"
+ column_aliases: [
+ "id",
+ "name"
+ ]
+ end: 46
+ start: 14
+ table: {
+ end: 30
+ rows: [
+ [
+ {
+ end: 24
+ start: 23
+ value: 1
+ },
+ {
+ end: 29
+ start: 26
+ value: "a"
+ }
+ ]
+ ]
+ start: 15
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_values_clause_in_from_carries_positions[SELECT_FROM_VALUES_1_george_created_2_jack_deleted-4f07d09a]
+ '''
+ {
+ end: 71
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 71
+ start: 14
+ table: {
+ end: 70
+ rows: [
+ [
+ {
+ end: 24
+ start: 23
+ value: 1
+ },
+ {
+ end: 34
+ start: 26
+ value: "george"
+ },
+ {
+ end: 45
+ start: 36
+ value: "created"
+ }
+ ],
+ [
+ {
+ end: 50
+ start: 49
+ value: 2
+ },
+ {
+ end: 58
+ start: 52
+ value: "jack"
+ },
+ {
+ end: 69
+ start: 60
+ value: "deleted"
+ }
+ ]
+ ]
+ start: 15
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
# name: test_window_frame_between_falls_back_to_field[select_1_from_a_window_w_as_range_between_1_preceding_and_2_-74bc5cc4]
'''
{
diff --git a/posthog/hogql/test/__snapshots__/test_resolver.ambr b/posthog/hogql/test/__snapshots__/test_resolver.ambr
index 585fbb4349fe..2e4d62af3411 100644
--- a/posthog/hogql/test/__snapshots__/test_resolver.ambr
+++ b/posthog/hogql/test/__snapshots__/test_resolver.ambr
@@ -13063,7 +13063,11 @@
nullable: False
repeat: False
}
- value: (1, 2, 3)
+ value: (
+ 1,
+ 2,
+ 3
+ )
}
]
type: {
diff --git a/posthog/hogql/test/_test_parser.py b/posthog/hogql/test/_test_parser.py
index 66a00808be10..b6515c2f853d 100644
--- a/posthog/hogql/test/_test_parser.py
+++ b/posthog/hogql/test/_test_parser.py
@@ -11,7 +11,7 @@ import hashlib
from typing import Any, Optional, cast
import pytest
-from posthog.test.base import BaseTest, MemoryLeakTestMixin
+from posthog.test.base import BaseTest, MemoryLeakTestMixin, no_memory_leak_check
from unittest.mock import patch
from parameterized import parameterized
@@ -63,13 +63,20 @@ class _SharedParserSnapshotExtension(AmberSnapshotExtension):
@classmethod
def get_snapshot_name(cls, *, test_location: Any, index: Any = 0) -> str:
+ # Strip `parameterized.expand`'s `_<idx>` / `_<idx>_<name>` suffix so
+ # `test_foo_0_case_a` keys the same snapshot as the un-parametrized
+ # `test_foo`. The `_assert_ast` snapshot key is the SOURCE STRING via
+ # `_snapshot_key(src)` — so a parameterized variant carrying the same
+ # `src` should reuse the same snapshot regardless of method-name
+ # decoration.
+ base_method = re.sub(r"_\d+(?:_[A-Za-z0-9_]+)?$", "", test_location.methodname)
if isinstance(index, str):
index_suffix = f"[{index}]"
elif index:
index_suffix = f".{index}"
else:
index_suffix = ""
- return f"{test_location.methodname}{index_suffix}"
+ return f"{base_method}{index_suffix}"
def _snapshot_key(src: str) -> str:
@@ -366,7 +373,11 @@ def parser_test_factory(backend: HogQLParserBackend):
self.assertEqual(self._expr(f"1{space}+{space}2"), self._expr("1 + 2"))
def test_byte_order_mark_does_not_break_parse(self):
- # A file saved with a leading UTF-8 byte-order mark still parses.
+ # A file saved with a leading UTF-8 byte-order mark still parses, AND the BOM is zero-width to cpp's
+ # ANTLR lexer: every char offset is reckoned from the char AFTER the BOM. `_assert_ast` pins the exact
+ # span (via the cross-backend snapshot) so a parser that counts the BOM as 1 char (rust's natural
+ # `byte_to_char_index` behaviour, before the leading-BOM adjustment) fails here.
+ self._assert_ast("let x := 1", "program")
self.assertEqual(self._program("let x := 1"), self._program("let x := 1"))
def test_booleans(self):
@@ -4837,6 +4848,16 @@ def parser_test_factory(backend: HogQLParserBackend):
for src in cases:
self._assert_ast(src, "select")
+ def test_limit_by_then_limit_offset_position_stops_before_outer_offset(self):
+ # `selectStmt: ... limitByClause? (limitAndOffsetClause | offsetOnlyClause)?`
+ # `limitAndOffsetClause` lists compact (no OFFSET) before verbose (with OFFSET),
+ # so ANTLR ALL(*) picks compact for the trailing `LIMIT n` after limit-by — the
+ # `OFFSET m` belongs to the outer `selectSetStmt`'s `limitAndOffsetClauseOptional`,
+ # and the inner SelectQuery's source span stops at the LIMIT, not the OFFSET.
+ # Pinned so a regression that greedily eats OFFSET inside selectStmt — extending
+ # the SelectQuery end past the trailing OFFSET — fails here.
+ self._assert_ast("select 1 from events LIMIT 1 BY event LIMIT 2 OFFSET 3", "select")
+
def test_zero_arg_lambda_as_clause_body(self):
# After `,`, a clause-keyword + `()->` is a lambda clause body; bare `()` makes the keyword a column.
cases = (
@@ -4878,6 +4899,59 @@ def parser_test_factory(backend: HogQLParserBackend):
for src in cases:
self._assert_ast(src, "select")
+ @parameterized.expand(
+ [
+ # `tableExpr: LPAREN valuesClause RPAREN` — the ValuesQuery node spans the
+ # inner `VALUES (...)` (cpp's valuesClause ctx), not the stripped outer
+ # parens. Pinned with positions so a regression that drops the span (or
+ # wraps the outer parens) fails here on rust / rust-py.
+ ("no_alias", "SELECT * FROM (VALUES (1, 'a'))"),
+ ("alias_with_columns", "SELECT * FROM (VALUES (1, 'a')) AS v(id, name)"),
+ (
+ "multi_row_tuples",
+ "SELECT * FROM (VALUES (1, 'george', 'created'), (2, 'jack', 'deleted'))",
+ ),
+ ]
+ )
+ def test_values_clause_in_from_carries_positions(self, _name: str, src: str) -> None:
+ self._assert_ast(src, "select")
+
+ @no_memory_leak_check # re-clears positions per run (allocates); correctness pin, runs once
+ def test_internal_parse_emits_no_positions(self):
+ # `parse_expr(..., start=None)` is cpp's `is_internal` mode: a synthetic
+ # fragment (e.g. an injected database `ExpressionField`) has no meaningful
+ # source span, so cpp gates off every `addPositionInfo` and every node is
+ # position-less. All backends must match — a backend that emits spans here
+ # diverges from cpp on the many queries that join through person overrides.
+ src = "if(not(empty(override.distinct_id)), override.person_id, event_person_id)"
+ internal = parse_expr(src, start=None, backend=backend)
+ positioned = parse_expr(src, start=0, backend=backend)
+ self.assertEqual(internal, clear_locations(positioned))
+ self.assertIsNone(internal.start)
+ self.assertIsNone(internal.end)
+
+ @parameterized.expand(
+ [
+ # `parse_full_template_string` returns the result of the body splitter — a multi-chunk
+ # `concat(...)` or a single chunk. cpp positions by chunk count: the multi-chunk wrapper
+ # spans the whole `F'…'` input (rule ctx), but a single-chunk shortcut keeps the inner
+ # element's own span (literal text or substitution expr). Both shapes pinned so a
+ # regression that wraps unconditionally (clobbering the single-chunk span) — or that
+ # drops the multi-chunk wrap — fails here.
+ # multi-chunk → outer span (0..len(src))
+ ("multi_arraymap_bang", "Hello, {arrayMap(a -> a, [1, 2, 3])}!"),
+ ("multi_lib_version", "v={event.properties.$lib_version}"),
+ ("multi_typescript_arraymap", "Hello, TypeScript {arrayMap(a -> a, [1, 2, 3])}!"),
+ # single literal → wrap_literal_chunk span (body_offset..body_end)
+ ("single_literal_hello", "hello"),
+ # single substitution → inner expr span (only the placeholder body)
+ ("single_substitution_field", "{x}"),
+ ("single_substitution_bool", "{true}"),
+ ]
+ )
+ def test_template_string_top_level_carries_outer_span(self, _name: str, src: str) -> None:
+ self._assert_ast(src, "template")
+
def test_columns_macro_asterisk_form_as_list_element(self):
# `COLUMNS(…)` tries `columnExprList` before `* EXCLUDE` / `id.* …`, so an asterisk-form + postfix call is `ColumnsList(ExprCall(asterisk-form))`.
cases = (
diff --git a/posthog/hogql/test/test_parser_rust_py.py b/posthog/hogql/test/test_parser_rust_py.py
index cb8541c248a7..75184b1dd0a2 100644
--- a/posthog/hogql/test/test_parser_rust_py.py
+++ b/posthog/hogql/test/test_parser_rust_py.py
@@ -9,24 +9,8 @@ dataclass instances directly, skipping the JSON round-trip).
from ._test_parser import parser_test_factory
-# `ast.Dict.items` is typed `list[tuple[Expr, Expr]]`. The direct-PyO3 path
-# builds tuples (matching the annotation); the JSON oracle (cpp-json) builds
-# lists, since JSON has no tuple type. These two tests assert full AST parity
-# against the JSON oracle, so the list-vs-tuple shape diverges — a serialisation
-# representation difference, not a parser-behaviour one. Deferred for rust-py
-# rather than reshaping the JSON deserialiser (which the oracle shares).
-_DEFERRED: set[str] = {
- "test_block_then_empty_param_lambda_is_two_statements",
- "test_statement_leading_brace_block_vs_call",
-}
-
class TestParserRustPy(parser_test_factory("rust-py")): # type: ignore
- def setUp(self) -> None:
- super().setUp()
- if self._testMethodName in _DEFERRED:
- self.skipTest("Dict.items list (JSON oracle) vs tuple (direct PyO3) representation difference")
-
def test_empty(self):
# this test only exists to make pycharm recognise this class as a test class
# the actual tests are in the parent class
diff --git a/posthog/hogql/test/utils.py b/posthog/hogql/test/utils.py
index d307236e876c..7dbe9f0daba8 100644
--- a/posthog/hogql/test/utils.py
+++ b/posthog/hogql/test/utils.py
@@ -77,6 +77,14 @@ def pretty_dataclasses(obj, seen=None, indent=0):
elements = [pretty_dataclasses(item, seen, indent + 2) for item in obj]
return "[\n" + ",\n".join(next_indent + element for element in elements) + "\n" + indent_space + "]"
+ elif isinstance(obj, tuple):
+ # AST fields typed `list[tuple[...]]` (Dict.items, TryCatchStatement.catches) — render
+ # tuple as `(...)` so snapshots distinguish it from list at the same level.
+ if len(obj) == 0:
+ return "()"
+ elements = [pretty_dataclasses(item, seen, indent + 2) for item in obj]
+ return "(\n" + ",\n".join(next_indent + element for element in elements) + "\n" + indent_space + ")"
+
elif isinstance(obj, dict):
if len(obj) == 0:
return "{}"
diff --git a/pyproject.toml b/pyproject.toml
index 71d50b7112ab..e46697a398f3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,7 +68,7 @@ dependencies = [
"grpcio~=1.71.0",
"gspread==6.2.1",
"hogql-parser==1.3.69",
- "hogql-parser-rs==1.3.75", # built from rust/hogql/parser via the build-hogql-parser-rs workflow + published to PyPI; rebuild locally with `uv pip install -e rust/hogql/parser` when iterating
+ "hogql-parser-rs==1.3.81", # built from rust/hogql/parser via the build-hogql-parser-rs workflow + published to PyPI; rebuild locally with `uv pip install -e rust/hogql/parser` when iterating
"humanize~=4.12.3",
"infi-clickhouse-orm",
"jsonref==1.1.0",
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 1d3c37594551..850c11fe966e 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4152,7 +4152,7 @@ dependencies = [
[[package]]
name = "hogql_parser_rs"
-version = "1.3.75"
+version = "1.3.81"
dependencies = [
"pyo3",
"serde_json",
diff --git a/rust/hogql/parser/Cargo.toml b/rust/hogql/parser/Cargo.toml
index 01150a2274e2..9cd00f6a8814 100644
--- a/rust/hogql/parser/Cargo.toml
+++ b/rust/hogql/parser/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "hogql_parser_rs"
-# Versioned independently from the cpp parser in `common/hogql_parser/setup.py`. Both started from the same HogQL grammar revision, but the Rust port is bumped on its own whenever the hand-rolled parser changes (cpp is currently 1.3.69, this is 1.3.75); each ships as its own PyPI wheel.
-version = "1.3.75"
+# Versioned independently from the cpp parser in `common/hogql_parser/setup.py`. Both started from the same HogQL grammar revision, but the Rust port is bumped on its own whenever the hand-rolled parser changes (cpp is currently 1.3.69, this is 1.3.81); each ships as its own PyPI wheel.
+version = "1.3.81"
edition = "2021"
publish = false
diff --git a/rust/hogql/parser/README.md b/rust/hogql/parser/README.md
index bf24a925ee11..483eb2c55765 100644
--- a/rust/hogql/parser/README.md
+++ b/rust/hogql/parser/README.md
@@ -269,10 +269,13 @@ landing.
### Shadow compare in TEST via `cpp-with-rust-shadow`
In `TEST` mode the default backend is `cpp-with-rust-shadow`: both
-backends parse, ASTs are compared, mismatches **raise** so the failing
-test points right at the offending query. In production this same
-mode runs at a 1% sample and only logs. Useful when a regression
-slips past the PBT but shows up in the suite.
+backends parse, ASTs are compared **including per-node `start` / `end`
+positions** (matching the diagnostics' default), mismatches **raise**
+so the failing test points right at the offending query. In production
+this same mode runs at a 1% sample and only logs — a mismatch there is
+tagged `hogql_parser_position_only_mismatch` so position-only
+divergences are triaged apart from structural ones. Useful when a
+regression slips past the PBT but shows up in the suite.
```python
from posthog.hogql.constants import HogQLParserBackend
diff --git a/rust/hogql/parser/pyproject.toml b/rust/hogql/parser/pyproject.toml
index 51897563084f..edc062bfaff0 100644
--- a/rust/hogql/parser/pyproject.toml
+++ b/rust/hogql/parser/pyproject.toml
@@ -8,8 +8,8 @@ build-backend = "maturin"
[project]
name = "hogql_parser_rs"
-# Mirrors `rust/hogql/parser/Cargo.toml` (always identical). Tracks but is NOT locked to `common/hogql_parser/setup.py`: the Rust port is versioned independently and bumped on its own whenever the hand-rolled parser changes (cpp is currently 1.3.69, this is 1.3.75).
-version = "1.3.75"
+# Mirrors `rust/hogql/parser/Cargo.toml` (always identical). Tracks but is NOT locked to `common/hogql_parser/setup.py`: the Rust port is versioned independently and bumped on its own whenever the hand-rolled parser changes (cpp is currently 1.3.69, this is 1.3.81).
+version = "1.3.81"
description = "Hand-rolled Rust HogQL parser with C++-parity AST output"
readme = "README.md"
requires-python = ">=3.12"
diff --git a/rust/hogql/parser/src/emit_py.rs b/rust/hogql/parser/src/emit_py.rs
index e58b8ef72748..390a3fd86d27 100644
--- a/rust/hogql/parser/src/emit_py.rs
+++ b/rust/hogql/parser/src/emit_py.rs
@@ -768,12 +768,13 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_variable_declaration, &kw)
}
fn catch_clause(&self, var: PyAst, ty: PyAst, body: PyAst) -> PyAst {
- // cpp emits this as a `[var, type, body]` JSON array — we mirror the shape on Py since `TryCatchStatement.catches` is `list[list[Expr | Type | Block]]`.
- let list = PyList::empty_bound(self.py);
- list.append(var.obj).unwrap();
- list.append(ty.obj).unwrap();
- list.append(body.obj).unwrap();
- self.wrap_prim(list.into_any().unbind())
+ // cpp emits this as a `[var, type, body]` JSON array; the Python AST types
+ // `TryCatchStatement.catches` as `list[tuple[Optional[str], Optional[str], Statement]]`
+ // (matching what `CloningVisitor.visit_try_catch_statement` builds and what
+ // `json_ast._TUPLE_INNER_FIELDS` now deserialises cpp/rust-json arrays into).
+ // Build a tuple here so `rust-py` produces the canonical shape directly.
+ let pair = PyTuple::new_bound(self.py, [var.obj, ty.obj, body.obj]);
+ self.wrap_prim(pair.into_any().unbind())
}
// ===== Query / clause builders =====
diff --git a/rust/hogql/parser/src/parse.rs b/rust/hogql/parser/src/parse.rs
index ce29dcffcd36..5e61ea75679d 100644
--- a/rust/hogql/parser/src/parse.rs
+++ b/rust/hogql/parser/src/parse.rs
@@ -44,9 +44,10 @@ pub fn parse_expr(src: &str, is_internal: bool) -> Result<Value, ParseError> {
pub fn parse_expr_with_emit<E: Emitter + Clone>(
emit: E,
src: &str,
- _is_internal: bool,
+ is_internal: bool,
) -> Result<E::Value, ParseError> {
let mut p = Parser::new_with_emit(src, emit)?;
+ p.suppress_pos = is_internal;
// Bare-list lambda `IDENT (, IDENT)* -> body` is only valid at the
// outermost expression level; inside an argument list each item parses
// independently and the commas are separators. So we try it here
@@ -153,7 +154,16 @@ pub fn parse_full_template_string_with_emit<E: Emitter + Clone>(
// `body_offset` and `body_end`. For the standalone entry point the
// body extends to the end of `src` — there is no trailing `'`.
let body_end = src.len();
- parse_template_body(&emit, src, body_offset, body_end)
+ let result = parse_template_body(&emit, src, body_offset, body_end)?;
+ // cpp positions the result by chunk count: a multi-chunk `concat(...)`
+ // gets the outer rule-ctx span `(0, src.len())`, while a single-chunk
+ // shortcut keeps the inner element's own span (the literal text or the
+ // substitution expr). `with_pos` is idempotent — it sets `(0, src.len())`
+ // on the position-less `concat` and is a no-op on the already-positioned
+ // single-chunk cases.
+ let start_pos = template::pos_in_source(&emit, src, 0);
+ let end_pos = template::pos_in_source(&emit, src, src.len());
+ Ok(emit.with_pos(result, start_pos, end_pos))
}
// ============================================================================
@@ -304,6 +314,18 @@ pub(crate) struct Parser<'a, E: Emitter = JsonEmitter> {
pub(crate) is_ascii_src: bool,
/// Live recursive-descent depth shared across expression / subquery / statement nesting; bumped on entry to each recursive entry point, decremented on exit. Enforces `MAX_RECURSION_DEPTH`.
pub(crate) recursion_depth: u32,
+ /// When set, every node is emitted position-less (`pos_obj` returns
+ /// `null`). Mirrors cpp's `is_internal` flag, which gates every
+ /// `addPositionInfo(json, ctx)` call: a synthetic fragment parsed with
+ /// `start=None` (e.g. an injected database `ExpressionField`) carries no
+ /// meaningful source spans, so cpp emits none and we must match.
+ pub(crate) suppress_pos: bool,
+ /// UTF-8 byte length of a leading BOM (3) or 0 if none. cpp's ANTLR
+ /// lexer treats a leading `U+FEFF` as zero-width: every emitted char
+ /// offset is reckoned from the char AFTER the BOM, so `let` at byte 3
+ /// gets char offset 0 (not 1). `pos_obj` subtracts this width past the
+ /// BOM so rust matches.
+ pub(crate) leading_bom_bytes: usize,
/// AST node builder. Routes every node/position construction through the `Emitter` trait so we can swap `JsonEmitter` (current default, kept for WASM) for `PyEmitter` (constructs Python ast.* objects directly, avoiding the `serde_json::Value` intermediate). See `crate::emit`.
pub(crate) emit: E,
}
@@ -343,6 +365,8 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
char_offsets: std::cell::OnceCell::new(),
is_ascii_src,
recursion_depth: 0,
+ suppress_pos: false,
+ leading_bom_bytes: if src.starts_with('\u{FEFF}') { 3 } else { 0 },
emit,
})
}
@@ -462,6 +486,15 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
/// character-based, so byte offsets need converting through `src`
/// slicing for any source containing non-ASCII bytes.
pub(crate) fn pos_obj(&self, byte_offset: usize) -> E::Value {
+ // `is_internal` parses (cpp's term) emit no positions at all — every
+ // node stays at its dataclass `start`/`end` default. Returning `null`
+ // here is the single chokepoint: `with_pos` / `replace_pos` then leave
+ // the node bare (json `start:null` → None; py setattr of None is a
+ // no-op on the already-None default), matching cpp's `!is_internal`
+ // gate on `addPositionInfo`.
+ if self.suppress_pos {
+ return self.emit.null();
+ }
let (line, byte_col, line_start_byte) = offset_to_line_col(&self.line_starts, byte_offset);
// ASCII fast path: byte == char in every dimension. Avoid the
// `byte_to_char_index` binary search and the line-slice chars
@@ -469,15 +502,25 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
if self.is_ascii_src {
return self.emit.position(line, byte_col, byte_offset);
}
- let char_offset = self.byte_to_char_index(byte_offset);
+ let mut char_offset = self.byte_to_char_index(byte_offset);
// Column needs to be characters-in-line, not bytes-in-line. For
// lines with multi-byte chars we count chars between the line
// start and the offset.
- let column = if byte_col == 0 {
+ let mut column = if byte_col == 0 {
0
} else {
self.src[line_start_byte..byte_offset].chars().count() as u32
};
+ // cpp's ANTLR lexer treats a leading UTF-8 BOM (`U+FEFF`, 3 bytes / 1 char) as zero-width: every char offset
+ // it reports is reckoned from the char AFTER the BOM, and the BOM contributes no column on line 1. Mirror
+ // that here past the BOM byte boundary — without this, every offset is `+1` and a BOM-prefixed source
+ // diverges from cpp at every node.
+ if self.leading_bom_bytes > 0 && byte_offset >= self.leading_bom_bytes {
+ char_offset = char_offset.saturating_sub(1);
+ if line == 1 {
+ column = column.saturating_sub(1);
+ }
+ }
self.emit.position(line, column, char_offset)
}
diff --git a/rust/hogql/parser/src/parse/join.rs b/rust/hogql/parser/src/parse/join.rs
index e43ae1030196..f3be64de7f8f 100644
--- a/rust/hogql/parser/src/parse/join.rs
+++ b/rust/hogql/parser/src/parse/join.rs
@@ -933,6 +933,11 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
/// reference is expected. The caller has already consumed the leading
/// `(` if any; we consume the `VALUES` keyword and emit a ValuesQuery.
fn parse_values_query(&mut self) -> Result<E::Value, ParseError> {
+ // cpp's `valuesClause` ctx spans `VALUES` through the final row's
+ // `)`, so position from the VALUES keyword to `last_consumed_end`
+ // (after the last `)` the loop consumes) — not the outer parens the
+ // caller strips.
+ let start = self.peek0.start;
self.expect_kw(Kw::Values, "VALUES")?;
let mut rows: Vec<E::Value> = Vec::new();
loop {
@@ -944,7 +949,8 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
break;
}
}
- Ok(self.emit.values_query(rows))
+ let values = self.emit.values_query(rows);
+ Ok(self.wrap_pos(values, start))
}
/// `SAMPLE ratioExpr PERCENT? (OFFSET ratioExpr)? (LPAREN ident RPAREN)?`
diff --git a/rust/hogql/parser/src/parse/select.rs b/rust/hogql/parser/src/parse/select.rs
index fbe6d22f5d7d..bfbebb719cbb 100644
--- a/rust/hogql/parser/src/parse/select.rs
+++ b/rust/hogql/parser/src/parse/select.rs
@@ -1133,22 +1133,23 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
.set_field(obj, "limit_with_ties", self.emit.bool(true));
}
} else {
- // Verbose form (or no second operand).
+ // After LIMIT BY's trailing LIMIT n, ANTLR ALL(*) picks
+ // `limitAndOffsetClause`'s compact alt — `LIMIT n PERCENT?
+ // (COMMA m)? (WITH TIES)?` — over verbose (which would
+ // consume OFFSET) because compact is listed first in the
+ // grammar. So we stop here even if `OFFSET m` follows; the
+ // outer `selectSetStmt`'s `limitAndOffsetClauseOptional`
+ // picks it up, and `merge_select_decorators` attaches it
+ // to the inner SelectQuery — keeping the inner's position
+ // span stopping before OFFSET, matching cpp's selectStmt
+ // ctx. Verbose-form `__rust_offset_liftable` is never set
+ // here: limit-by's trailing OFFSET stays on the inner.
if self.peek_kw2(Kw::With, Kw::Ties) {
self.bump()?;
self.bump()?;
self.emit
.set_field(obj, "limit_with_ties", self.emit.bool(true));
}
- if self.eat_kw(Kw::Offset)? {
- let _v = self.parse_expr_bp(0)?;
- self.emit.set_field(obj, "offset", _v);
- // Sentinel for the SelectSetStmt wrapper's
- // conditional lift logic — only the verbose form
- // is liftable.
- self.emit
- .set_field(obj, "__rust_offset_liftable", self.emit.bool(true));
- }
}
} else if self.eat_kw(Kw::Offset)? {
// Bare `OFFSET m` (no preceding LIMIT). cpp keeps this on
diff --git a/rust/hogql/parser/src/parse/template.rs b/rust/hogql/parser/src/parse/template.rs
index e7a2d58584fd..fff6bb915fb4 100644
--- a/rust/hogql/parser/src/parse/template.rs
+++ b/rust/hogql/parser/src/parse/template.rs
@@ -299,7 +299,7 @@ fn wrap_literal_chunk<E: Emitter>(
/// absolute byte offset in `src`. `offset` is the character index
/// (Unicode code points), matching cpp's ANTLR `getStartIndex()`
/// semantics; `column` is character-position-in-line.
-fn pos_in_source<E: Emitter>(emit: &E, src: &str, byte_offset: usize) -> E::Value {
+pub(crate) fn pos_in_source<E: Emitter>(emit: &E, src: &str, byte_offset: usize) -> E::Value {
// Line: count `\n` bytes before `byte_offset`.
let preceding = &src[..byte_offset.min(src.len())];
let line_breaks = preceding.bytes().filter(|&b| b == b'\n').count();
diff --git a/uv.lock b/uv.lock
index 3dd4749b1bb9..4cbc2d5d501b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -11,7 +11,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "2026-05-19T19:35:56.17510417Z"
+exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -3025,16 +3025,16 @@ wheels = [
[[package]]
name = "hogql-parser-rs"
-version = "1.3.75"
+version = "1.3.81"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/0a/b1/744526df944b4b2675edacc9b9c100f97e964d62dd62d1b7ea566ed73110/hogql_parser_rs-1.3.75.tar.gz", hash = "sha256:2607eedc28004e45e03910e6f76502b1fd1757bd69d2ca768ef5ebde98e7a78f", size = 279337, upload-time = "2026-05-26T18:32:39.741Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/c6/63/fd42a45e67192ee549753522974b07ed0b379db6a7f618089a11be812279/hogql_parser_rs-1.3.81.tar.gz", hash = "sha256:8480ea04f3a36539540c4ec0ae454908874881b54aa9ed8d7f1734bc64c20afb", size = 280808, upload-time = "2026-05-29T09:42:04.978Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/bf/47/9d941887c7c9f4bbd4757d35a23e9214207e0f2ffb8edefee59ce77df2a0/hogql_parser_rs-1.3.75-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e6c3c6a1941ec5991853c7304861c40430004f9db0f07836b79bcc569a47d0f2", size = 727452, upload-time = "2026-05-26T18:32:29.964Z" },
- { url = "https://files.pythonhosted.org/packages/a6/aa/d9e38b03b6a09dbdca6d87ea8ba8beb350f30382346c050fd9515037c374/hogql_parser_rs-1.3.75-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:7bb55e490ce617ddaea009f2bedcbfa7c620c9912f5e017ba6949cd0c410bae4", size = 685286, upload-time = "2026-05-26T18:32:31.942Z" },
- { url = "https://files.pythonhosted.org/packages/8e/72/738099fef905ebab38d9cec09665883f1fe85267e5e8cc81d755f53d880c/hogql_parser_rs-1.3.75-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:9bc361647c9b7524a5046f10671100937e3183f703efedcbbfc141c9e73139c1", size = 2472142, upload-time = "2026-05-26T18:32:33.411Z" },
- { url = "https://files.pythonhosted.org/packages/d1/cb/3e2a9f3e4a5e8e3d9041f868031bb72ed8ae0b69cfd16d424ffcda285680/hogql_parser_rs-1.3.75-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:360b29ae4bec41bdfd783f69c476f38c3eebaebd200effd6aa3965855c2040be", size = 2733287, upload-time = "2026-05-26T18:32:34.985Z" },
- { url = "https://files.pythonhosted.org/packages/07/6a/3d9671f911d5fd59616f12a4df07d4c889a076bea89d379005ca9c5d57b1/hogql_parser_rs-1.3.75-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:d07a4a38f30745264fc8d6b11bc3a4205f33a3277c8c2fed8c6f352dffb05308", size = 2645445, upload-time = "2026-05-26T18:32:36.447Z" },
- { url = "https://files.pythonhosted.org/packages/49/97/06407d8accdf8c8a8f73912b838a611ab88386430e657c9056e112473888/hogql_parser_rs-1.3.75-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6ef7eae9924db9d324d7752eaad4941bc96475fa3ac8831ffad323435d9bbe4f", size = 2697696, upload-time = "2026-05-26T18:32:38.085Z" },
+ { url = "https://files.pythonhosted.org/packages/49/37/72fe3743427d19353c242c40f17a5bf56723e4f145a6ef0d44d12ac75e74/hogql_parser_rs-1.3.81-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:f609d9e80c5644062b2c0cf810801d323fc1ffcee57d1603fc015b50d49580a9", size = 727518, upload-time = "2026-05-29T09:41:54.677Z" },
+ { url = "https://files.pythonhosted.org/packages/1e/05/3c485befaaa3f6faecd9c9669c56b31e95a662fd896c789c215ed8cadfa2/hogql_parser_rs-1.3.81-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:2c46e57150a77887e9598fb558b06953f307f08692833222c48935d9c79947ac", size = 685509, upload-time = "2026-05-29T09:41:56.439Z" },
+ { url = "https://files.pythonhosted.org/packages/a7/d5/1dda7641f13c1144ac6c8bb8041adb97ca9e100c07bf57bd08ad2208a4de/hogql_parser_rs-1.3.81-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:12f8c4ce20f3ce6f5fbb7b07b635c80a71cc9146bc6e959aa979c6eb563b3eef", size = 2474357, upload-time = "2026-05-29T09:41:58.016Z" },
+ { url = "https://files.pythonhosted.org/packages/51/00/2b822a49f6078251ab290c08123541dc56e884f83f5ee8a4bd7486dd994c/hogql_parser_rs-1.3.81-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:edbc88076ce9cc97f744fffba36c4eee32f67e2f9bae6d334d62730d6738bb94", size = 2734306, upload-time = "2026-05-29T09:41:59.838Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/ef/4ff4db6253f18b6398adf68296a59cc88f09e0a3cfd295f534e24dcf02d5/hogql_parser_rs-1.3.81-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fff27c1a03433bf18ac6d8e317a7a8aaee1f428833bd2a6bc2021b42d17a1a66", size = 2646821, upload-time = "2026-05-29T09:42:01.612Z" },
+ { url = "https://files.pythonhosted.org/packages/96/13/43861d5b1bd04bf74400de33b639f09c518844439fdbed4f370d2815b40c/hogql_parser_rs-1.3.81-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:c0c064123b39773e9a5591c5f3c9f275238471404a76a9eeb9560e567eb24b91", size = 2697834, upload-time = "2026-05-29T09:42:03.375Z" },
]
[[package]]
@@ -5566,7 +5566,7 @@ requires-dist = [
{ name = "grpcio", specifier = "~=1.71.0" },
{ name = "gspread", specifier = "==6.2.1" },
{ name = "hogql-parser", specifier = "==1.3.69" },
- { name = "hogql-parser-rs", specifier = "==1.3.75" },
+ { name = "hogql-parser-rs", specifier = "==1.3.81" },
{ name = "humanize", specifier = "~=4.12.3" },
{ name = "infi-clickhouse-orm", git = "https://github.com/PostHog/infi.clickhouse_orm?rev=4e3996becf66bf5c26580aff12a80425d9d56fe5" },
{ name = "jsonref", specifier = "==1.1.0" },