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.

perf(hogql): cache parsed ASTs with separate built-in / user buckets (#58269)

Robbie9dd25c82fab7
diff --git a/posthog/hogql/parser.py b/posthog/hogql/parser.py
index a4f4e2313508..ace1369f966e 100644
--- a/posthog/hogql/parser.py
+++ b/posthog/hogql/parser.py
@@ -1,8 +1,14 @@
+import sys
+import copy
+import threading
from collections.abc import Callable
-from typing import Literal, cast
+from enum import StrEnum
+from types import FrameType
+from typing import Any, Literal, cast
from antlr4 import CommonTokenStream, InputStream, ParserRuleContext, ParseTreeVisitor
from antlr4.error.ErrorListener import ErrorListener
+from cachetools import LRUCache
from hogql_parser import (
parse_expr_json as _parse_expr_json_cpp,
parse_full_template_string_json as _parse_full_template_string_json_cpp,
@@ -11,7 +17,7 @@ from hogql_parser import (
parse_select_json as _parse_select_json_cpp,
)
from opentelemetry import trace
-from prometheus_client import Histogram
+from prometheus_client import Counter, Gauge, Histogram
from structlog import getLogger
from posthog.hogql import ast
@@ -26,6 +32,21 @@ from posthog.hogql.parse_string import parse_string_literal_ctx, parse_string_li
from posthog.hogql.placeholders import replace_placeholders
from posthog.hogql.timings import HogQLTimings
+
+class CacheOrigin(StrEnum):
+ AUTO = "auto"
+ BUILTIN = "builtin"
+ USER = "user"
+
+
+class ParseRule(StrEnum):
+ EXPR = "expr"
+ ORDER_EXPR = "order_expr"
+ SELECT = "select"
+ FULL_TEMPLATE_STRING = "full_template_string"
+ PROGRAM = "program"
+
+
tracer = trace.get_tracer(__name__)
logger = getLogger(__name__)
@@ -62,55 +83,243 @@ def safe_lambda(f):
return wrapped
-RULE_TO_PARSE_FUNCTION: dict[
- HogQLParserBackend,
- dict[Literal["expr", "order_expr", "select", "full_template_string", "program"], Callable],
-] = {
+RULE_TO_PARSE_FUNCTION: dict[HogQLParserBackend, dict[ParseRule, Callable]] = {
"python": {
- "expr": safe_lambda(
+ ParseRule.EXPR: safe_lambda(
lambda string, start: HogQLParseTreeConverter(start=start).visit(get_parser(string).expr())
),
- "order_expr": safe_lambda(lambda string: HogQLParseTreeConverter().visit(get_parser(string).orderExpr())),
- "select": safe_lambda(lambda string: HogQLParseTreeConverter().visit(get_parser(string).select())),
- "full_template_string": safe_lambda(
+ ParseRule.ORDER_EXPR: safe_lambda(
+ lambda string: HogQLParseTreeConverter().visit(get_parser(string).orderExpr())
+ ),
+ ParseRule.SELECT: safe_lambda(lambda string: HogQLParseTreeConverter().visit(get_parser(string).select())),
+ ParseRule.FULL_TEMPLATE_STRING: safe_lambda(
lambda string: HogQLParseTreeConverter().visit(get_parser(string).fullTemplateString())
),
- "program": safe_lambda(lambda string: HogQLParseTreeConverter().visit(get_parser(string).program())),
+ ParseRule.PROGRAM: safe_lambda(lambda string: HogQLParseTreeConverter().visit(get_parser(string).program())),
},
"cpp-json": {
- "expr": lambda string, start: deserialize_ast(_parse_expr_json_cpp(string, is_internal=start is None)),
- "order_expr": lambda string: deserialize_ast(_parse_order_expr_json_cpp(string)),
- "select": lambda string: deserialize_ast(_parse_select_json_cpp(string)),
- "full_template_string": lambda string: deserialize_ast(_parse_full_template_string_json_cpp(string)),
- "program": lambda string: deserialize_ast(_parse_program_json_cpp(string)),
+ ParseRule.EXPR: lambda string, start: deserialize_ast(_parse_expr_json_cpp(string, is_internal=start is None)),
+ ParseRule.ORDER_EXPR: lambda string: deserialize_ast(_parse_order_expr_json_cpp(string)),
+ ParseRule.SELECT: lambda string: deserialize_ast(_parse_select_json_cpp(string)),
+ ParseRule.FULL_TEMPLATE_STRING: lambda string: deserialize_ast(_parse_full_template_string_json_cpp(string)),
+ ParseRule.PROGRAM: lambda string: deserialize_ast(_parse_program_json_cpp(string)),
},
}
-RULE_TO_HISTOGRAM: dict[Literal["expr", "order_expr", "select", "full_template_string"], Histogram] = {
- cast(Literal["expr", "order_expr", "select", "full_template_string"], rule): Histogram(
+RULE_TO_HISTOGRAM: dict[ParseRule, Histogram] = {
+ rule: Histogram(
f"parse_{rule}_seconds",
f"Time to parse {rule} expression",
labelnames=["backend"],
)
- for rule in ("expr", "order_expr", "select", "full_template_string")
+ for rule in (ParseRule.EXPR, ParseRule.ORDER_EXPR, ParseRule.SELECT, ParseRule.FULL_TEMPLATE_STRING)
}
DEFAULT_BACKEND: HogQLParserBackend = "cpp-json"
+# Two caches so a flood of unique user-generated queries can't displace the
+# hot in-code-literal entries. Origin is auto-detected via the call-stack
+# `co_consts` walk; callers can override via `cache_origin`.
+
+_BUILTIN_CACHE_SIZE = 256
+_USER_CACHE_SIZE = 512
+_LITERAL_DETECTION_FRAME_DEPTH = 40
+# Short identifier-shaped strings are auto-interned by CPython and can
+# spuriously identity-match `co_consts` elsewhere, misrouting user input.
+_LITERAL_DETECTION_MIN_LEN = 32
+
+# Skip caching very short queries — they parse fast enough that caching
+# adds no measurable speedup and they'd churn cache slots that longer,
+# higher-value entries could use. Cap the upper end too, to bound memory
+# from user-controlled inputs. Explicit `cache_origin=BUILTIN` bypasses
+# only the upper bound (trusted opt-in for large queries — some in-code
+# templates run past this).
+_MIN_CACHEABLE_STATEMENT_LEN = 40
+_MAX_CACHEABLE_STATEMENT_LEN = 4 * 1024
+
+_PARSE_CACHE_EVENTS = Counter(
+ "hogql_parse_cache_events_total",
+ "HogQL parse-cache lookups",
+ labelnames=["origin", "result", "rule"],
+)
+_PARSE_CACHE_SIZE = Gauge(
+ "hogql_parse_cache_size",
+ "Current entries in the HogQL parse cache (compare against the configured maxsize to spot saturation)",
+ labelnames=["cache"],
+ multiprocess_mode="livemax",
+)
+_PARSE_CACHE_MAXSIZE = Gauge(
+ "hogql_parse_cache_maxsize",
+ "Configured maxsize of the HogQL parse cache",
+ labelnames=["cache"],
+ multiprocess_mode="livemax",
+)
+# Bucket boundaries align with the cache size bounds (40 and 4096) so the
+# fraction of statements below the min or above the max is directly
+# readable from the histogram.
+_PARSE_STATEMENT_LENGTH = Histogram(
+ "hogql_parse_statement_length_chars",
+ "Length of HogQL statements passed to the parser, in characters",
+ labelnames=["rule"],
+ buckets=(16, 32, 40, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 32768, 131072, 524288),
+)
+
+
+def _looks_like_code_literal(s: str) -> bool:
+ """True if ``s`` is a string literal somewhere in the active call stack.
+
+ Python literals share identity with their frame's ``co_consts``;
+ runtime-constructed strings don't. Module/class-level constants
+ referenced via ``LOAD_GLOBAL`` are missed — callers pass
+ ``cache_origin=CacheOrigin.BUILTIN`` explicitly for those.
+
+ This is a best-effort heuristic. A wrong classification only affects
+ which bucket a cache entry lands in; the returned AST is the same
+ either way, so functional behavior is correct regardless. The cost
+ of a miss is at worst a less-optimal cache layout.
+ """
+ if len(s) < _LITERAL_DETECTION_MIN_LEN:
+ return False
+ frame: FrameType | None = sys._getframe(1)
+ for _ in range(_LITERAL_DETECTION_FRAME_DEPTH):
+ if frame is None:
+ return False
+ for const in frame.f_code.co_consts:
+ if const is s:
+ return True
+ frame = frame.f_back
+ return False
+
+
+# Sentinel distinguishes "key absent" from a cached ``None``.
+_MISS: Any = object()
+
+_builtin_parse_cache: LRUCache[Any, Any] = LRUCache(maxsize=_BUILTIN_CACHE_SIZE)
+_user_parse_cache: LRUCache[Any, Any] = LRUCache(maxsize=_USER_CACHE_SIZE)
+# `cachetools.LRUCache` is not thread-safe; the lock guards against
+# threaded WSGI/Celery workers.
+_PARSE_CACHE_LOCK = threading.Lock()
+
+_PARSE_CACHE_MAXSIZE.labels(cache=CacheOrigin.BUILTIN).set(_BUILTIN_CACHE_SIZE)
+_PARSE_CACHE_MAXSIZE.labels(cache=CacheOrigin.USER).set(_USER_CACHE_SIZE)
+
+
+def _invoke_parser(backend: HogQLParserBackend, rule: ParseRule, statement: str, start: int | None) -> Any:
+ fn = RULE_TO_PARSE_FUNCTION[backend][rule]
+ # Histogram wraps only the parse so `parse_*_seconds` stays a parser-perf
+ # signal regardless of cache hit rate. Only `expr` takes a `start` arg;
+ # `PROGRAM` is the only rule without a histogram.
+ histogram = RULE_TO_HISTOGRAM.get(rule)
+ if histogram is None:
+ return fn(statement)
+ with histogram.labels(backend=backend).time():
+ return fn(statement, start) if rule == ParseRule.EXPR else fn(statement)
+
+
+def _parse_cached(
+ rule: ParseRule,
+ statement: str,
+ backend: HogQLParserBackend,
+ cache_origin: CacheOrigin,
+ *,
+ start: int | None = None,
+ classify_input: str | None = None,
+) -> Any:
+ """Look up a parsed AST, parsing on miss.
+
+ ``AUTO`` consults both caches before classifying via frame walk, so the
+ walk is on the cold path only. Explicit ``BUILTIN``/``USER`` only
+ consult their own cache.
+
+ ``classify_input`` lets callers key the cache on a derived string while
+ classifying on the original (e.g. ``parse_string_template`` keys on
+ ``"F'" + string`` but the frame literal it wants to match is ``string``).
+
+ Returns a deepcopy on hit so the resolver/printer can mutate freely.
+ The miss path returns the fresh parse directly and stores the deepcopy.
+ """
+ # Coerce so a stringly-typed call validates and a typo raises.
+ cache_origin = CacheOrigin(cache_origin)
+
+ _PARSE_STATEMENT_LENGTH.labels(rule=rule).observe(len(statement))
+
+ if len(statement) < _MIN_CACHEABLE_STATEMENT_LEN or (
+ cache_origin != CacheOrigin.BUILTIN and len(statement) > _MAX_CACHEABLE_STATEMENT_LEN
+ ):
+ _PARSE_CACHE_EVENTS.labels(origin=cache_origin, result="skip", rule=rule).inc()
+ return _invoke_parser(backend, rule, statement, start)
+
+ key = (statement, backend, rule, start)
+
+ if cache_origin == CacheOrigin.AUTO:
+ with _PARSE_CACHE_LOCK:
+ cached = _builtin_parse_cache.get(key, _MISS)
+ if cached is _MISS:
+ cached = _user_parse_cache.get(key, _MISS)
+ hit_origin = CacheOrigin.USER if cached is not _MISS else None
+ else:
+ hit_origin = CacheOrigin.BUILTIN
+ if hit_origin is not None:
+ _PARSE_CACHE_EVENTS.labels(origin=hit_origin, result="hit", rule=rule).inc()
+ return copy.deepcopy(cached)
+ cache_origin = (
+ CacheOrigin.BUILTIN
+ if _looks_like_code_literal(classify_input if classify_input is not None else statement)
+ else CacheOrigin.USER
+ )
+ else:
+ cache = _builtin_parse_cache if cache_origin == CacheOrigin.BUILTIN else _user_parse_cache
+ with _PARSE_CACHE_LOCK:
+ cached = cache.get(key, _MISS)
+ if cached is not _MISS:
+ _PARSE_CACHE_EVENTS.labels(origin=cache_origin, result="hit", rule=rule).inc()
+ return copy.deepcopy(cached)
+
+ # Parse outside the lock — it's the expensive part, and concurrent parses
+ # of the same key race idempotently.
+ cache = _builtin_parse_cache if cache_origin == CacheOrigin.BUILTIN else _user_parse_cache
+ parsed = _invoke_parser(backend, rule, statement, start)
+ cached_copy = copy.deepcopy(parsed)
+ with _PARSE_CACHE_LOCK:
+ cache[key] = cached_copy
+ currsize = cache.currsize
+ _PARSE_CACHE_EVENTS.labels(origin=cache_origin, result="miss", rule=rule).inc()
+ _PARSE_CACHE_SIZE.labels(cache=cache_origin).set(currsize)
+ return parsed
+
+
+def clear_parse_caches() -> None:
+ """Drop both parse caches. Used by tests."""
+ with _PARSE_CACHE_LOCK:
+ _builtin_parse_cache.clear()
+ _user_parse_cache.clear()
+ _PARSE_CACHE_SIZE.labels(cache=CacheOrigin.BUILTIN).set(0)
+ _PARSE_CACHE_SIZE.labels(cache=CacheOrigin.USER).set(0)
+
+
def parse_string_template(
string: str,
placeholders: dict[str, ast.Expr] | None = None,
timings: HogQLTimings | None = None,
*,
backend: HogQLParserBackend = DEFAULT_BACKEND,
+ cache_origin: CacheOrigin = CacheOrigin.AUTO,
) -> ast.Call:
"""Parse a full template string without start/end quotes"""
if timings is None:
timings = HogQLTimings()
+ # The cache is keyed on `"F'" + string` (a runtime concat that never
+ # matches a frame literal), so pass the raw `string` as the classify
+ # target — that keeps the frame walk on the cold path here too.
with timings.measure(f"parse_full_template_string_{backend}"):
- with RULE_TO_HISTOGRAM["full_template_string"].labels(backend=backend).time():
- node = RULE_TO_PARSE_FUNCTION[backend]["full_template_string"]("F'" + string)
+ node = _parse_cached(
+ ParseRule.FULL_TEMPLATE_STRING,
+ "F'" + string,
+ backend,
+ cache_origin,
+ classify_input=string,
+ )
if placeholders:
with timings.measure("replace_placeholders"):
node = replace_placeholders(node, placeholders)
@@ -124,14 +333,14 @@ def parse_expr(
timings: HogQLTimings | None = None,
*,
backend: HogQLParserBackend = DEFAULT_BACKEND,
+ cache_origin: CacheOrigin = CacheOrigin.AUTO,
) -> ast.Expr:
if expr == "":
raise SyntaxError("Empty query")
if timings is None:
timings = HogQLTimings()
with timings.measure(f"parse_expr_{backend}"):
- with RULE_TO_HISTOGRAM["expr"].labels(backend=backend).time():
- node = RULE_TO_PARSE_FUNCTION[backend]["expr"](expr, start)
+ node = _parse_cached(ParseRule.EXPR, expr, backend, cache_origin, start=start)
if placeholders:
with timings.measure("replace_placeholders"):
node = replace_placeholders(node, placeholders)
@@ -144,12 +353,12 @@ def parse_order_expr(
timings: HogQLTimings | None = None,
*,
backend: HogQLParserBackend = DEFAULT_BACKEND,
+ cache_origin: CacheOrigin = CacheOrigin.AUTO,
) -> ast.OrderExpr:
if timings is None:
timings = HogQLTimings()
with timings.measure(f"parse_order_expr_{backend}"):
- with RULE_TO_HISTOGRAM["order_expr"].labels(backend=backend).time():
- node = RULE_TO_PARSE_FUNCTION[backend]["order_expr"](order_expr)
+ node = _parse_cached(ParseRule.ORDER_EXPR, order_expr, backend, cache_origin)
if placeholders:
with timings.measure("replace_placeholders"):
node = replace_placeholders(node, placeholders)
@@ -162,15 +371,13 @@ def parse_select(
timings: HogQLTimings | None = None,
*,
backend: HogQLParserBackend = DEFAULT_BACKEND,
+ cache_origin: CacheOrigin = CacheOrigin.AUTO,
) -> ast.SelectQuery | ast.SelectSetQuery:
if timings is None:
timings = HogQLTimings()
with timings.measure(f"parse_select_{backend}"):
- with (
- RULE_TO_HISTOGRAM["select"].labels(backend=backend).time(),
- tracer.start_as_current_span("parse_statement_to_node"),
- ):
- node = RULE_TO_PARSE_FUNCTION[backend]["select"](statement)
+ with tracer.start_as_current_span("parse_statement_to_node"):
+ node = _parse_cached(ParseRule.SELECT, statement, backend, cache_origin)
if placeholders:
with timings.measure("replace_placeholders"), tracer.start_as_current_span("replace_placeholders"):
node = replace_placeholders(node, placeholders)
@@ -182,13 +389,13 @@ def parse_program(
timings: HogQLTimings | None = None,
*,
backend: HogQLParserBackend = DEFAULT_BACKEND,
+ cache_origin: CacheOrigin = CacheOrigin.AUTO,
) -> ast.Program:
if timings is None:
timings = HogQLTimings()
with timings.measure(f"parse_expr_{backend}"):
- with RULE_TO_HISTOGRAM["expr"].labels(backend=backend).time():
- node = RULE_TO_PARSE_FUNCTION[backend]["program"](source)
- return node
+ node = _parse_cached(ParseRule.PROGRAM, source, backend, cache_origin)
+ return cast("ast.Program", node)
def get_parser(query: str) -> HogQLParser:
diff --git a/posthog/hogql/property.py b/posthog/hogql/property.py
index e2c94459ba27..9c0848eec3bb 100644
--- a/posthog/hogql/property.py
+++ b/posthog/hogql/property.py
@@ -43,7 +43,7 @@ from posthog.hogql.database.models import BooleanDatabaseField
from posthog.hogql.database.schema.sessions_v3 import LAZY_SESSIONS_FIELDS
from posthog.hogql.errors import NotImplementedError, QueryError
from posthog.hogql.functions import find_hogql_aggregation
-from posthog.hogql.parser import parse_expr
+from posthog.hogql.parser import CacheOrigin, parse_expr
from posthog.hogql.utils import map_virtual_properties
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
@@ -735,7 +735,7 @@ def property_to_expr(
raise QueryError(f"property_to_expr with property of type {type(property).__name__} not implemented")
if property.type == "hogql":
- return parse_expr(property.key)
+ return parse_expr(property.key, cache_origin=CacheOrigin.USER)
elif property.type == "event_metadata" and scope == "group" and GROUP_KEY_PATTERN.match(property.key) is not None:
group_type_index = property.key.split("_")[1]
operator = cast(Optional[PropertyOperator], property.operator) or PropertyOperator.EXACT
diff --git a/posthog/hogql/test/test_parser_cache.py b/posthog/hogql/test/test_parser_cache.py
new file mode 100644
index 000000000000..1b61c11bf2f8
--- /dev/null
+++ b/posthog/hogql/test/test_parser_cache.py
@@ -0,0 +1,233 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+from posthog.hogql.errors import BaseHogQLError
+from posthog.hogql.parser import (
+ _MAX_CACHEABLE_STATEMENT_LEN,
+ _MIN_CACHEABLE_STATEMENT_LEN,
+ CacheOrigin,
+ _builtin_parse_cache,
+ _looks_like_code_literal,
+ _user_parse_cache,
+ clear_parse_caches,
+ parse_expr,
+ parse_select,
+ parse_string_template,
+)
+
+
+class TestParserCache(BaseTest):
+ def setUp(self):
+ super().setUp()
+ clear_parse_caches()
+
+ def _total_cache_size(self) -> int:
+ return int(_builtin_parse_cache.currsize + _user_parse_cache.currsize)
+
+ def test_cache_hit_returns_equivalent_ast(self):
+ sql = "SELECT count() FROM events WHERE event = '$pageview' -- cache test"
+ first = parse_select(sql)
+ second = parse_select(sql)
+ self.assertEqual(first, second)
+ # Verify the second call was actually a cache hit, not a re-parse.
+ self.assertEqual(self._total_cache_size(), 1)
+
+ def test_cache_hit_returns_distinct_object(self):
+ # The resolver and printer mutate the AST in place — cache hits must
+ # not share node identity with previous returns.
+ sql = "SELECT count() FROM events WHERE event = '$pageview' -- distinct test"
+ first = parse_select(sql)
+ second = parse_select(sql)
+ self.assertIsNot(first, second)
+ self.assertEqual(self._total_cache_size(), 1)
+
+ def test_mutation_does_not_leak_across_calls(self):
+ sql = "SELECT 1 FROM events WHERE event = '$exception' -- mutation isolation"
+ first = parse_select(sql)
+ assert isinstance(first, ast.SelectQuery)
+ first.limit = ast.Constant(value=10)
+ second = parse_select(sql)
+ assert isinstance(second, ast.SelectQuery)
+ self.assertIsNone(second.limit)
+ # The second call must have hit the cache; otherwise mutation isolation
+ # is trivially satisfied by re-parsing, which isn't what we're testing.
+ self.assertEqual(self._total_cache_size(), 1)
+
+ @parameterized.expand(
+ [
+ (CacheOrigin.BUILTIN, lambda: _builtin_parse_cache, lambda: _user_parse_cache),
+ (CacheOrigin.USER, lambda: _user_parse_cache, lambda: _builtin_parse_cache),
+ ]
+ )
+ def test_explicit_origin_routes_to_matching_cache(self, origin, target_getter, other_getter):
+ parse_select(f"SELECT 1 -- routing test {origin}, plenty long enough to cache", cache_origin=origin)
+ self.assertEqual(target_getter().currsize, 1)
+ self.assertEqual(other_getter().currsize, 0)
+
+ def test_auto_detects_function_local_literal(self):
+ # Literal must be long enough to bypass the auto-interning guard
+ # (`_LITERAL_DETECTION_MIN_LEN`).
+ parse_select("SELECT count() FROM events WHERE event = '$exception'")
+ self.assertEqual(_builtin_parse_cache.currsize, 1)
+ self.assertEqual(_user_parse_cache.currsize, 0)
+
+ def test_auto_routes_constructed_strings_to_user_cache(self):
+ # `.join` produces a fresh runtime string. Concat of two string
+ # literals (`"a " + "b"`) would be folded by the compiler into a
+ # single literal and incorrectly look built-in.
+ sql = " ".join(["SELECT", "count()", "FROM", "events", "WHERE", "event", "=", "'$pageview'"])
+ parse_select(sql)
+ self.assertEqual(_user_parse_cache.currsize, 1)
+ self.assertEqual(_builtin_parse_cache.currsize, 0)
+
+ def test_user_pollution_does_not_displace_builtin(self):
+ parse_select(
+ "SELECT 'builtin entry' -- pollution test, plenty long enough to cache",
+ cache_origin=CacheOrigin.BUILTIN,
+ )
+ user_maxsize = int(_user_parse_cache.maxsize)
+ for i in range(user_maxsize + 50):
+ parse_select(
+ f"SELECT {i} -- pollution test row, plenty long enough to cache", cache_origin=CacheOrigin.USER
+ )
+ self.assertEqual(_builtin_parse_cache.currsize, 1)
+ self.assertEqual(_user_parse_cache.currsize, user_maxsize)
+
+ def test_different_placeholders_share_cache_entry(self):
+ # Cache key is the raw SQL; placeholders are substituted on the
+ # deepcopy returned from cache. The whole templated-query workload
+ # depends on this sharing — assert it explicitly.
+ sql = "SELECT {x} FROM events WHERE event = '$pageview' LIMIT {n}"
+
+ first = parse_select(sql, placeholders={"x": ast.Constant(value=1), "n": ast.Constant(value=10)})
+ self.assertEqual(_builtin_parse_cache.currsize + _user_parse_cache.currsize, 1)
+ assert isinstance(first, ast.SelectQuery)
+ first_select = first.select[0]
+ assert isinstance(first_select, ast.Constant)
+ self.assertEqual(first_select.value, 1)
+
+ second = parse_select(sql, placeholders={"x": ast.Constant(value=99), "n": ast.Constant(value=50)})
+ self.assertEqual(_builtin_parse_cache.currsize + _user_parse_cache.currsize, 1)
+ assert isinstance(second, ast.SelectQuery)
+ second_select = second.select[0]
+ assert isinstance(second_select, ast.Constant)
+ self.assertEqual(second_select.value, 99)
+
+ def test_returned_ast_has_independent_nested_objects(self):
+ # deepcopy must reach nested children — mutating a deep field must
+ # not leak to the cached entry.
+ sql = "SELECT count() FROM events WHERE event = '$pageview' -- nested mutation"
+ first = parse_select(sql)
+ assert isinstance(first, ast.SelectQuery) and first.where is not None
+ first.where = ast.Constant(value=False)
+ second = parse_select(sql)
+ assert isinstance(second, ast.SelectQuery) and second.where is not None
+ self.assertNotEqual(second.where, ast.Constant(value=False))
+ # Cache must have served the second call; otherwise this only proves
+ # that a fresh parse produces a fresh AST, which is uninteresting.
+ self.assertEqual(self._total_cache_size(), 1)
+
+ def test_parse_expr_cached_separately_by_start_arg(self):
+ # `parse_expr` short identifier-only inputs route to user cache via
+ # the interning guard; use explicit BUILTIN to test start-arg keying
+ # in isolation.
+ expr = "1 + 1 -- start-arg keying test, long enough to cache"
+ parse_expr(expr, start=0, cache_origin=CacheOrigin.BUILTIN)
+ parse_expr(expr, start=1, cache_origin=CacheOrigin.BUILTIN)
+ self.assertEqual(_builtin_parse_cache.currsize, 2)
+
+ def test_looks_like_code_literal_finds_function_literal(self):
+ s = "this is a literal in this function — definitely past the min length"
+ self.assertTrue(_looks_like_code_literal(s))
+
+ def test_looks_like_code_literal_rejects_constructed_strings(self):
+ # `.join` produces a fresh runtime string (compile-time concat would
+ # be folded into a single literal).
+ s = " ".join(["constructed", "string", "definitely", "long", "enough", "now"])
+ self.assertFalse(_looks_like_code_literal(s))
+
+ def test_looks_like_code_literal_rejects_short_strings(self):
+ # Short identifier-shaped strings may be process-wide-interned by
+ # CPython and falsely identity-match `co_consts` elsewhere.
+ s = "event"
+ self.assertFalse(_looks_like_code_literal(s))
+
+ def test_cache_origin_typo_raises(self):
+ with self.assertRaises(ValueError):
+ parse_select("SELECT 1", cache_origin="buultin") # type: ignore[arg-type]
+
+ @parameterized.expand([(CacheOrigin.AUTO,), (CacheOrigin.USER,)])
+ def test_oversized_query_skips_user_and_auto_caches(self, origin):
+ padding = "x" * (_MAX_CACHEABLE_STATEMENT_LEN + 1)
+ sql = f"SELECT 1 -- {padding}"
+ parse_select(sql, cache_origin=origin)
+ self.assertEqual(_builtin_parse_cache.currsize, 0)
+ self.assertEqual(_user_parse_cache.currsize, 0)
+
+ @parameterized.expand([(CacheOrigin.AUTO,), (CacheOrigin.USER,), (CacheOrigin.BUILTIN,)])
+ def test_undersized_query_skips_cache(self, origin):
+ # Short queries skip caching regardless of origin — even explicit
+ # BUILTIN doesn't bypass the minimum, since the speedup isn't worth
+ # the slot.
+ sql = "SELECT 1"
+ assert len(sql) < _MIN_CACHEABLE_STATEMENT_LEN
+ parse_select(sql, cache_origin=origin)
+ self.assertEqual(_builtin_parse_cache.currsize, 0)
+ self.assertEqual(_user_parse_cache.currsize, 0)
+
+ def test_oversized_query_still_caches_under_explicit_builtin(self):
+ # Explicit BUILTIN bypasses the upper bound (trusted opt-in for
+ # large queries).
+ padding = "x" * (_MAX_CACHEABLE_STATEMENT_LEN + 1)
+ sql = f"SELECT 1 -- {padding}"
+ parse_select(sql, cache_origin=CacheOrigin.BUILTIN)
+ self.assertEqual(_builtin_parse_cache.currsize, 1)
+
+ def test_parse_string_template_literal_routes_to_builtin(self):
+ # The cache key is `"F'" + string` (runtime concat) so naive
+ # auto-detect would never see a built-in literal here — we
+ # classify against the raw `string` arg instead.
+ parse_string_template("hello {x} world, this is a long enough template now")
+ self.assertEqual(_builtin_parse_cache.currsize, 1)
+ self.assertEqual(_user_parse_cache.currsize, 0)
+
+ def test_syntax_errors_are_not_cached(self):
+ # SQL has to clear `_MIN_CACHEABLE_STATEMENT_LEN`; otherwise the
+ # length gate masks the error-path skip we're trying to verify.
+ with self.assertRaises(BaseHogQLError):
+ parse_select(
+ "NOT VALID SQL -- padding to exceed the minimum cacheable length",
+ cache_origin=CacheOrigin.USER,
+ )
+ self.assertEqual(_user_parse_cache.currsize, 0)
+ self.assertEqual(_builtin_parse_cache.currsize, 0)
+
+ @parameterized.expand(
+ [
+ (CacheOrigin.BUILTIN, "SELECT 4 -- prior built-in cache entry, plenty long enough"),
+ (CacheOrigin.USER, "SELECT 5 -- prior user cache entry, also plenty long enough"),
+ ]
+ )
+ def test_auto_path_skips_frame_walk_on_hit(self, prior_origin, sql):
+ parse_select(sql, cache_origin=prior_origin)
+ with patch("posthog.hogql.parser._looks_like_code_literal") as detector:
+ parse_select(sql)
+ detector.assert_not_called()
+
+ @parameterized.expand(
+ [
+ (CacheOrigin.BUILTIN, "hello {x} world, prior built-in template entry, long enough"),
+ (CacheOrigin.USER, "hello {x} world, prior user template entry, also long enough"),
+ ]
+ )
+ def test_parse_string_template_skips_frame_walk_on_hit(self, prior_origin, template):
+ # The cache key is the runtime-concatenated `"F'" + template`, but
+ # the classifier must still run only on the cold path — otherwise
+ # warm template hits pay the 40-frame walk every call.
+ parse_string_template(template, cache_origin=prior_origin)
+ with patch("posthog.hogql.parser._looks_like_code_literal") as detector:
+ parse_string_template(template)
+ detector.assert_not_called()
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 85611d269f51..a3f34ecf8b26 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -15,7 +15,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.filters import replace_filters
-from posthog.hogql.parser import parse_select
+from posthog.hogql.parser import CacheOrigin, parse_select
from posthog.hogql.placeholders import find_placeholders, replace_placeholders
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.user_query_validator import validate_user_query
@@ -59,7 +59,12 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
{key: ast.Constant(value=value) for key, value in self.query.values.items()} if self.query.values else None
)
with self.timings.measure("parse_select"):
- parsed_select = parse_select(self.query.query, timings=self.timings, placeholders=values)
+ parsed_select = parse_select(
+ self.query.query,
+ timings=self.timings,
+ placeholders=values,
+ cache_origin=CacheOrigin.USER,
+ )
finder = find_placeholders(parsed_select)
with self.timings.measure("filters"):
diff --git a/posthog/models/web_preaggregated/__snapshots__/test_web_pre_aggregated_timezones.ambr b/posthog/models/web_preaggregated/__snapshots__/test_web_pre_aggregated_timezones.ambr
index d8ab38ec83d7..e461a33f00bd 100644
--- a/posthog/models/web_preaggregated/__snapshots__/test_web_pre_aggregated_timezones.ambr
+++ b/posthog/models/web_preaggregated/__snapshots__/test_web_pre_aggregated_timezones.ambr
@@ -473,7 +473,15 @@
events__session.session_id AS session_id,
any(events__session.`$is_bounce`) AS is_bounce,
min(events__session.`$start_timestamp`) AS start_timestamp
- FROM events
+ FROM
+ (SELECT events.`$session_id_uuid`,
+ events.distinct_id,
+ events.event,
+ events.person_id,
+ events.`mat_$browser`,
+ events.timestamp
+ FROM events
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(toDate(events.timestamp), '2024-01-14'), lessOrEquals(toDate(events.timestamp), '2024-01-18'))) AS events
LEFT JOIN
(SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'America/Sao_Paulo')), max(toTimeZone(raw_sessions.max_timestamp, 'America/Sao_Paulo'))), 10)))) AS `$is_bounce`,
@@ -489,7 +497,7 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'America/Sao_Paulo'), assumeNotNull(toDateTime('2024-01-15 00:00:00', 'America/Sao_Paulo'))), lessOrEquals(toTimeZone(events.timestamp, 'America/Sao_Paulo'), assumeNotNull(toDateTime('2024-01-16 23:59:59', 'America/Sao_Paulo')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), 1))
+ WHERE and(or(and(greaterOrEquals(toTimeZone(events.timestamp, 'America/Sao_Paulo'), assumeNotNull(toDateTime('2024-01-15 00:00:00', 'America/Sao_Paulo'))), lessOrEquals(toTimeZone(events.timestamp, 'America/Sao_Paulo'), assumeNotNull(toDateTime('2024-01-16 23:59:59', 'America/Sao_Paulo')))), 0), or(equals(events.event, '$pageview'), equals(events.event, '$screen')), 1)
GROUP BY session_id,
breakdown_value)
GROUP BY `context.columns.breakdown_value`