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): un-exclude HogQLX, templates, kv-pairs from grammar fuzzer (#63910)

Robbie10b92271804d
diff --git a/posthog/hogql/scripts/build_grammar_strategies.py b/posthog/hogql/scripts/build_grammar_strategies.py
index afea2650b456..d26b7f5b8db6 100755
--- a/posthog/hogql/scripts/build_grammar_strategies.py
+++ b/posthog/hogql/scripts/build_grammar_strategies.py
@@ -479,6 +479,8 @@ _VARIABLE_CONTENT_TOKENS: frozenset[str] = frozenset(
"QUOTED_IDENTIFIER",
"FLOATING_LITERAL",
"OCTAL_LITERAL",
+ "OCTAL_PREFIX_LITERAL",
+ "BINARY_LITERAL",
"DECIMAL_LITERAL",
"HEXADECIMAL_LITERAL",
"STRING_LITERAL",
@@ -585,28 +587,15 @@ def _alt_to_literal(alt: Alternative, host_token: str, lexer: Grammar) -> str |
# HogQLX and Hog-program productions are explicitly out of scope (per
# product requirements). We carry a hard-coded skip-set; any rule
# alternative that transitively requires an excluded rule is dropped.
-
-EXCLUDED_RULES: frozenset[str] = frozenset(
- {
- # HogQLX
- "hogqlxTagElement",
- "hogqlxChildElement",
- "hogqlxText",
- "hogqlxTagAttribute",
- # Template strings (lexer-mode dependent; not exercised by the
- # grammar PBT — the mode-stack interaction is hand-tested in the
- # parametrised suite and would dominate the grind otherwise)
- "templateString",
- "stringContents",
- "fullTemplateString",
- "stringContentsFull",
- # `kvPair` / `kvPairList` — Hog dict key/value pairs. Not a
- # program statement; left excluded so enabling Hog programs
- # doesn't also widen the expression-strategy surface.
- "kvPair",
- "kvPairList",
- }
-)
+#
+# HogQLX tags, template strings, the lexer mode-stack tokens, and Hog kv-pairs
+# are all enabled. Escape-hatch strategies for their variable-content tokens
+# (HOGQLX_TEXT_TEXT, QUOTE_SINGLE_TEMPLATE*, STRING_TEXT*, ESCAPE_CHAR_COMMON,
+# …) live in `_grammar_token_strategies.py` and are mapped via
+# `_ESCAPE_HATCH_NAMES`. The grammar PBT's space-joined token output is still
+# accepted by the lexer in these modes because STRING_TEXT / FULL_STRING_TEXT
+# / HOGQLX_TEXT_TEXT all permit whitespace within their alphabets.
+EXCLUDED_RULES: frozenset[str] = frozenset()
# NB: the Hog program rules (`program`, `declaration`, `statement`,
# `returnStmt` / `throwStmt` / `tryCatchStmt` / `catchBlock` /
# `ifStmt` / `whileStmt` / `forStmt` / `forInStmt` / `funcStmt` /
@@ -801,7 +790,24 @@ _ESCAPE_HATCH_NAMES: dict[str, str] = {
"OCTAL_LITERAL": "octal_literal_token",
"DECIMAL_LITERAL": "decimal_literal_token",
"HEXADECIMAL_LITERAL": "hexadecimal_literal_token",
+ "BINARY_LITERAL": "binary_literal_token",
+ "OCTAL_PREFIX_LITERAL": "octal_prefix_literal_token",
"STRING_LITERAL": "string_literal_token",
+ # HogQLX / template-string variable-content tokens. These belong to lexer
+ # modes the codegen can't resolve to a literal; strategies in
+ # `_grammar_token_strategies.py` supply short, conservative content.
+ "QUOTE_SINGLE_TEMPLATE": "quote_single_template_token",
+ "QUOTE_SINGLE_TEMPLATE_FULL": "quote_single_template_full_token",
+ "STRING_ESCAPE_TRIGGER": "string_escape_trigger_token",
+ "FULL_STRING_ESCAPE_TRIGGER": "full_string_escape_trigger_token",
+ "STRING_TEXT": "string_text_token",
+ "FULL_STRING_TEXT": "full_string_text_token",
+ "HOGQLX_TEXT_TEXT": "hogqlx_text_token",
+ # ESCAPE_CHAR_COMMON is a lexer-internal subrule of STRING_TEXT /
+ # FULL_STRING_TEXT, never referenced by parser rules directly, so no
+ # escape-hatch is needed. (`escape_char_common_token` still lives in
+ # `_grammar_token_strategies.py` for manual use if a future grammar edit
+ # adds a parser-level reference.)
}
@@ -905,13 +911,22 @@ from typing import Any
from hypothesis import strategies as st
from posthog.hogql.test._grammar_token_strategies import (
+ binary_literal_token,
decimal_literal_token,
floating_literal_token,
+ full_string_escape_trigger_token,
+ full_string_text_token,
hexadecimal_literal_token,
+ hogqlx_text_token,
identifier_token,
octal_literal_token,
+ octal_prefix_literal_token,
+ quote_single_template_full_token,
+ quote_single_template_token,
quoted_identifier_token,
+ string_escape_trigger_token,
string_literal_token,
+ string_text_token,
)
_DEFAULT_DEPTH = 5
diff --git a/posthog/hogql/test/_generated_grammar_strategies.py b/posthog/hogql/test/_generated_grammar_strategies.py
index 42ec8fa772f6..8cda195f4256 100644
--- a/posthog/hogql/test/_generated_grammar_strategies.py
+++ b/posthog/hogql/test/_generated_grammar_strategies.py
@@ -23,13 +23,22 @@ from typing import Any
from hypothesis import strategies as st
from posthog.hogql.test._grammar_token_strategies import (
+ binary_literal_token,
decimal_literal_token,
floating_literal_token,
+ full_string_escape_trigger_token,
+ full_string_text_token,
hexadecimal_literal_token,
+ hogqlx_text_token,
identifier_token,
octal_literal_token,
+ octal_prefix_literal_token,
+ quote_single_template_full_token,
+ quote_single_template_token,
quoted_identifier_token,
+ string_escape_trigger_token,
string_literal_token,
+ string_text_token,
)
_DEFAULT_DEPTH = 5
@@ -443,16 +452,47 @@ def block_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
return gen()
+def kvPair_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(":")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def kvPairList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(kvPair_strategy(_dec(depth))))
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(",")
+ parts.append(draw(kvPair_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(",")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
@functools.cache
def select_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
def gen(draw: Any) -> str:
parts: list[str] = []
- group_idx = draw(st.integers(min_value=0, max_value=1))
+ group_idx = draw(st.integers(min_value=0, max_value=2))
if group_idx == 0:
parts.append(draw(selectSetStmt_strategy(_dec(depth))))
if group_idx == 1:
parts.append(draw(selectStmt_strategy(_dec(depth))))
+ if group_idx == 2:
+ parts.append(draw(hogqlxTagElement_strategy(_dec(depth))))
if _include_optional(draw):
parts.append(";")
parts.append("")
@@ -1838,7 +1878,7 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
def gen(draw: Any) -> str:
parts: list[str] = []
if depth <= 0:
- seed_idx = draw(st.sampled_from([3, 4, 7, 9, 14, 19, 34, 37]))
+ seed_idx = draw(st.sampled_from([3, 5, 7, 9, 14, 19, 39]))
else:
seed_idx = draw(
st.sampled_from(
@@ -1882,6 +1922,8 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
36,
37,
38,
+ 39,
+ 40,
]
)
)
@@ -1927,13 +1969,13 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
if seed_idx == 4:
parts = []
parts.append("interval")
- parts.append(draw(string_literal_token))
+ parts.append(draw(columnExpr_strategy(_dec(depth))))
+ parts.append(draw(interval_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
if seed_idx == 5:
parts = []
parts.append("interval")
- parts.append(draw(columnExpr_strategy(_dec(depth))))
- parts.append(draw(interval_strategy(_dec(depth))))
+ parts.append(draw(string_literal_token))
seed = " ".join(p for p in parts if p)
if seed_idx == 6:
parts = []
@@ -2202,19 +2244,27 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
seed = " ".join(p for p in parts if p)
if seed_idx == 25:
parts = []
- parts.append(draw(literal_strategy(_dec(depth))))
+ parts.append(draw(hogqlxTagElement_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
if seed_idx == 26:
+ parts = []
+ parts.append(draw(templateString_strategy(_dec(depth))))
+ seed = " ".join(p for p in parts if p)
+ if seed_idx == 27:
+ parts = []
+ parts.append(draw(literal_strategy(_dec(depth))))
+ seed = " ".join(p for p in parts if p)
+ if seed_idx == 28:
parts = []
parts.append("-")
parts.append(draw(columnExpr_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
- if seed_idx == 27:
+ if seed_idx == 29:
parts = []
parts.append("not")
parts.append(draw(columnExpr_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
- if seed_idx == 28:
+ if seed_idx == 30:
parts = []
if _include_optional(draw):
parts.append(draw(tableIdentifier_strategy(_dec(depth))))
@@ -2226,7 +2276,7 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
parts.append(draw(identifierList_strategy(_dec(depth))))
parts.append(")")
seed = " ".join(p for p in parts if p)
- if seed_idx == 29:
+ if seed_idx == 31:
parts = []
parts.append("lambda")
parts.append(draw(identifier_strategy(_dec(depth))))
@@ -2238,25 +2288,25 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
parts.append(":")
parts.append(draw(columnExpr_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
- if seed_idx == 30:
+ if seed_idx == 32:
parts = []
parts.append("(")
parts.append(draw(selectSetStmt_strategy(_dec(depth))))
parts.append(")")
seed = " ".join(p for p in parts if p)
- if seed_idx == 31:
+ if seed_idx == 33:
parts = []
parts.append("(")
parts.append(draw(columnExpr_strategy(_dec(depth))))
parts.append(")")
seed = " ".join(p for p in parts if p)
- if seed_idx == 32:
+ if seed_idx == 34:
parts = []
parts.append("(")
parts.append(draw(columnExprList_strategy(_dec(depth))))
parts.append(")")
seed = " ".join(p for p in parts if p)
- if seed_idx == 33:
+ if seed_idx == 35:
parts = []
if _include_optional(draw):
parts.append("array")
@@ -2265,28 +2315,29 @@ def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
parts.append(draw(columnExprList_strategy(_dec(depth))))
parts.append("]")
seed = " ".join(p for p in parts if p)
- if seed_idx == 34:
+ if seed_idx == 36:
parts = []
parts.append("{")
- parts.append("")
+ if _include_optional(draw):
+ parts.append(draw(kvPairList_strategy(_dec(depth))))
parts.append("}")
seed = " ".join(p for p in parts if p)
- if seed_idx == 35:
+ if seed_idx == 37:
parts = []
parts.append(draw(columnLambdaExpr_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
- if seed_idx == 36:
+ if seed_idx == 38:
parts = []
parts.append(draw(identifier_strategy(_dec(depth))))
parts.append(":=")
parts.append(draw(columnExpr_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
- if seed_idx == 37:
+ if seed_idx == 39:
parts = []
parts.append("#")
parts.append(draw(decimal_literal_token))
seed = " ".join(p for p in parts if p)
- if seed_idx == 38:
+ if seed_idx == 40:
parts = []
parts.append(draw(columnIdentifier_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
@@ -2568,6 +2619,103 @@ def columnsReplaceItem_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrateg
return gen()
+def hogqlxChildElement_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ alt_idx = draw(st.integers(min_value=0, max_value=2))
+ if alt_idx == 0:
+ parts = []
+ parts.append(draw(hogqlxTagElement_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(hogqlxText_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 2:
+ parts = []
+ parts.append("{")
+ parts.append(draw(columnExpr_strategy(_dec(depth))))
+ parts.append("}")
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
+def hogqlxText_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(hogqlx_text_token))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def hogqlxTagElement_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ alt_idx = draw(st.integers(min_value=0, max_value=1))
+ if alt_idx == 0:
+ parts = []
+ parts.append("<")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(hogqlxTagAttribute_strategy(_dec(depth))))
+ parts.append("/>")
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append("<")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(hogqlxTagAttribute_strategy(_dec(depth))))
+ parts.append(">")
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(hogqlxChildElement_strategy(_dec(depth))))
+ parts.append("</")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ parts.append(">")
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
+def hogqlxTagAttribute_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ alt_idx = draw(st.integers(min_value=0, max_value=2))
+ if alt_idx == 0:
+ parts = []
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ parts.append("=")
+ parts.append(draw(string_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ parts.append("=")
+ parts.append("{")
+ parts.append(draw(columnExpr_strategy(_dec(depth))))
+ parts.append("}")
+ return " ".join(p for p in parts if p)
+ if alt_idx == 2:
+ parts = []
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
@functools.cache
def withExprList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
@@ -2678,7 +2826,7 @@ def tableExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
def gen(draw: Any) -> str:
parts: list[str] = []
- seed_idx = draw(st.integers(min_value=0, max_value=4))
+ seed_idx = draw(st.integers(min_value=0, max_value=5))
seed = ""
if seed_idx == 0:
parts = []
@@ -2701,6 +2849,10 @@ def tableExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
parts.append(")")
seed = " ".join(p for p in parts if p)
if seed_idx == 4:
+ parts = []
+ parts.append(draw(hogqlxTagElement_strategy(_dec(depth))))
+ seed = " ".join(p for p in parts if p)
+ if seed_idx == 5:
parts = []
parts.append(draw(placeholder_strategy(_dec(depth))))
seed = " ".join(p for p in parts if p)
@@ -2957,11 +3109,11 @@ def numberLiteral_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str
if group_idx == 0:
parts.append(draw(floatingLiteral_strategy(_dec(depth))))
if group_idx == 1:
- parts.append("<unresolved:BINARY_LITERAL>")
+ parts.append(draw(binary_literal_token))
if group_idx == 2:
parts.append(draw(octal_literal_token))
if group_idx == 3:
- parts.append("<unresolved:OCTAL_PREFIX_LITERAL>")
+ parts.append(draw(octal_prefix_literal_token))
if group_idx == 4:
parts.append(draw(decimal_literal_token))
if group_idx == 5:
@@ -3678,7 +3830,94 @@ def string_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
def gen(draw: Any) -> str:
parts: list[str] = []
- parts.append(draw(string_literal_token))
+ if depth <= 0:
+ alt_idx = draw(st.sampled_from([0]))
+ else:
+ alt_idx = draw(st.sampled_from([0, 1]))
+ if alt_idx == 0:
+ parts = []
+ parts.append(draw(string_literal_token))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(templateString_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
+def templateString_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(quote_single_template_token))
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(stringContents_strategy(_dec(depth))))
+ parts.append("'")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def stringContents_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ if depth <= 0:
+ alt_idx = draw(st.sampled_from([1]))
+ else:
+ alt_idx = draw(st.sampled_from([0, 1]))
+ if alt_idx == 0:
+ parts = []
+ parts.append(draw(string_escape_trigger_token))
+ parts.append(draw(columnExpr_strategy(_dec(depth))))
+ parts.append("}")
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(string_text_token))
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
+def fullTemplateString_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(quote_single_template_full_token))
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(stringContentsFull_strategy(_dec(depth))))
+ parts.append("")
return " ".join(p for p in parts if p)
return gen()
+
+
+def stringContentsFull_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ if depth <= 0:
+ alt_idx = draw(st.sampled_from([1]))
+ else:
+ alt_idx = draw(st.sampled_from([0, 1]))
+ if alt_idx == 0:
+ parts = []
+ parts.append(draw(full_string_escape_trigger_token))
+ parts.append(draw(columnExpr_strategy(_dec(depth))))
+ parts.append("}")
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(full_string_text_token))
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
diff --git a/posthog/hogql/test/_grammar_token_strategies.py b/posthog/hogql/test/_grammar_token_strategies.py
index ae52e4ad8c2f..b1883c7b2468 100644
--- a/posthog/hogql/test/_grammar_token_strategies.py
+++ b/posthog/hogql/test/_grammar_token_strategies.py
@@ -215,6 +215,15 @@ octal_literal_token: st.SearchStrategy[str] = st.from_regex(r"0[0-7]{1,6}", full
hexadecimal_literal_token: st.SearchStrategy[str] = st.from_regex(r"0[xX][0-9a-fA-F]{1,6}", fullmatch=True)
+# Binary literal per the lexer: ``BINARY_LITERAL : '0' B BIN_DIGIT+`` where B is
+# case-insensitive ``b`` and BIN_DIGIT is ``[01]``.
+binary_literal_token: st.SearchStrategy[str] = st.from_regex(r"0[bB][01]{1,8}", fullmatch=True)
+
+# Octal-prefix literal: ``'0' [oO] DEC_DIGIT+``. The lexer allows 0-9 here, not
+# just 0-7 — the parser / visitor rejects truly non-octal payloads downstream.
+# Matching the lexer rule faithfully exercises that mismatch handling.
+octal_prefix_literal_token: st.SearchStrategy[str] = st.from_regex(r"0[oO][0-9]{1,6}", fullmatch=True)
+
# Floating literal — ``DECIMAL_LITERAL DOT DEC_DIGIT* E (PLUS|DASH)? DEC_DIGIT+``
# is one valid form. We keep things simple with ``<int>.<int>e<int>``.
@@ -230,3 +239,50 @@ def _floating_literal(draw: Any) -> str:
floating_literal_token: st.SearchStrategy[str] = _floating_literal()
+
+
+# ─── Variable-content tokens for HogQLX / template strings ────────────────────
+# These belong to lexer modes the codegen can't resolve to literal text on its
+# own. Strategies are short and conservative so the surrounding parse stays
+# plausible; the surface we care about exercising is the *grammar rule*, not
+# whatever arbitrary text could legally fit in the token slot.
+
+
+# `f'…'` template-string start. Pushes the lexer into IN_TEMPLATE_STRING mode.
+quote_single_template_token: st.SearchStrategy[str] = st.just("f'")
+
+# `F'…'` full-template start. Pushes IN_FULL_TEMPLATE_STRING.
+quote_single_template_full_token: st.SearchStrategy[str] = st.just("F'")
+
+# `{` inside a template-string body — escapes back into expression mode for
+# the embedded ``{expr}`` chunk. The closing `}` is a separate punctuation
+# token the codegen already knows.
+string_escape_trigger_token: st.SearchStrategy[str] = st.just("{")
+full_string_escape_trigger_token: st.SearchStrategy[str] = st.just("{")
+
+# Body text inside a `f'…'` template (the part between `f'`/`}` and `{`/`'`).
+# The lexer rule excludes ``\``, ``'``, and ``{``; everything else, including
+# whitespace, is fair game. Stay short for legibility.
+string_text_token: st.SearchStrategy[str] = st.text(
+ alphabet="abcdefghijklmnopqrstuvwxyz 0123456789", min_size=1, max_size=8
+)
+
+# Body text inside a `F'…'` full template. The lexer rule for FULL_STRING_TEXT
+# only excludes ``{`` (no quote escaping), so the alphabet can include `'`.
+full_string_text_token: st.SearchStrategy[str] = st.text(
+ alphabet="abcdefghijklmnopqrstuvwxyz '0123456789", min_size=1, max_size=8
+)
+
+# Body text inside a HogQLX tag (`<tag>here</tag>`). HOGQLX_TEXT_TEXT excludes
+# `<` and `{` (the tag and interpolation triggers).
+hogqlx_text_token: st.SearchStrategy[str] = st.text(
+ alphabet="abcdefghijklmnopqrstuvwxyz 0123456789", min_size=1, max_size=8
+)
+
+# Common escape sequences inside string content. Mirrors the lexer's
+# ESCAPE_CHAR_COMMON alternatives (``\b``, ``\f``, ``\r``, ``\n``, ``\t``,
+# ``\0``, ``\a``, ``\v``, ``\\``, ``\xHH``). Each is a complete token, so
+# we sample whole sequences rather than building char-by-char.
+escape_char_common_token: st.SearchStrategy[str] = st.sampled_from(
+ ["\\b", "\\f", "\\r", "\\n", "\\t", "\\0", "\\a", "\\v", "\\\\", "\\x00", "\\xff", "\\xAF"]
+)
diff --git a/posthog/hogql/test/test_parser_grammar_pbt.py b/posthog/hogql/test/test_parser_grammar_pbt.py
index fb4d4f49de7f..939e9639f2e2 100644
--- a/posthog/hogql/test/test_parser_grammar_pbt.py
+++ b/posthog/hogql/test/test_parser_grammar_pbt.py
@@ -46,8 +46,12 @@ from hypothesis import (
from posthog.hogql import ast
from posthog.hogql.errors import BaseHogQLError
-from posthog.hogql.parser import parse_expr, parse_select
-from posthog.hogql.test._generated_grammar_strategies import expr_strategy, select_strategy
+from posthog.hogql.parser import parse_expr, parse_select, parse_string_template
+from posthog.hogql.test._generated_grammar_strategies import (
+ expr_strategy,
+ fullTemplateString_strategy as full_template_string_strategy,
+ select_strategy,
+)
from posthog.hogql.test._grammar_token_strategies import _RESERVED_KEYWORDS
from posthog.hogql.visitor import clear_locations
@@ -523,9 +527,22 @@ def _try_parse(query: str, rule: str, backend: str) -> tuple[bool, ast.AST | Non
the failure. The whole point of the differential PBT is to surface
asymmetric crashes; swallowing them here would defeat that.
"""
- parser_fn = parse_expr if rule == "expr" else parse_select
try:
- node = parser_fn(query, backend=backend) # type: ignore[arg-type]
+ if rule == "expr":
+ node: ast.AST = parse_expr(query, backend=backend) # type: ignore[arg-type]
+ elif rule == "select":
+ node = parse_select(query, backend=backend) # type: ignore[arg-type]
+ elif rule == "full_template_string":
+ # The strategy emits "F'<contents>" (the wrapped F-string grammar form), but
+ # `parse_string_template` takes the inside and re-adds the F-quote itself, so
+ # strip the leading "F'" here. Asserted (rather than `removeprefix`) so a future
+ # strategy or jiggle regression that drops the leading "F'" fails loudly instead
+ # of silently producing "F'F'…" inputs that both backends accept (the second F'
+ # becomes FULL_STRING_TEXT content) and that the parity assertion treats as fine.
+ assert query.startswith("F'"), f"fullTemplateString strategy emitted unexpected prefix: {query!r}"
+ node = parse_string_template(query[2:], backend=backend) # type: ignore[arg-type]
+ else:
+ raise ValueError(f"unknown rule: {rule!r}")
return True, clear_locations(node)
except BaseHogQLError:
return False, None
@@ -621,3 +638,26 @@ class TestSelectGrammarPBT:
@_PBT_SETTINGS
def test_select_backends_agree_with_jiggle(self, query: str) -> None:
_assert_backends_agree(query, rule="select")
+
+
[email protected](_PBT_TIMEOUT_SECONDS)
+class TestFullTemplateStringGrammarPBT:
+ """``parse_string_template`` differential parity over the full
+ ``fullTemplateString`` grammar surface — auto-generated from .g4.
+
+ Covers the standalone ``parseFullTemplateString`` parser entry point
+ (the ``F'…`` form used by the public ``parse_string_template`` API),
+ which isn't reachable from the ``expr``/``select`` grammar rules.
+ The grammar rule is ``QUOTE_SINGLE_TEMPLATE_FULL stringContentsFull* EOF``
+ — no closing quote; the body lexes through to end-of-input.
+ """
+
+ @given(query=full_template_string_strategy())
+ @_PBT_SETTINGS
+ def test_full_template_string_backends_agree(self, query: str) -> None:
+ _assert_backends_agree(query, rule="full_template_string")
+
+ @given(query=full_template_string_strategy().flatmap(_apply_jiggle))
+ @_PBT_SETTINGS
+ def test_full_template_string_backends_agree_with_jiggle(self, query: str) -> None:
+ _assert_backends_agree(query, rule="full_template_string")