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.

fix(hogql): rust parser handles paren-led non-first CTE expressions (#62201)

George Munyorofe27f48cbc96
diff --git a/posthog/hogql/test/_test_parser.py b/posthog/hogql/test/_test_parser.py
index b6515c2f853d..ea926a77ad6f 100644
--- a/posthog/hogql/test/_test_parser.py
+++ b/posthog/hogql/test/_test_parser.py
@@ -2823,6 +2823,35 @@ def parser_test_factory(backend: HogQLParserBackend):
),
)
+ @parameterized.expand(
+ [
+ # A non-first CTE whose column-form expression begins with a paren group
+ # followed by an operator tail. The CTE-list disambiguation must look past
+ # the paren group to the top-level `AS <ident>` alias; an early version of
+ # the rust parser stopped at the matching `)` and mis-parsed the remainder
+ # as the enclosing SELECT's paren.
+ ("operator_tail_after_paren_group", "WITH 5 AS a, 2 AS b, (a - b) * 10 AS c SELECT c", ["a", "b", "c"]),
+ ("single_paren_then_operator", "WITH 1 AS a, (a) + 1 AS c SELECT c", ["a", "c"]),
+ ("both_ctes_paren_led", "WITH (a - b) AS c, (c) * 2 AS d SELECT d", ["c", "d"]),
+ ("scalar_subquery_in_expression", "WITH 1 AS a, (SELECT 2) + 1 AS c SELECT c", ["a", "c"]),
+ (
+ "paren_then_property_access",
+ "WITH x AS (SELECT 1 AS n), (x.n) * 2 AS y SELECT y FROM x",
+ ["x", "y"],
+ ),
+ # Disambiguation that must be preserved: an alias directly after the paren
+ # group is still a CTE, and a trailing-comma paren main query (no alias)
+ # must terminate the CTE list rather than be swallowed as a CTE.
+ ("immediate_alias_after_paren", "WITH 1 AS a, (a) AS c SELECT c", ["a", "c"]),
+ ("immediate_alias_after_subquery", "WITH 1 AS a, (SELECT 2) AS c SELECT c", ["a", "c"]),
+ ("trailing_comma_paren_main_query", "WITH 1 AS a, (SELECT 2)", ["a"]),
+ ]
+ )
+ def test_paren_led_cte_disambiguation(self, _name: str, query: str, expected_ctes: list[str]):
+ node = cast(ast.SelectQuery, self._select(query))
+ assert isinstance(node.ctes, dict)
+ self.assertEqual(sorted(node.ctes.keys()), sorted(expected_ctes))
+
def test_grammar_quirk_invalid_join_type_rejected_on_all_backends(self):
# `LEFT OUTER SEMI JOIN` passes the rust grammar's per-keyword checks (no rule forbids the combination) but isn't in `VALID_JOIN_TYPES`, so `JoinExpr.__post_init__` raises `ValueError` on every backend. rust-py writes `join_type` post-construction (via `chain_join`), so `PyEmitter::set_field` re-fires `__post_init__` and restores the original exception — surfacing the same `ValueError` the json backends raise from `cls(**kwargs)`.
q = "SELECT 1 FROM a LEFT OUTER SEMI JOIN b ON a.x = b.x"
diff --git a/pyproject.toml b/pyproject.toml
index 5908ca224a9b..a5dd6e1a4980 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.82", # 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.84", # 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 dec9ed121931..29a317f86542 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4348,7 +4348,7 @@ dependencies = [
[[package]]
name = "hogql_parser_rs"
-version = "1.3.82"
+version = "1.3.84"
dependencies = [
"pyo3",
"serde_json",
diff --git a/rust/hogql/parser/Cargo.toml b/rust/hogql/parser/Cargo.toml
index c55e5702ae03..c753e3bb9e8b 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.82); each ships as its own PyPI wheel.
-version = "1.3.82"
+# 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.84); each ships as its own PyPI wheel.
+version = "1.3.84"
edition = "2021"
publish = false
diff --git a/rust/hogql/parser/pyproject.toml b/rust/hogql/parser/pyproject.toml
index 898ea1ff7eae..357a6fad62ad 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.82).
-version = "1.3.82"
+# 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.84).
+version = "1.3.84"
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/parse/cte.rs b/rust/hogql/parser/src/parse/cte.rs
index c9dc5fb4b073..d1e5c00bfe9b 100644
--- a/rust/hogql/parser/src/parse/cte.rs
+++ b/rust/hogql/parser/src/parse/cte.rs
@@ -22,8 +22,8 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// that terminates the CTE list; mirror that. A bare `LPAREN`
// following the comma can ALSO be the leading `(` of the next
// CTE element (column-form `(SELECT 1) AS x` / `(a + b) AS y`),
- // so peek past the matching `)` to see if an `AS identifier`
- // pattern follows before terminating the loop.
+ // so peek past the paren group's expression to see if an
+ // `AS identifier` alias follows before terminating the loop.
let mut out = Vec::new();
loop {
out.push(self.parse_with_expr()?);
@@ -33,48 +33,64 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
if matches!(self.peek(), TokenKind::Keyword(Kw::Select)) {
break;
}
- if self.peek() == TokenKind::LParen && !self.paren_group_followed_by_as_identifier() {
+ if self.peek() == TokenKind::LParen && !self.paren_led_column_cte_follows() {
break;
}
}
Ok(out)
}
- /// `self.peek()` is `(`. Probe whether the matching `)` is followed
- /// by an `AS identifier` pattern — the shape that marks the paren
- /// group as the head of the next column-form CTE
- /// (`(SELECT 1) AS x`, `(a + b) AS y`) rather than the leading
- /// paren of the enclosing SELECT statement.
- fn paren_group_followed_by_as_identifier(&self) -> bool {
+ /// `self.peek()` is `(`. Probe whether this paren group heads a
+ /// column-form CTE — i.e. a top-level `AS identifier` alias follows
+ /// the expression it begins — rather than being the leading paren of
+ /// the enclosing SELECT statement.
+ ///
+ /// The paren group can be the whole expression (`(a + b) AS y`,
+ /// `(SELECT 1) AS x`) or just its head, with an operator tail
+ /// before the alias (`(a - b) * 10 AS y`, `(SELECT n) + 1 AS y`).
+ /// Either way the distinguishing mark is a depth-0 `AS <ident>`:
+ /// the alias of a column-form CTE. We scan forward and return true
+ /// on the first depth-0 `AS <ident>`. A trailing-comma main query
+ /// (`WITH a AS 1, (SELECT 2)`) has no such alias, so we stop at
+ /// EOF, a depth-0 comma, or a `)` that closes past the leading
+ /// paren (the enclosing query's own paren).
+ fn paren_led_column_cte_follows(&self) -> bool {
let mut probe = Lexer::with_pos(self.src, self.peek0.end);
+ // Depth starts at 1: the leading `(` has been consumed by the
+ // caller's `peek`. `AS`/`,` inside the paren group (tuple
+ // commas, `CAST(x AS t)`, nested subqueries) sit at depth >= 1
+ // and are skipped; only a depth-0 `AS` is the CTE alias.
let mut depth: i32 = 1;
- while depth > 0 {
- let tok = match probe.next_token() {
- Ok(t) => t,
- Err(_) => return false,
+ loop {
+ let Ok(tok) = probe.next_token() else {
+ return false;
};
match tok.kind {
TokenKind::LParen | TokenKind::LBracket | TokenKind::LBrace => depth += 1,
- TokenKind::RParen | TokenKind::RBracket | TokenKind::RBrace => depth -= 1,
+ TokenKind::RParen | TokenKind::RBracket | TokenKind::RBrace => {
+ depth -= 1;
+ // Closed past the leading paren group's container —
+ // the enclosing query's `)`. Not a CTE head.
+ if depth < 0 {
+ return false;
+ }
+ }
TokenKind::Eof => return false,
+ // A depth-0 comma ends this list element without an
+ // alias: it is not a column-form CTE.
+ TokenKind::Comma if depth == 0 => return false,
+ TokenKind::Keyword(Kw::As) if depth == 0 => {
+ let Ok(ident) = probe.next_token() else {
+ return false;
+ };
+ return matches!(
+ ident.kind,
+ TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
+ );
+ }
_ => {}
}
}
- let after = match probe.next_token() {
- Ok(t) => t,
- Err(_) => return false,
- };
- if after.kind != TokenKind::Keyword(Kw::As) {
- return false;
- }
- let ident = match probe.next_token() {
- Ok(t) => t,
- Err(_) => return false,
- };
- matches!(
- ident.kind,
- TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
- )
}
fn parse_with_expr(&mut self) -> Result<E::Value, ParseError> {
diff --git a/uv.lock b/uv.lock
index 54ed30c3cfe7..4620bdedd24f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3136,16 +3136,16 @@ wheels = [
[[package]]
name = "hogql-parser-rs"
-version = "1.3.82"
+version = "1.3.84"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/38/3f/d9bea06219775097b1dbde1885c6089ce9c9c7c6e6f0c1e30aed6cc3f3d7/hogql_parser_rs-1.3.82.tar.gz", hash = "sha256:b5e13d1467060ffd4a26430177a9abfeb760fd2cabef19641960f3c5d9191296", size = 280827, upload-time = "2026-05-29T14:42:51.978Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/87/8c/03d5335d3d98bff386f0497a4624e761a6ea283e802bc01a77ac8cc8d221/hogql_parser_rs-1.3.84.tar.gz", hash = "sha256:7db5389fcb36e52624d5c6c8733f3d50477a06439a82ad3e027a3ed19e5514c7", size = 282589, upload-time = "2026-06-08T18:03:21.783Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/79/92/1b03ed83090b947046978bee27e4cd9e34419a5f3eb6024d82f8a685e3f4/hogql_parser_rs-1.3.82-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:7d1417a6d4714d92e691a2e20d5a1486d61a34dddc45265fd0fd3fb9a1400397", size = 727516, upload-time = "2026-05-29T14:42:42.372Z" },
- { url = "https://files.pythonhosted.org/packages/8f/a2/3a04eba078a02aacf9351825b837e64b68449fcde0568ae3b05e0156b885/hogql_parser_rs-1.3.82-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:1d21ad7cefb74cfadbafd8daa1de72cd774704100e20ec2253fd5aeb24b7d7ba", size = 685383, upload-time = "2026-05-29T14:42:43.941Z" },
- { url = "https://files.pythonhosted.org/packages/01/46/64b408c7e1021a73656b335983836d45e2e5ad9a072fbaa4fba863d7336f/hogql_parser_rs-1.3.82-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dbe6d6680ee528d27f0f6a1374973f7ae9ddd10cab4972f1e9aede68460501e5", size = 2475166, upload-time = "2026-05-29T14:42:45.701Z" },
- { url = "https://files.pythonhosted.org/packages/1b/ec/42df4f4e9fefbd1dbe8874fb3df9e7328e3bf4e2beb0f3d05a82bf5cb1a7/hogql_parser_rs-1.3.82-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:63f571fa4a7629133e84e4e5ff22b7f02e85f830cf5520b6f9cdb743410c49f9", size = 2734482, upload-time = "2026-05-29T14:42:47.215Z" },
- { url = "https://files.pythonhosted.org/packages/80/50/7a4c2dd611414c7fe17e1b6c77bc31bee1583d852c25594906141cc91527/hogql_parser_rs-1.3.82-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:68298628f3bcccb1ef5557f455af0005f7f6628677f17c9cf23c950acd1264fa", size = 2647339, upload-time = "2026-05-29T14:42:48.965Z" },
- { url = "https://files.pythonhosted.org/packages/c3/f3/39f0e6ea25221780371fb5a452c7e1a53f4e959e5d997819b4c1bc8ad907/hogql_parser_rs-1.3.82-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f62790bb62b0846a0ea421c772f69759d71e4480f1965144f202aaccbd302b62", size = 2696915, upload-time = "2026-05-29T14:42:50.49Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/8e/ad99eff56a05ca6b2f1bd592efde1aa81a7a52b3fc7fcd4c7519c9ce5515/hogql_parser_rs-1.3.84-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:fc32c43413bd2692798faedc65e2687ba52630d9f232b167fc745f9113e0621c", size = 727303, upload-time = "2026-06-08T18:03:12.447Z" },
+ { url = "https://files.pythonhosted.org/packages/5e/89/c94866d0ab46d8bbd2a45c741a2ff5c1dd7b977083ba3f3b6e2f01690f6e/hogql_parser_rs-1.3.84-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:44aaae7a57a29762d3598284183443e16098a5a65d5cba430f11ea5727fee16b", size = 685009, upload-time = "2026-06-08T18:03:13.943Z" },
+ { url = "https://files.pythonhosted.org/packages/76/a7/68e64caf41f9e8606cf21c126371b75d401259655ce88f4fd35501d32825/hogql_parser_rs-1.3.84-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ef3dfb8a520e17a9315c18be59dda9e81c37be2b30d3f8a0fca14c118ade452f", size = 2474527, upload-time = "2026-06-08T18:03:15.475Z" },
+ { url = "https://files.pythonhosted.org/packages/1c/5d/d2894e3ae4e2c4197cfc36c6735af0ed48b2ad6cbe97f5b267b6c0d6c5a6/hogql_parser_rs-1.3.84-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:097551f2733d2dabe7b419f08199d30f6e2970f442dc8a87fa3228fa7be82b15", size = 2733806, upload-time = "2026-06-08T18:03:17.2Z" },
+ { url = "https://files.pythonhosted.org/packages/99/f1/56857dea8c90b4f5b5731327bf3977c90737bd32c21ef3a6fb487b62a769/hogql_parser_rs-1.3.84-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:bf77c7067610833aae1292ed995619445d44f7cbf2cb7790a9d3ec26653b335b", size = 2647471, upload-time = "2026-06-08T18:03:18.568Z" },
+ { url = "https://files.pythonhosted.org/packages/78/34/411d1e5c8c08474d0c49c9e03b734895867a2b3eaff8730da2c8550445bc/hogql_parser_rs-1.3.84-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:497c7d435f6bcbc839372f12026176fbccf6b419714673edda61a4fd2d05913d", size = 2696957, upload-time = "2026-06-08T18:03:20.124Z" },
]
[[package]]
@@ -5770,7 +5770,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.82" },
+ { name = "hogql-parser-rs", specifier = "==1.3.84" },
{ 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" },