: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
fix(hogql): cap recursion depth in the C++ parser (#73958)
George Munyoro40ab12035e60
diff --git a/common/hogql_parser/parser_json.cpp b/common/hogql_parser/parser_json.cppindex 82aaf602111b..bc9c75a78173 100644--- a/common/hogql_parser/parser_json.cpp+++ b/common/hogql_parser/parser_json.cpp@@ -9,6 +9,7 @@#include <sstream>#include <string>#include <unordered_map>+#include <vector>#include "HogQLLexer.h"#include "HogQLParser.h"@@ -26,6 +27,95 @@using namespace std;+// NESTING DEPTH GUARD++// Cap on parser recursion depth, mirroring the Rust backend's `MAX_RECURSION_DEPTH` and+// ClickHouse's `max_parser_depth`. One level per open bracket or per prefix operator, so+// this maps directly onto the descent depth ANTLR would reach — 1000 is absurdly deep for+// any real query yet safely below the point where the parser gets into trouble.+static constexpr size_t MAX_PARSER_DEPTH = 1000;++// Reject pathologically deep nesting BEFORE handing the stream to ANTLR. HogQL's grammar+// recurses on bracket nesting — parentheses (`(((…`), arrays/subqueries (`[[[…`), Hog blocks+// (`{{{…`) — and on runs of prefix operators, each recursing on its operand: `NOT NOT … 1`+// (`ColumnExprNot`) and `- - - … 1` (`ColumnExprNegate`). ANTLR's generated parser recurses+// on both with no built-in cap, and — worse for brackets — its ALL(*) prediction explores+// the ambiguous `(` alternatives before any rule-entry hook fires, so deeply nested input+// either exhausts the native stack (an uncatchable SIGSEGV) or drives prediction into+// effectively unbounded work. A parse-tree listener can't help: the bracket runaway happens+// in prediction, before the parse tree exists. Lexing, by contrast, is iterative, so a+// linear pre-scan of the already-lexed token stream is crash-safe and surfaces a clean+// SyntaxError.+//+// `depth` tracks live recursion: each open bracket is +1 until its close, and a prefix+// operator is +1 while its operand is still being parsed. Consecutive prefixes accumulate+// in `prefix_run`. A prefix's operand can itself be a bracketed group, and the prefix+// frames stay live for that whole group — so at a bracket open we fold the pending+// `prefix_run` into the bracket's contribution and push it, unwinding the whole lot at the+// matching close. This catches the combined `999 NOT + 999 (` case (~2000 real frames)+// that a separate bracket/prefix count would miss, while a prefix run ending on a plain+// atom (`NOT a`) is transient and dropped — so scattered `NOT a AND NOT b` never+// accumulates and there are no false positives on real queries.+//+// Not covered: recursive *statement* productions (`if (1) if (1) … return 1`, which nest+// `ifStmt → statement → ifStmt`) have no delimiter token, so a token scan can't bound them+// without either parsing or false-positiving on legitimate sequential statements. Client+// selection of this backend as primary is gated at the API layer (see+// `sanitize_client_parser_mode` in parser.py), so the only untrusted reach into cpp is the+// rust-wheel-missing fallback; this scan is a best-effort defense for that path, not a+// complete recursion guard.+void guardNestingDepth(antlr4::CommonTokenStream* stream) {+ stream->fill();+ size_t depth = 0;+ size_t prefix_run = 0;+ vector<size_t> bracket_contributions; // per open bracket: amount to unwind on its close+ for (antlr4::Token* token : stream->getTokens()) {+ // Whitespace and comments sit on the hidden channel (see `WHITESPACE -> channel(HIDDEN)`+ // in the lexer grammar). The parser skips them, so we must too — otherwise a hidden token+ // between operators resets `prefix_run` and a spaced `- - - … 1` chain slips past the cap.+ if (token->getChannel() != antlr4::Token::DEFAULT_CHANNEL) {+ continue;+ }+ size_t type = token->getType();+ switch (type) {+ case HogQLParser::NOT:+ case HogQLParser::DASH:+ ++prefix_run;+ break;+ case HogQLParser::LPAREN:+ case HogQLParser::LBRACKET:+ case HogQLParser::LBRACE: {+ // The bracket begins the operand of any pending prefixes, so those prefix frames+ // stay live for the whole group. Fold them in with the bracket and remember the+ // total so the matching close unwinds exactly this much.+ size_t contribution = 1 + prefix_run;+ depth += contribution;+ bracket_contributions.push_back(contribution);+ prefix_run = 0;+ break;+ }+ case HogQLParser::RPAREN:+ case HogQLParser::RBRACKET:+ case HogQLParser::RBRACE:+ prefix_run = 0;+ if (!bracket_contributions.empty()) {+ depth -= bracket_contributions.back();+ bracket_contributions.pop_back();+ }+ break;+ default:+ // Plain atom: any pending prefixes had an atomic operand, a transient frame — drop it.+ prefix_run = 0;+ break;+ }+ if (depth + prefix_run > MAX_PARSER_DEPTH) {+ // Point at the token that tripped the cap so downstream tooling highlights where+ // nesting ran away, matching the real-position errors the Rust guard reports.+ throw SyntaxError("input too deeply nested", token->getStartIndex(), token->getStartIndex());+ }+ }+}+// JSON UTILS// Helper: Add position information to Json object from ParserRuleContextdiff --git a/common/hogql_parser/parser_json_python.cpp b/common/hogql_parser/parser_json_python.cppindex 52db482bc495..b5fa8f8bac22 100644--- a/common/hogql_parser/parser_json_python.cpp+++ b/common/hogql_parser/parser_json_python.cpp@@ -29,6 +29,7 @@parser->addErrorListener(error_listener); \HogQLParser::PASCAL_CASE##Context* parse_tree; \try { \+ guardNestingDepth(stream); \parse_tree = parser->CAMEL_CASE(); \} catch (const SyntaxError& e) { \string err_json = buildJSONError("SyntaxError", e.what(), e.start, e.end).dump(); \diff --git a/common/hogql_parser/parser_wasm.cpp b/common/hogql_parser/parser_wasm.cppindex 6a551e1cff5d..14f2ce60b7e3 100644--- a/common/hogql_parser/parser_wasm.cpp+++ b/common/hogql_parser/parser_wasm.cpp@@ -110,6 +110,8 @@ struct ParserContext {parser->removeErrorListeners();error_listener = std::make_unique<HogQLErrorListener>(input);parser->addErrorListener(error_listener.get());+ // Reject pathologically deep bracket nesting before ANTLR runs (see guardNestingDepth).+ guardNestingDepth(stream.get());}// Prevent copying (would cause double-free)diff --git a/posthog/hogql/parser.py b/posthog/hogql/parser.pyindex ed3ea0993597..08c9c44b8189 100644--- a/posthog/hogql/parser.py+++ b/posthog/hogql/parser.py@@ -181,6 +181,30 @@ _PARSER_MODE_BACKENDS: dict[ParserMode, tuple[HogQLParserBackend, HogQLParserBacParserMode.RUST_PY_WITH_CPP_SHADOW: ("rust-py", "cpp-json"),}+# Parser modes whose *primary* backend is the C++ parser. `parserMode` is a public+# `HogQLQueryModifier`, so a client can supply it — but the C++ backend's recursion guard is+# best-effort (a token pre-scan that can't bound recursive statement productions like nested+# `if`), so untrusted callers must not be able to force it as primary. cpp-as-*shadow* modes+# are safe: the shadow only runs after the rust primary parses successfully, and rust rejects+# pathologically deep input via `MAX_RECURSION_DEPTH` first, so the shadow never sees it.+_CPP_PRIMARY_PARSER_MODES = frozenset(+ {ParserMode.CPP_ONLY, ParserMode.CPP_WITH_RUST_SHADOW, ParserMode.CPP_WITH_RUST_PY_SHADOW}+)+++def sanitize_client_parser_mode(parser_mode: ParserMode | None) -> ParserMode | None:+ """Neutralize a client-supplied `parserMode` that would force the C++ backend as primary.++ Returns None (→ safe default resolution: rust-py primary, cpp sampled shadow) for+ cpp-primary modes, else the value unchanged. `parserMode` is an internal rollout knob+ never set by server-side code, so dropping these values costs nothing legitimate while+ closing the "authenticated caller selects the unguarded cpp parser" vector.+ """+ if parser_mode in _CPP_PRIMARY_PARSER_MODES:+ return None+ return parser_mode++# Fraction of `*_shadow` parses in PROD that also run the shadow backend. With rust-py promoted to the default primary,# the shadow leg now runs the cpp parser on ~0.1% of requests purely as a divergence canary. Bump if a fresh regression# surfaces and tighter coverage is needed.diff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex f0e002075151..c25cb90092f5 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -43,7 +43,7 @@ from posthog.hogql.feature_extractor import extract_hogql_featuresfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.hogql import HogQLContextfrom posthog.hogql.modifiers import create_default_modifiers_for_team-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_select, sanitize_client_parser_modefrom posthog.hogql.placeholders import find_placeholders, replace_placeholdersfrom posthog.hogql.printer import prepare_ast_for_printing, print_prepared_astfrom posthog.hogql.printer.access_control import build_access_control_warning@@ -146,7 +146,8 @@ class HogQLQueryExecutor:self.select_query = parse_select(str(self.query),timings=self.timings,- parser_mode=self.query_modifiers.parserMode,+ # Client-supplied `parserMode` can't force the best-effort-guarded cpp backend.+ parser_mode=sanitize_client_parser_mode(self.query_modifiers.parserMode),)@tracer.start_as_current_span("HogQLQueryExecutor._process_variables")diff --git a/posthog/hogql/test/_test_parser.py b/posthog/hogql/test/_test_parser.pyindex 03a0eb18b946..42e86340dbd9 100644--- a/posthog/hogql/test/_test_parser.py+++ b/posthog/hogql/test/_test_parser.py@@ -2923,14 +2923,13 @@ def parser_test_factory(backend: HogQLParserBackend):self.assertIn("synthetic post_init failure", str(caught.exception))def test_deeply_nested_input_does_not_stack_overflow(self):- # Deeply-nested input must surface a clean `SyntaxError`, not a host stack overflow (an uncatchable SIGSEGV) in the recursive-descent loop. One shared counter caps all three recursion dimensions — expression nesting, subquery / set nesting, and Hog statement / block nesting — at `MAX_RECURSION_DEPTH = 1000`, mirroring ClickHouse's `max_parser_depth`. cpp has its own stack characteristics so the assertion is rust-specific. Which guard fires (and so the exact message) depends on how the input routes through the descent, hence the loose substring check.- if backend not in ("rust-json", "rust-py"):- self.skipTest("rust-specific recursion cap")+ # Deeply-nested input must surface a clean `SyntaxError`, not a host stack overflow (an uncatchable SIGSEGV) in the recursive-descent loop. Both recursion shapes are covered: bracket nesting (parens / subqueries / blocks) and prefix-operator chains (`- - - …`), which recurse on their operand without any bracket. Rust caps live descent at `MAX_RECURSION_DEPTH = 1000`; cpp rejects via a crash-safe pre-parse token scan at `MAX_PARSER_DEPTH` (a parse-tree listener can't help — ALL(*) prediction runs the bracket case away before the tree exists). Both mirror ClickHouse's `max_parser_depth`. Which guard fires (and so the exact message) depends on how the input routes through the descent, hence the loose substring check.parse_fns = {"expr": parse_expr, "select": parse_select, "program": parse_program}cases = (("expr", "(" * 1500 + "1" + ")" * 1500),("select", "(" * 1500 + "select 1" + ")" * 1500),("program", "{" * 1500 + "}" * 1500),+ ("expr", "- " * 1500 + "1"),)for rule, src in cases:with self.assertRaises(SyntaxError, msg=rule) as cm:diff --git a/posthog/hogql/test/test_parser_mode.py b/posthog/hogql/test/test_parser_mode.pyindex 9a552e162ee0..e2e26f264025 100644--- a/posthog/hogql/test/test_parser_mode.py+++ b/posthog/hogql/test/test_parser_mode.py@@ -10,7 +10,13 @@ from posthog.hogql import (parser as parser_module,)from posthog.hogql.errors import SyntaxError as HogQLSyntaxError-from posthog.hogql.parser import HogQLParserShadowMismatch, _resolve_parser_mode, parse_expr, parse_select+from posthog.hogql.parser import (+ HogQLParserShadowMismatch,+ _resolve_parser_mode,+ parse_expr,+ parse_select,+ sanitize_client_parser_mode,+)class TestParserMode(BaseTest):@@ -48,6 +54,41 @@ class TestParserMode(BaseTest):with self.assertRaises(ValueError):_resolve_parser_mode(ParserMode.RUST_PY_ONLY, "cpp-json")+ @parameterized.expand(+ [+ # cpp-as-primary modes are untrusted from a client → neutralized to the safe default.+ (ParserMode.CPP_ONLY, None),+ (ParserMode.CPP_WITH_RUST_SHADOW, None),+ (ParserMode.CPP_WITH_RUST_PY_SHADOW, None),+ # cpp-as-shadow and rust-primary modes are safe (rust primary rejects deep input+ # before the shadow runs) → passed through untouched.+ (ParserMode.RUST_WITH_CPP_SHADOW, ParserMode.RUST_WITH_CPP_SHADOW),+ (ParserMode.RUST_PY_WITH_CPP_SHADOW, ParserMode.RUST_PY_WITH_CPP_SHADOW),+ (ParserMode.RUST_ONLY, ParserMode.RUST_ONLY),+ (ParserMode.RUST_PY_ONLY, ParserMode.RUST_PY_ONLY),+ (None, None),+ ]+ )+ def test_sanitize_client_parser_mode(self, mode, expected):+ self.assertEqual(sanitize_client_parser_mode(mode), expected)++ def test_client_cpp_parser_mode_does_not_reach_the_parser(self):+ # A client that sets `parserMode=cpp_only` must not force the cpp backend: the query+ # path sanitizes it first, so `parse_select` sees the safe (None) mode. This guards the+ # wiring at the single consume point (query.py), not just the helper in isolation.+ from posthog.schema import HogQLQueryModifiers # noqa: PLC0415++ from posthog.hogql.query import HogQLQueryExecutor # noqa: PLC0415++ executor = HogQLQueryExecutor(+ query="select 1",+ team=self.team,+ modifiers=HogQLQueryModifiers(parserMode=ParserMode.CPP_ONLY),+ )+ with patch("posthog.hogql.query.parse_select", wraps=parse_select) as spy:+ executor._parse_query()+ self.assertIsNone(spy.call_args.kwargs["parser_mode"])+def test_shadow_silent_when_backends_agree(self):with patch("posthog.hogql.parser._SHADOW_SAMPLE_RATE", 1.0):with patch("posthog.hogql.parser.capture_exception") as captured: