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.

feat(hogql): default to cpp with rust-py shadow + parity metrics (#60201)

Robbie8e0ba1b8f8b6
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 606c03e6e803..0d8ae3305d7e 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -21153,10 +21153,11 @@
"type": "boolean"
},
"parserMode": {
- "description": "HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.",
+ "description": "HogQL parser backend; absent → `cpp_with_rust_py_shadow` (cpp is primary, rust-py runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.",
"enum": [
"cpp_only",
"cpp_with_rust_shadow",
+ "cpp_with_rust_py_shadow",
"rust_with_cpp_shadow",
"rust_only",
"rust_py_only",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 4a767bd08237..5a3605943e9e 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -451,10 +451,11 @@ export interface HogQLQueryModifiers {
/** If these are provided, the query will fail if these skip indexes are not used */
forceClickhouseDataSkippingIndexes?: string[]
inlineCohortCalculation?: 'off' | 'auto' | 'always'
- /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
+ /** HogQL parser backend; absent → `cpp_with_rust_py_shadow` (cpp is primary, rust-py runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?:
| 'cpp_only'
| 'cpp_with_rust_shadow'
+ | 'cpp_with_rust_py_shadow'
| 'rust_with_cpp_shadow'
| 'rust_only'
| 'rust_py_only'
diff --git a/posthog/hogql/parser.py b/posthog/hogql/parser.py
index 94977b2a65ec..1aef8795861f 100644
--- a/posthog/hogql/parser.py
+++ b/posthog/hogql/parser.py
@@ -2,6 +2,7 @@ import sys
import copy
import random
import threading
+import importlib.metadata
from collections.abc import Callable
from enum import StrEnum
from types import FrameType
@@ -188,11 +189,29 @@ RULE_TO_PARSE_FUNCTION: dict[HogQLParserBackend, dict[ParseRule, Callable]] = {
},
}
+
+def _parser_version(distribution: str) -> str:
+ """Installed version of a parser wheel, or "unknown" if it has no distribution metadata (editable/source build). Tagged on telemetry so old wheels can be filtered out."""
+ try:
+ return importlib.metadata.version(distribution)
+ except importlib.metadata.PackageNotFoundError:
+ return "unknown"
+
+
+# Parser version per backend, resolved once at import. cpp/rust ship as wheels (`hogql-parser`, `hogql-parser-rs`);
+# the python ANTLR backend is vendored and has no standalone version.
+_BACKEND_VERSION: dict[HogQLParserBackend, str] = {
+ "cpp-json": _parser_version("hogql-parser"),
+ "rust-json": _parser_version("hogql-parser-rs"),
+ "rust-py": _parser_version("hogql-parser-rs"),
+ "python": "n/a",
+}
+
RULE_TO_HISTOGRAM: dict[ParseRule, Histogram] = {
rule: Histogram(
f"parse_{rule}_seconds",
f"Time to parse {rule} expression",
- labelnames=["backend"],
+ labelnames=["backend", "version"],
)
for rule in (ParseRule.EXPR, ParseRule.ORDER_EXPR, ParseRule.SELECT, ParseRule.FULL_TEMPLATE_STRING)
}
@@ -208,21 +227,21 @@ _PARSER_MODE_BACKENDS: dict[ParserMode, tuple[HogQLParserBackend, HogQLParserBac
ParserMode.CPP_ONLY: ("cpp-json", None),
ParserMode.RUST_ONLY: ("rust-json", None),
ParserMode.CPP_WITH_RUST_SHADOW: ("cpp-json", "rust-json"),
+ ParserMode.CPP_WITH_RUST_PY_SHADOW: ("cpp-json", "rust-py"),
ParserMode.RUST_WITH_CPP_SHADOW: ("rust-json", "cpp-json"),
ParserMode.RUST_PY_ONLY: ("rust-py", None),
ParserMode.RUST_PY_WITH_CPP_SHADOW: ("rust-py", "cpp-json"),
}
-# Fraction of `*_shadow` parses that also run the secondary backend. Kept
-# low in production — the shadow parse is pure overhead on the request's
-# hot path. Tests run every parse through the shadow (see
-# `_shadow_sample_rate`).
+# Fraction of `*_shadow` parses in PROD that also run the shadow backend. Held at 1% for the rust-py rollout: a latent
+# rust-py pathology (slow parse, crash) then touches ~1% of requests, not all. Ramp to 100% once it looks safe in prod.
+# Tests always sample 100%.
_SHADOW_SAMPLE_RATE = 0.01
def _shadow_sample_rate() -> float:
- """Tests force 100% shadow sampling to catch any divergence; production
- keeps the 1% sample to bound per-request overhead."""
+ """Shadow sampling fraction: 100% in tests (every parse compared, regressions fail loud), `_SHADOW_SAMPLE_RATE` in
+ prod. Divergence behavior also differs by env (TEST raises, prod records) in `_run_shadow_comparison`."""
return 1.0 if settings.TEST else _SHADOW_SAMPLE_RATE
@@ -231,19 +250,25 @@ def _resolve_parser_mode(
) -> tuple[HogQLParserBackend, HogQLParserBackend | None]:
"""Resolve a `parserMode` modifier to `(primary, shadow)` backends.
- In TEST: an absent modifier defaults to `CPP_WITH_RUST_SHADOW` so the
- test suite exercises both backends on every parse and raises on AST
- divergence (see `_run_shadow_comparison`). Honour an explicit
- `backend=` override (test factories / parity scripts) untouched.
-
- In prod: an absent modifier is treated as `cpp_only` — resolved here at
- the call site, never written back onto the modifier, so the query
- hash is unaffected. The explicitly-passed `backend` is honoured
- (default `cpp-json`).
+ An absent modifier defaults to `CPP_WITH_RUST_PY_SHADOW`: cpp stays the
+ primary (its result is always returned) and rust-py runs as the shadow,
+ sampled per `_shadow_sample_rate` (100% in test, 1% in prod for now). The
+ divergence behavior differs by environment downstream
+ (`_run_shadow_comparison`): TEST raises on any mismatch, prod only
+ reports it (never failing the request).
+
+ If the rust wheel failed to import (`_RUST_PARSER_AVAILABLE` is False)
+ the default drops the shadow and runs cpp-only, so a broken wheel can't
+ spam the parse path; the unavailability is reported once at import time.
+
+ An explicit `backend=` override (test factories / parity scripts) is
+ honoured untouched and bypasses the shadow. Resolution happens here at
+ the call site and is never written back onto the modifier, so the query
+ hash is unaffected.
"""
if parser_mode is None:
- if settings.TEST and backend == DEFAULT_BACKEND:
- return _PARSER_MODE_BACKENDS[ParserMode.CPP_WITH_RUST_SHADOW]
+ if backend == DEFAULT_BACKEND and _RUST_PARSER_AVAILABLE:
+ return _PARSER_MODE_BACKENDS[ParserMode.CPP_WITH_RUST_PY_SHADOW]
return backend, None
return _PARSER_MODE_BACKENDS[parser_mode]
@@ -254,11 +279,16 @@ class HogQLParserShadowMismatch(Exception):
into a request — the primary backend's result is always returned."""
-_SHADOW_BACKEND_FAILURES = Counter(
- "hogql_parser_shadow_backend_failures",
- "Shadow-backend parses that threw an exception (packaging error, panic, etc.). "
- "Captured but never propagated — primary backend's result is always returned.",
- labelnames=["rule", "shadow"],
+# Shadowed-run telemetry (sampled; see `_run_shadow_comparison`). This counter adds the run count + agreement rate;
+# durations and their ratio come from the per-backend `parse_*_seconds` timer (the shadow runs on the already-done cpp
+# parse). `*_version` labels let results be filtered by parser wheel. The raw query behind a divergence can't be a
+# label, so it goes to error tracking via `capture_exception` (already a sink for query SQL on failures), not the logs.
+_SHADOW_COMPARISONS = Counter(
+ "hogql_parser_shadow_comparisons_total",
+ "Shadowed parser runs by outcome. Sum across results is the number of "
+ "shadowed runs; agreement rate is agree / that sum.",
+ # result: agree | disagree | shadow_rejected | shadow_error
+ labelnames=["rule", "result", "primary_version", "shadow_version"],
)
@@ -270,71 +300,65 @@ def _run_shadow_comparison(
primary_node: Any,
start: int | None,
) -> None:
- """Sample-rate-gated cross-backend parity check.
-
- In prod: a `_SHADOW_SAMPLE_RATE` (1%) sample of parses also runs the
- shadow backend; a divergence or shadow-backend crash is captured to
- error tracking and the primary result is returned untouched.
-
- In TEST: every parse runs through the shadow. Two failure classes
- are distinguished:
- - parser-class: shadow rejects (`BaseHogQLError`) input the primary
- accepted, OR the two backends agree to parse but produce
- different ASTs. Both raise in TEST so a regression fails loud.
- - packaging-class: any other exception (`ImportError`,
- `RuntimeError` from the stub, a PyO3 panic). NEVER propagates;
- captured + counted only. A broken shadow wheel must not block
- the primary parser's hot path or fail the test suite.
+ """Cross-backend parity check, gated by `_shadow_sample_rate`. Emits telemetry only for shadowed runs, and always
+ returns the primary result untouched.
+
+ Increments `hogql_parser_shadow_comparisons_total` (run count + agreement rate, tagged by parser version). The
+ shadow runs on the already-done cpp parse (never parsed twice); durations and their ratio come from the per-backend
+ `parse_*_seconds` timer. The divergent query, which can't be a metric label, goes to error tracking via
+ `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.
"""
if random.random() >= _shadow_sample_rate():
return
test_mode = settings.TEST
+ rule_label = str(rule)
+ primary_version = _BACKEND_VERSION.get(primary_backend, "unknown")
+ shadow_version = _BACKEND_VERSION.get(shadow_backend, "unknown")
+
+ def _count(result: str) -> None:
+ _SHADOW_COMPARISONS.labels(
+ rule=rule_label, result=result, primary_version=primary_version, shadow_version=shadow_version
+ ).inc()
+
+ # Divergent query SQL rides error tracking (not the logs), the channel that already carries query SQL on failures.
+ divergence_properties = {
+ "hogql_parser_rule": rule_label,
+ "hogql_parser_primary": primary_backend,
+ "hogql_parser_shadow": shadow_backend,
+ "hogql_parser_primary_version": primary_version,
+ "hogql_parser_shadow_version": shadow_version,
+ "hogql_parser_statement": statement,
+ }
try:
shadow_node = _invoke_parser(shadow_backend, rule, statement, start)
except BaseHogQLError as err:
- # Parser-class failure: shadow rejects input that primary accepted.
- # In TEST that's a regression we want to see.
- _SHADOW_BACKEND_FAILURES.labels(rule=str(rule), shadow=shadow_backend).inc()
- capture_exception(
- err,
- additional_properties={
- "hogql_parser_rule": str(rule),
- "hogql_parser_shadow": shadow_backend,
- "hogql_parser_statement": statement,
- "hogql_parser_shadow_throw": "true",
- },
- )
+ # Shadow rejects input the primary accepted: a divergence (raises in TEST).
+ _count("shadow_rejected")
+ capture_exception(err, additional_properties={**divergence_properties, "hogql_parser_shadow_throw": "true"})
if test_mode:
raise
return
except Exception as err:
- # Packaging-class failure (ImportError, stub RuntimeError, panic).
- # Capture + count, never propagate, even in TEST.
- _SHADOW_BACKEND_FAILURES.labels(rule=str(rule), shadow=shadow_backend).inc()
- capture_exception(
- err,
- additional_properties={
- "hogql_parser_rule": str(rule),
- "hogql_parser_shadow": shadow_backend,
- "hogql_parser_statement": statement,
- "hogql_parser_shadow_throw": "true",
- },
- )
+ # Packaging-class failure (broken wheel / panic). Counted, never raised.
+ _count("shadow_error")
+ capture_exception(err, additional_properties={**divergence_properties, "hogql_parser_shadow_throw": "true"})
return
- if clear_locations(primary_node) == clear_locations(shadow_node):
+ # 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):
+ _count("agree")
return
+ _count("disagree")
mismatch = HogQLParserShadowMismatch(f"{rule} parser AST mismatch: {primary_backend} vs {shadow_backend}")
if test_mode:
raise mismatch
- capture_exception(
- mismatch,
- additional_properties={
- "hogql_parser_rule": str(rule),
- "hogql_parser_primary": primary_backend,
- "hogql_parser_shadow": shadow_backend,
- "hogql_parser_statement": statement,
- },
- )
+ capture_exception(mismatch, additional_properties=divergence_properties)
# Two caches so a flood of unique user-generated queries can't displace the
@@ -432,7 +456,7 @@ def _invoke_parser(backend: HogQLParserBackend, rule: ParseRule, statement: str,
histogram = RULE_TO_HISTOGRAM.get(rule)
if histogram is None:
return fn(statement)
- with histogram.labels(backend=backend).time():
+ with histogram.labels(backend=backend, version=_BACKEND_VERSION.get(backend, "unknown")).time():
return fn(statement, start) if rule == ParseRule.EXPR else fn(statement)
diff --git a/posthog/hogql/test/test_parser_mode.py b/posthog/hogql/test/test_parser_mode.py
index fb2229d6ef7a..ef406c62a088 100644
--- a/posthog/hogql/test/test_parser_mode.py
+++ b/posthog/hogql/test/test_parser_mode.py
@@ -5,20 +5,22 @@ from parameterized import parameterized
from posthog.schema import ParserMode
-from posthog.hogql import ast
-from posthog.hogql.parser import HogQLParserShadowMismatch, _resolve_parser_mode, parse_select
+from posthog.hogql import (
+ ast,
+ 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
class TestParserMode(BaseTest):
@parameterized.expand(
[
- # An absent modifier in TEST defaults to CPP_WITH_RUST_SHADOW so
- # every test-suite parse exercises both backends and raises on
- # divergence (see `_run_shadow_comparison`).
- (None, ("cpp-json", "rust-json")),
+ (None, ("cpp-json", "rust-py")),
(ParserMode.CPP_ONLY, ("cpp-json", None)),
(ParserMode.RUST_ONLY, ("rust-json", None)),
(ParserMode.CPP_WITH_RUST_SHADOW, ("cpp-json", "rust-json")),
+ (ParserMode.CPP_WITH_RUST_PY_SHADOW, ("cpp-json", "rust-py")),
(ParserMode.RUST_WITH_CPP_SHADOW, ("rust-json", "cpp-json")),
(ParserMode.RUST_PY_ONLY, ("rust-py", None)),
(ParserMode.RUST_PY_WITH_CPP_SHADOW, ("rust-py", "cpp-json")),
@@ -27,22 +29,19 @@ class TestParserMode(BaseTest):
def test_resolve_parser_mode(self, mode, expected):
self.assertEqual(_resolve_parser_mode(mode, "cpp-json"), expected)
- def test_resolve_parser_mode_honours_explicit_backend_when_absent(self):
- # With no modifier the `backend=` override still wins — this is the
- # path the test/diagnostic harness relies on. Even in TEST, an
- # explicit non-default backend disables the auto-shadow.
+ def test_resolve_parser_mode_honours_explicit_backend_when_modifier_absent(self):
self.assertEqual(_resolve_parser_mode(None, "rust-json"), ("rust-json", None))
- def test_resolve_parser_mode_prod_absent_modifier_no_shadow(self):
- # The TEST-only auto-shadow is gated on `settings.TEST`; with that
- # flag off (i.e. production) an absent modifier means "no shadow".
+ def test_resolve_parser_mode_default_shadows_in_prod_not_only_in_test(self):
with patch("posthog.hogql.parser.settings") as mock_settings:
mock_settings.TEST = False
+ self.assertEqual(_resolve_parser_mode(None, "cpp-json"), ("cpp-json", "rust-py"))
+
+ def test_resolve_parser_mode_drops_shadow_when_rust_unavailable(self):
+ with patch("posthog.hogql.parser._RUST_PARSER_AVAILABLE", False):
self.assertEqual(_resolve_parser_mode(None, "cpp-json"), ("cpp-json", None))
def test_shadow_silent_when_backends_agree(self):
- # A `*_shadow` mode parses with the shadow backend on every sampled
- # query; when the ASTs match, nothing is reported.
with patch("posthog.hogql.parser._SHADOW_SAMPLE_RATE", 1.0):
with patch("posthog.hogql.parser.capture_exception") as captured:
node = parse_select("select 1 from events", parser_mode=ParserMode.CPP_WITH_RUST_SHADOW)
@@ -50,12 +49,6 @@ class TestParserMode(BaseTest):
captured.assert_not_called()
def test_shadow_raises_mismatch_in_test_mode(self):
- # In TEST the shadow comparison raises on divergence, so a test
- # whose parser produces a mismatched AST fails loudly. Only the
- # shadow backend is forced to diverge; the primary still parses
- # for real.
- from posthog.hogql import parser as parser_module
-
decoy = ast.SelectQuery(select=[ast.Constant(value=999)])
real_invoke = parser_module._invoke_parser
@@ -71,12 +64,7 @@ class TestParserMode(BaseTest):
parser_mode=ParserMode.CPP_WITH_RUST_SHADOW,
)
- def test_shadow_reports_mismatch_without_failing_in_prod(self):
- # In production (`settings.TEST = False`) the shadow comparison
- # captures the mismatch to error tracking and returns the primary
- # result — never raises into a request.
- from posthog.hogql import parser as parser_module
-
+ def test_shadow_captures_mismatch_without_raising_in_prod(self):
decoy = ast.SelectQuery(select=[ast.Constant(value=999)])
real_invoke = parser_module._invoke_parser
@@ -99,17 +87,10 @@ class TestParserMode(BaseTest):
self.assertIsInstance(captured.call_args.args[0], HogQLParserShadowMismatch)
def test_rust_only_parses_through_the_rust_backend(self):
- # `rust_only` routes the parse entirely through the Rust backend.
node = parse_select("select a, b from events where a > 1", parser_mode=ParserMode.RUST_ONLY)
self.assertIsInstance(node, ast.SelectQuery)
- def test_shadow_raises_parser_class_throw_in_test_mode(self):
- # A `BaseHogQLError` from the shadow backend means it rejected what
- # the primary accepted — a real parser regression. Propagate in TEST
- # so a unit-suite parse hitting the regression fails loudly.
- from posthog.hogql import parser as parser_module
- from posthog.hogql.errors import SyntaxError as HogQLSyntaxError
-
+ def test_shadow_raises_when_shadow_rejects_primary_accepted_input_in_test_mode(self):
real_invoke = parser_module._invoke_parser
def shadow_throws_parser_class(backend, rule, statement, start):
@@ -122,12 +103,33 @@ class TestParserMode(BaseTest):
with self.assertRaises(HogQLSyntaxError):
parse_select("select 1 from events", parser_mode=ParserMode.CPP_WITH_RUST_SHADOW)
- def test_shadow_swallows_packaging_class_throw_in_test_mode(self):
- # A non-BaseHogQLError exception (ImportError, RuntimeError from a
- # broken wheel, PyO3 panic) is treated as a packaging issue — never
- # propagates, even in TEST. Captures + counts.
- from posthog.hogql import parser as parser_module
+ def test_shadow_rejection_counts_and_captures_sql_without_raising_in_prod(self):
+ real_invoke = parser_module._invoke_parser
+
+ def shadow_throws_parser_class(backend, rule, statement, start):
+ if backend == "rust-py":
+ raise HogQLSyntaxError("simulated rust-py rejection")
+ return real_invoke(backend, rule, statement, start)
+ with patch("posthog.hogql.parser.settings") as mock_settings:
+ mock_settings.TEST = False
+ with patch("posthog.hogql.parser._SHADOW_SAMPLE_RATE", 1.0):
+ with patch("posthog.hogql.parser._invoke_parser", side_effect=shadow_throws_parser_class):
+ with patch("posthog.hogql.parser._SHADOW_COMPARISONS") as counter:
+ with patch("posthog.hogql.parser.capture_exception") as captured:
+ node = parse_select(
+ "select shadow_rejected_probe from events",
+ parser_mode=ParserMode.CPP_WITH_RUST_PY_SHADOW,
+ )
+ self.assertIsInstance(node, ast.SelectQuery)
+ results = [c.kwargs.get("result") for c in counter.labels.call_args_list]
+ self.assertIn("shadow_rejected", results)
+ captured.assert_called_once()
+ props = captured.call_args.kwargs["additional_properties"]
+ self.assertIn("shadow_rejected_probe", props["hogql_parser_statement"])
+ self.assertEqual(props["hogql_parser_shadow_version"], parser_module._BACKEND_VERSION["rust-py"])
+
+ def test_shadow_swallows_non_parser_packaging_error_even_in_test_mode(self):
real_invoke = parser_module._invoke_parser
def shadow_throws_packaging(backend, rule, statement, start):
@@ -141,3 +143,54 @@ class TestParserMode(BaseTest):
self.assertIsInstance(node, ast.SelectQuery)
captured.assert_called_once()
self.assertIsInstance(captured.call_args.args[0], ImportError)
+
+ def test_shadow_agreement_counts_as_agree_with_parser_version_labels(self):
+ with patch("posthog.hogql.parser._SHADOW_COMPARISONS") as counter:
+ with patch("posthog.hogql.parser.capture_exception") as captured:
+ parse_select("select 1 from events", parser_mode=ParserMode.CPP_WITH_RUST_PY_SHADOW)
+ self.assertEqual([c.kwargs.get("result") for c in counter.labels.call_args_list], ["agree"])
+ agree_call = counter.labels.call_args_list[0]
+ self.assertEqual(agree_call.kwargs["primary_version"], parser_module._BACKEND_VERSION["cpp-json"])
+ self.assertEqual(agree_call.kwargs["shadow_version"], parser_module._BACKEND_VERSION["rust-py"])
+ captured.assert_not_called()
+
+ def test_shadow_divergence_counts_as_disagree_and_captures_sql_in_prod(self):
+ decoy = ast.SelectQuery(select=[ast.Constant(value=999)])
+ real_invoke = parser_module._invoke_parser
+
+ def only_shadow_diverges(backend, rule, statement, start):
+ if backend == "rust-py":
+ return decoy
+ return real_invoke(backend, rule, statement, start)
+
+ with patch("posthog.hogql.parser.settings") as mock_settings:
+ mock_settings.TEST = False
+ with patch("posthog.hogql.parser._SHADOW_SAMPLE_RATE", 1.0):
+ with patch("posthog.hogql.parser._invoke_parser", side_effect=only_shadow_diverges):
+ with patch("posthog.hogql.parser._SHADOW_COMPARISONS") as counter:
+ with patch("posthog.hogql.parser.capture_exception") as captured:
+ parse_select(
+ "select sql_attach_probe from events",
+ parser_mode=ParserMode.CPP_WITH_RUST_PY_SHADOW,
+ )
+ results = [c.kwargs.get("result") for c in counter.labels.call_args_list]
+ self.assertIn("disagree", results)
+ captured.assert_called_once()
+ self.assertIsInstance(captured.call_args.args[0], HogQLParserShadowMismatch)
+ props = captured.call_args.kwargs["additional_properties"]
+ self.assertEqual(props["hogql_parser_rule"], "select")
+ self.assertIn("sql_attach_probe", props["hogql_parser_statement"])
+ self.assertEqual(props["hogql_parser_primary_version"], parser_module._BACKEND_VERSION["cpp-json"])
+ self.assertEqual(props["hogql_parser_shadow_version"], parser_module._BACKEND_VERSION["rust-py"])
+
+ def test_shadow_treats_nan_constant_as_agreement_not_divergence(self):
+ with patch("posthog.hogql.parser._SHADOW_COMPARISONS") as counter:
+ node = parse_expr("nan", parser_mode=ParserMode.CPP_WITH_RUST_PY_SHADOW)
+ self.assertIsInstance(node, ast.Constant)
+ self.assertEqual([c.kwargs.get("result") for c in counter.labels.call_args_list], ["agree"])
+
+ def test_parser_version_falls_back_to_unknown_for_missing_dist(self):
+ self.assertEqual(parser_module._parser_version("definitely-not-a-real-distribution"), "unknown")
+
+ def test_backend_version_map_covers_every_parse_backend(self):
+ self.assertEqual(set(parser_module._BACKEND_VERSION), set(parser_module.RULE_TO_PARSE_FUNCTION))
diff --git a/posthog/schema.py b/posthog/schema.py
index aeb87e81755d..78db1abbef85 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2633,6 +2633,7 @@ class MaterializedColumnsOptimizationMode(StrEnum):
class ParserMode(StrEnum):
CPP_ONLY = "cpp_only"
CPP_WITH_RUST_SHADOW = "cpp_with_rust_shadow"
+ CPP_WITH_RUST_PY_SHADOW = "cpp_with_rust_py_shadow"
RUST_WITH_CPP_SHADOW = "rust_with_cpp_shadow"
RUST_ONLY = "rust_only"
RUST_PY_ONLY = "rust_py_only"
@@ -7415,10 +7416,11 @@ class HogQLQueryModifiers(BaseModel):
parserMode: ParserMode | None = Field(
default=None,
description=(
- "HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the"
- " primary result and sample-compare against the other parser, reporting"
- " divergences without failing the request. The `rust_py_*` modes drive the"
- " same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast`"
+ "HogQL parser backend; absent → `cpp_with_rust_py_shadow` (cpp is primary,"
+ " rust-py runs as a sampled shadow). `*_shadow` modes return the primary"
+ " result and sample-compare against the other parser, reporting divergences"
+ " without failing the request. The `rust_py_*` modes drive the same"
+ " hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast`"
" dataclass instances directly via PyO3, skipping the JSON round-trip."
),
)
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 7d843f3ff424..b7d248e944ab 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -361,6 +361,7 @@ export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]
export const ParserModeApi = {
CppOnly: 'cpp_only',
CppWithRustShadow: 'cpp_with_rust_shadow',
+ CppWithRustPyShadow: 'cpp_with_rust_py_shadow',
RustWithCppShadow: 'rust_with_cpp_shadow',
RustOnly: 'rust_only',
RustPyOnly: 'rust_py_only',
@@ -431,7 +432,7 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
- /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
+ /** HogQL parser backend; absent → `cpp_with_rust_py_shadow` (cpp is primary, rust-py runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserModeApi | null
personsArgMaxVersion?: PersonsArgMaxVersionApi | null
personsJoinMode?: PersonsJoinModeApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f91d6bca1a60..5fc281cee302 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1504,6 +1504,7 @@ export namespace Schemas {
export const ParserMode = {
CppOnly: 'cpp_only',
CppWithRustShadow: 'cpp_with_rust_shadow',
+ CppWithRustPyShadow: 'cpp_with_rust_py_shadow',
RustWithCppShadow: 'rust_with_cpp_shadow',
RustOnly: 'rust_only',
RustPyOnly: 'rust_py_only',
@@ -1580,7 +1581,7 @@ export namespace Schemas {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationMode | null;
optimizeJoinedFilters?: boolean | null;
optimizeProjections?: boolean | null;
- /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
+ /** HogQL parser backend; absent → `cpp_with_rust_py_shadow` (cpp is primary, rust-py runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserMode | null;
personsArgMaxVersion?: PersonsArgMaxVersion | null;
personsJoinMode?: PersonsJoinMode | null;