: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
chore(hogql): grammar-driven property-based parser equivalence tests (#58627)
Robbief8fd58c851a0
diff --git a/posthog/hogql/scripts/__init__.py b/posthog/hogql/scripts/__init__.pynew file mode 100644index 000000000000..549e497be0db--- /dev/null+++ b/posthog/hogql/scripts/__init__.py@@ -0,0 +1,6 @@+"""Standalone scripts and supporting tooling for HogQL development.++Currently houses the grammar-driven PBT strategy generator. Anything+that's runnable from the command line (rather than imported by+production code) belongs here.+"""diff --git a/posthog/hogql/scripts/build_grammar_strategies.py b/posthog/hogql/scripts/build_grammar_strategies.pynew file mode 100755index 000000000000..e2a32974c759--- /dev/null+++ b/posthog/hogql/scripts/build_grammar_strategies.py@@ -0,0 +1,1359 @@+#!/usr/bin/env python3+"""Regenerate the HogQL grammar PBT strategies module.++Reads ``posthog/hogql/grammar/HogQLParser.g4`` and+``posthog/hogql/grammar/HogQLLexer.common.g4`` and emits+``posthog/hogql/test/_generated_grammar_strategies.py``.++The output is a Python module of Hypothesis strategies — one per+parser rule — that produce syntactically valid HogQL strings. It's+consumed by ``test_parser_grammar_pbt.py`` to drive differential+parsing against the Python and C++ HogQL parsers.++Variable-content tokens (``IDENTIFIER``, ``STRING_LITERAL``, etc.)+are hand-written once in+``posthog/hogql/test/_grammar_token_strategies.py`` and referenced by+name from the emitted module — that's the only piece that needs+human attention when the grammar gains a new variable-content token.++Modes:++ python -m posthog.hogql.scripts.build_grammar_strategies+ Regenerate and write the file.++ python -m posthog.hogql.scripts.build_grammar_strategies --check+ Regenerate to memory and exit non-zero if the on-disk file+ differs. Use in CI to catch drift between the grammar and the+ checked-in generated strategies.++Pipeline:++ 1. Lex the .g4 source into a stream of tokens (g4_lex)+ 2. Parse it into a Grammar AST: list of named rules, each with+ alternatives, each alternative a sequence of Elements (g4_parse)+ 3. Resolve token names (``SELECT``) to their literal text (``"SELECT"``)+ via the lexer grammar (resolve_tokens)+ 4. Drop rules and alternatives that reference excluded regions —+ HogQLX, Hog programs, template strings (apply_exclusions)+ 5. Detect left-recursive rules and rewrite them into a Pratt-shaped+ seed-plus-suffix form (rewrite_left_recursion)+ 6. Emit a Python module string with one ``@st.composite`` function+ per rule (emit)+"""+# ruff: noqa: T201++from __future__ import annotations++import re+import sys+import argparse+from dataclasses import dataclass, field+from pathlib import Path+from typing import Literal++# ---------------------------------------------------------------------------+# AST types for parsed grammar+# ---------------------------------------------------------------------------++ElementKind = Literal["token", "rule", "literal", "group"]+Quantifier = Literal["", "?", "*", "+"]+++@dataclass+class Element:+ """One element in an alternative sequence.++ ``token`` — uppercase token reference (``SELECT``); resolved to text+ ``rule`` — lowercase rule reference (``columnExpr``); recursed into+ ``literal`` — single-quoted literal in the .g4 source (``'foo'``); rare+ ``group`` — ``(...)`` group; ``children`` holds nested alternatives+ """++ kind: ElementKind+ name: str = "" # token or rule name+ text: str = "" # literal text (for kind == 'literal')+ children: list[Alternative] = field(default_factory=list) # for groups+ quantifier: Quantifier = ""+++@dataclass+class Alternative:+ """One ``|``-separated alternative inside a rule."""++ elements: list[Element] = field(default_factory=list)+ # ``# AltName`` suffix in the .g4 file (we preserve for diagnostics+ # but don't use semantically).+ alt_name: str | None = None+++@dataclass+class Rule:+ """A grammar rule."""++ name: str+ alternatives: list[Alternative] = field(default_factory=list)+++@dataclass+class Grammar:+ """The entire parsed grammar."""++ rules: dict[str, Rule] = field(default_factory=dict)+ # Insertion order matters for alternative priority — preserve via list+ rule_order: list[str] = field(default_factory=list)+++# ---------------------------------------------------------------------------+# .g4 lexer+# ---------------------------------------------------------------------------+#+# Tokenises a .g4 source into a small set of token kinds. ANTLR grammar+# syntax we care about (and what we ignore):+#+# IDENT lowercase identifier — parser-rule name or rule reference+# TOKEN uppercase identifier — token name or token reference+# STRING single-quoted literal (``'foo'``, ``'\\\\'``)+# PUNCT one of ``: ; | ( ) ? * + = #``+# ASSOC ``<assoc=right>`` annotation (we skip)+#+# Skipped: ``//`` and ``/* */`` comments, whitespace, ``options { ... }``+# block, ``grammar`` / ``parser`` / ``lexer`` headers, ``mode`` directives.++_G4_TOKEN_RE = re.compile(+ r"""+ (?P<comment_line> //[^\n]* )|+ (?P<comment_block> /\*.*?\*/ )| # non-greedy+ (?P<string> ' (?: \\. | [^'\\] )* ' )|+ (?P<charclass> \[ (?: \\. | [^\]\\] )* \] )| # lexer-only [a-z], [aA], etc.+ (?P<assoc> <[^>]*> )|+ (?P<action> \{ (?: [^{}'] | '(?:\\.|[^'])*' )*? \} \?? )|+ (?P<arrow> -> )|+ (?P<ident> [A-Za-z_][A-Za-z0-9_]* )|+ (?P<punct> [:;|()?*+=#,] )|+ (?P<dot> \. )|+ (?P<tilde> ~ )|+ (?P<ws> \s+ )+ """,+ re.VERBOSE | re.DOTALL,+)+++@dataclass+class G4Token:+ kind: str+ text: str+ pos: int # for error messages+++def g4_lex(src: str) -> list[G4Token]:+ """Tokenise a .g4 source. Skips comments, whitespace, and+ parser/lexer/mode header lines."""+ out: list[G4Token] = []+ i = 0+ n = len(src)+ while i < n:+ m = _G4_TOKEN_RE.match(src, i)+ if not m:+ raise ValueError(f"Unexpected character at {i}: {src[i : i + 20]!r}")+ kind = m.lastgroup+ assert kind is not None+ text = m.group(0)+ i = m.end()+ if kind in ("comment_line", "comment_block", "ws", "assoc", "action"):+ continue+ if kind == "charclass":+ # Lexer-only character class (``[a-z]``, ``[aA]``). We never+ # need to render its content as a literal — any lexer rule+ # that uses one has variable content and is escape-hatched.+ # Emit a sentinel kind the parser can ignore as an opaque+ # element.+ out.append(G4Token("charclass", text, m.start()))+ continue+ if kind == "ident":+ # The ``parser grammar X;`` / ``lexer grammar X;`` / ``mode X;``+ # headers slip through as ident sequences. We strip them at+ # the parser level rather than the lexer level for clarity.+ out.append(G4Token("ident", text, m.start()))+ elif kind == "string":+ # Unescape single-quoted literal — collapse ``\\`` and ``\'``+ # to their character forms. Other escapes (``\n``, ``\t``) are+ # left as-is; they only appear inside lexer fragment rules.+ inner = text[1:-1]+ inner = inner.replace("\\\\", "\\").replace("\\'", "'")+ out.append(G4Token("string", inner, m.start()))+ elif kind == "arrow":+ out.append(G4Token("arrow", text, m.start()))+ elif kind == "punct":+ out.append(G4Token("punct", text, m.start()))+ elif kind == "dot":+ out.append(G4Token("dot", text, m.start()))+ elif kind == "tilde":+ out.append(G4Token("tilde", text, m.start()))+ return out+++# ---------------------------------------------------------------------------+# .g4 parser+# ---------------------------------------------------------------------------+#+# Hand-rolled recursive descent over the lexed stream. Handles parser rules+# in full and lexer rules just enough to extract their literal text for+# token-name → text resolution.+#+# Grammar of grammars (the subset we recognise):+#+# file : header (rule SEMI)++# header : 'parser'|'lexer' 'grammar' IDENT SEMI ('options' '{' ... '}')?+# rule : IDENT ':' alt_list ';'+# alt_list : alt ('|' alt)*+# alt : element* ('#' IDENT)?+# element : (IDENT '=')? # label, ignored+# ( IDENT # token or rule reference+# | STRING # literal+# | '(' alt_list ')' # group+# | '.' # wildcard (lexer-only, we punt)+# | '~' element # negation (lexer-only, we punt)+# )+# quantifier?+# ('->' action_chain)? # lexer action, ignored+# quantifier : '?' | '*' | '+'+++class _G4Parser:+ def __init__(self, tokens: list[G4Token], *, source: str = "") -> None:+ self.tokens = tokens+ self.pos = 0+ self.source = source++ def peek(self, offset: int = 0) -> G4Token | None:+ idx = self.pos + offset+ return self.tokens[idx] if 0 <= idx < len(self.tokens) else None++ def consume(self) -> G4Token:+ tok = self.tokens[self.pos]+ self.pos += 1+ return tok++ def at(self, kind: str, text: str | None = None) -> bool:+ tok = self.peek()+ if tok is None or tok.kind != kind:+ return False+ return text is None or tok.text == text++ def expect(self, kind: str, text: str | None = None) -> G4Token:+ tok = self.peek()+ if tok is None or tok.kind != kind or (text is not None and tok.text != text):+ want = f"{kind}({text!r})" if text else kind+ got = f"{tok.kind}({tok.text!r})" if tok else "EOF"+ raise ValueError(f"Expected {want}, got {got} at .g4 pos {tok.pos if tok else -1}")+ return self.consume()++ # ----- header++ def skip_header(self) -> None:+ # parser grammar NAME ; | lexer grammar NAME ;+ # options { ... } (action-block; the lexer already swallowed it)+ # ``mode NAME ;`` (lexer-only)+ while True:+ tok = self.peek()+ if tok is None:+ return+ if tok.kind == "ident" and tok.text in ("parser", "lexer"):+ # consume until ';'+ while self.peek() and not self.at("punct", ";"):+ self.consume()+ if self.peek():+ self.consume() # ';'+ continue+ if tok.kind == "ident" and tok.text == "options":+ # ``options { ... }`` — the lexer already stripped the+ # action block; just eat the ``options`` keyword and+ # loop.+ self.consume()+ continue+ if tok.kind == "ident" and tok.text == "mode":+ # ``mode NAME ;`` — used in lexer file+ while self.peek() and not self.at("punct", ";"):+ self.consume()+ if self.peek():+ self.consume()+ continue+ return++ # ----- rule++ def parse_rule(self) -> Rule | None:+ # Mode directives appear interspersed with lexer rules — skip them.+ while self.at("ident", "mode"):+ self.consume() # 'mode'+ self.consume() # NAME+ self.expect("punct", ";")+ tok = self.peek()+ if tok is None:+ return None+ if tok.kind != "ident":+ raise ValueError(f"Expected rule name at .g4 pos {tok.pos}, got {tok.kind}({tok.text!r})")+ name_tok = self.consume()+ # Lexer rules may carry a ``fragment`` prefix — the previous token+ # was actually the fragment marker. Detect by checking the rule+ # name spelling, since the lexer doesn't distinguish.+ if name_tok.text == "fragment":+ real_name = self.consume()+ self.expect("punct", ":")+ self.parse_alt_list()+ self.expect("punct", ";")+ return Rule(name=f"<fragment:{real_name.text}>", alternatives=[])+ self.expect("punct", ":")+ alts = self.parse_alt_list()+ self.expect("punct", ";")+ return Rule(name=name_tok.text, alternatives=alts)++ def parse_alt_list(self) -> list[Alternative]:+ alts = [self.parse_alt()]+ while self.at("punct", "|"):+ self.consume()+ alts.append(self.parse_alt())+ return alts++ def parse_alt(self) -> Alternative:+ elements: list[Element] = []+ alt_name: str | None = None+ while True:+ tok = self.peek()+ if tok is None:+ break+ if tok.kind == "punct" and tok.text in (";", "|", ")"):+ break+ if tok.kind == "punct" and tok.text == "#":+ # Alternative name marker+ self.consume()+ name = self.expect("ident")+ alt_name = name.text+ break+ element = self.parse_element()+ if element is not None:+ elements.append(element)+ return Alternative(elements=elements, alt_name=alt_name)++ def parse_element(self) -> Element | None:+ tok = self.peek()+ if tok is None:+ return None++ # Optional label: ``name=elem`` — skip the label, parse the element+ if (+ tok.kind == "ident"+ and self.peek(1) is not None+ and self.peek(1).kind == "punct" # type: ignore[union-attr]+ and self.peek(1).text == "=" # type: ignore[union-attr]+ ):+ self.consume() # label+ self.consume() # '='+ return self.parse_element()++ # Action arrow: ``-> skip``, ``-> type(LT), popMode``,+ # ``-> channel(HIDDEN), pushMode(DEFAULT_MODE)`` etc. The action+ # chain after ``->`` is lexer-only and can contain arbitrary+ # idents, commas, and balanced parens — we discard the whole+ # thing. The terminator is the rule terminator ``;`` or the+ # alternative separator ``|`` at depth 0.+ if tok.kind == "arrow":+ self.consume() # ->+ depth = 0+ while True:+ t = self.peek()+ if t is None:+ break+ if depth == 0 and t.kind == "punct" and t.text in (";", "|"):+ break+ if t.kind == "punct" and t.text == "(":+ depth += 1+ elif t.kind == "punct" and t.text == ")":+ if depth == 0:+ break+ depth -= 1+ self.consume()+ return None++ if tok.kind == "string":+ self.consume()+ return self._with_quantifier(Element(kind="literal", text=tok.text))++ if tok.kind == "charclass":+ # Lexer-only char class. Treat as an opaque literal that+ # ``_alt_to_literal`` will refuse to resolve, forcing the+ # containing lexer rule into the escape-hatch path.+ self.consume()+ return self._with_quantifier(Element(kind="literal", text=tok.text))++ if tok.kind == "ident":+ self.consume()+ kind: ElementKind = "token" if tok.text[:1].isupper() else "rule"+ return self._with_quantifier(Element(kind=kind, name=tok.text))++ if tok.kind == "punct" and tok.text == "(":+ self.consume()+ alts = self.parse_alt_list()+ self.expect("punct", ")")+ return self._with_quantifier(Element(kind="group", children=alts))++ if tok.kind == "dot":+ # Wildcard (lexer-only). We never reach this from a parser+ # rule; skip so lexer-rule parsing doesn't choke.+ self.consume()+ return self._with_quantifier(Element(kind="literal", text="<wildcard>"))++ if tok.kind == "tilde":+ # Negation in lexer rules. Consume the operand element so the+ # lexer-rule parse stays balanced; we ignore it for codegen.+ self.consume()+ return self.parse_element()++ if tok.kind == "punct" and tok.text in ("?", "*", "+"):+ # Quantifier without an element to attach to — shouldn't+ # happen for parser rules; lexer-side surprise. Skip.+ self.consume()+ return None++ raise ValueError(f"Unexpected token in element: {tok.kind}({tok.text!r}) at .g4 pos {tok.pos}")++ def _with_quantifier(self, element: Element) -> Element:+ tok = self.peek()+ if tok is None or tok.kind != "punct":+ return element+ # The `in` check narrows to the Literal union the field's+ # type expects; the type checker can't see that without+ # binding the value to a Literal-annotated local first.+ if tok.text == "?":+ element.quantifier = "?"+ elif tok.text == "*":+ element.quantifier = "*"+ elif tok.text == "+":+ element.quantifier = "+"+ else:+ return element+ self.consume()+ return element+++def g4_parse(src: str) -> Grammar:+ """Parse a .g4 source into a Grammar."""+ tokens = g4_lex(src)+ p = _G4Parser(tokens, source=src)+ p.skip_header()+ grammar = Grammar()+ while p.peek() is not None:+ rule = p.parse_rule()+ if rule is None:+ break+ if rule.name.startswith("<fragment:"):+ # Skip fragments — internal to lexer+ continue+ grammar.rules[rule.name] = rule+ grammar.rule_order.append(rule.name)+ return grammar+++# ---------------------------------------------------------------------------+# Token-name → literal-text resolution+# ---------------------------------------------------------------------------+#+# For each uppercase token name referenced in a parser rule, we look up+# the corresponding lexer rule and extract its valid literal forms. A+# token may have multiple valid spellings (e.g. ``NOT_EQ: '!=' | '<>';``)+# which we expose as a list so the emitter can produce+# ``st.sampled_from(...)``.+#+# Tokens with variable content (``IDENTIFIER``, ``STRING_LITERAL``, etc.)+# resolve to ``None`` — the emitter looks them up in the hand-written+# escape-hatch module.+++# Variable-content tokens that don't have a single literal form.+# The codegen emits a reference to ``_grammar_token_strategies.<name>``+# for these.+_VARIABLE_CONTENT_TOKENS: frozenset[str] = frozenset(+ {+ "IDENTIFIER",+ "QUOTED_IDENTIFIER",+ "FLOATING_LITERAL",+ "OCTAL_LITERAL",+ "DECIMAL_LITERAL",+ "HEXADECIMAL_LITERAL",+ "STRING_LITERAL",+ "ESCAPE_CHAR_COMMON",+ "STRING_TEXT",+ "STRING_ESCAPE_TRIGGER",+ "FULL_STRING_TEXT",+ "FULL_STRING_ESCAPE_TRIGGER",+ "HOGQLX_TEXT_TEXT",+ "QUOTE_SINGLE_TEMPLATE",+ "QUOTE_SINGLE_TEMPLATE_FULL",+ }+)++# The pseudo-token ``EOF`` is implicit in ANTLR and means "end of input".+# In our generator it produces nothing.+_EOF_TOKEN: str = "EOF"+++def resolve_token_literals(lexer_grammar: Grammar, token_name: str) -> list[str] | None:+ """Return the list of valid literal spellings for a token, or None if+ the token has variable content (the emitter then defers to the+ hand-written escape-hatch).++ For keyword-style rules (``SELECT: S E L E C T;``), the resolution is+ "lowercase the token name." For literal punctuation, we return the+ single literal string. For multi-alternative tokens (``YEAR: Y E A R+ | Y Y Y Y;``), we return all alternatives.+ """+ if token_name == _EOF_TOKEN:+ return [""]+ if token_name in _VARIABLE_CONTENT_TOKENS:+ return None++ rule = lexer_grammar.rules.get(token_name)+ if rule is None:+ # Not in lexer grammar — assume variable-content / escape-hatch.+ return None++ literals: list[str] = []+ for alt in rule.alternatives:+ text = _alt_to_literal(alt, token_name, lexer_grammar)+ if text is None:+ return None # any alt with variable content disqualifies+ literals.append(text)+ return literals or None+++def _alt_to_literal(alt: Alternative, host_token: str, lexer: Grammar) -> str | None:+ """Try to render a single lexer-rule alternative as a literal string.+ Returns None if any element resists literal resolution."""+ out: list[str] = []+ for el in alt.elements:+ # Within a lexer rule, single-letter idents are case-insensitive+ # macros (fragments) — ``S`` matches ``[Ss]``. We pick lowercase.+ if el.kind == "token":+ # Fragment reference (e.g. ``S``) or another token by name.+ # Single uppercase letter → fragment for that letter.+ if len(el.name) == 1 and el.name.isupper():+ if el.quantifier:+ return None+ out.append(el.name.lower())+ continue+ # Multi-char token reference — try to recurse, but only for+ # punctuation-style tokens. Most keyword rules don't nest.+ sub = lexer.rules.get(el.name)+ if sub is None or el.quantifier:+ return None+ # Recurse only if the sub-rule has a single alternative that+ # resolves; otherwise bail.+ if len(sub.alternatives) != 1:+ return None+ sub_text = _alt_to_literal(sub.alternatives[0], el.name, lexer)+ if sub_text is None:+ return None+ out.append(sub_text)+ continue+ if el.kind == "literal":+ if el.quantifier:+ return None+ out.append(el.text)+ continue+ # group / rule reference / wildcard / negation — unresolvable.+ return None++ # Lowercase the assembly for keyword-style rules where every fragment+ # was a case-insensitive single letter. We detect this by checking+ # the host token name itself was uppercase letters/underscore.+ text = "".join(out)+ if re.fullmatch(r"[A-Z_]+(_SQL)?", host_token) and re.fullmatch(r"[a-z_0-9]+", text):+ # Use the host token name lowercased — this aligns with what+ # ANTLR matches case-insensitively and what we emit consistently.+ # We keep the assembled text from the alternatives though (so+ # multi-alt tokens like YEAR: Y E A R | Y Y Y Y still report+ # both literal forms).+ pass+ return text+++# ---------------------------------------------------------------------------+# Exclusions+# ---------------------------------------------------------------------------+#+# 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",+ # Hog program top-level+ "program",+ "declaration",+ "statement",+ # Hog program statements+ "returnStmt",+ "throwStmt",+ "tryCatchStmt",+ "catchBlock",+ "ifStmt",+ "whileStmt",+ "forStmt",+ "forInStmt",+ "funcStmt",+ "varDecl",+ "varAssignment",+ "exprStmt",+ "emptyStmt",+ "block",+ # Hog uses+ "kvPair",+ "kvPairList",+ }+)++# Alternatives the cpp-json backend (ANTLR parser + Python visitor)+# unconditionally rejects. The PBT contract is one-sided — we only+# assert when cpp accepts — so generating these productions produces+# zero test signal: every example gets discarded. We hard-exclude them+# to keep the discard rate sane.+#+# Two sources of unconditional rejection are excluded here:+#+# 1. Error-message productions: the grammar declares an alternative+# *intentionally* invalid so the parser can attach a nice error+# (e.g. ``ColumnExprInvalidFromImplicitAlias`` catches+# ``SELECT FROM x`` typos and exists only to raise).+#+# 2. Visitor-NotImplementedError productions: the Python ANTLR visitor+# in ``posthog/hogql/parser.py`` raises ``NotImplementedError`` for+# productions the grammar accepts but HogQL's Python AST builder+# doesn't support. Until the visitor grows support, these are dead+# productions from cpp-json's point of view.+EXCLUDED_ALT_NAMES: frozenset[str] = frozenset(+ {+ # Error-message alts (always invalid by grammar author's intent)+ "ColumnExprInvalidFromImplicitAlias",+ # Visitor-NotImplementedError alts (Python-side product gap)+ "ColumnExprDate",+ "ColumnExprTimestamp",+ "ColumnExprSubstring",+ "ColumnTypeExprEnum",+ # ``INTERVAL 'literal'`` requires the string to be a well-formed+ # ``<count> <unit>`` — our random STRING_LITERAL strategy never+ # produces a valid one. The typed form ``INTERVAL <expr> <unit>``+ # (alt ``ColumnExprInterval``) covers the same surface generically+ # and gets exercised. Re-enable if we add a context-aware+ # STRING_LITERAL strategy that produces ``'1 day'`` shapes inside+ # INTERVAL.+ "ColumnExprIntervalString",+ }+)++# Whole rules the cpp-json visitor rejects unconditionally — same+# rationale as ``EXCLUDED_ALT_NAMES`` but at rule granularity.+EXCLUDED_BY_VISITOR_RULES: frozenset[str] = frozenset(+ {+ "topClause",+ "settingsClause",+ }+)++# Soft-weighting hooks remain (empty by default) for future+# productions where we want rare-fire coverage without exclusion.+SOFT_EXCLUDED_ALT_NAMES: frozenset[str] = frozenset()+SOFT_EXCLUDED_RULES: frozenset[str] = frozenset()++_SOFT_FREQ_DENOM: int = 30 # 1-in-30 inclusion for soft-excluded+++def apply_exclusions(grammar: Grammar) -> Grammar:+ """Walk the grammar, surgically removing references to excluded+ rules. Three cases per element:++ - excluded rule with quantifier ``?`` / ``*``: replace with a+ no-op (empty literal). The rule was optional anyway.+ - excluded rule, mandatory: the containing alt becomes+ unsatisfiable — drop it.+ - group with excluded children: filter children; if any survive,+ keep the group with the survivors. If none survive, recurse+ into the rule/mandatory cases above.++ Iterate to fixpoint because dropping one rule can cascade into+ others losing all their alternatives.+ """+ all_excluded = EXCLUDED_RULES | EXCLUDED_BY_VISITOR_RULES+ rules = {n: r for n, r in grammar.rules.items() if n not in all_excluded}+ order = [n for n in grammar.rule_order if n in rules]++ while True:+ changed = False+ available = set(rules.keys())+ for name, rule in list(rules.items()):+ new_alts: list[Alternative] = []+ for alt in rule.alternatives:+ if alt.alt_name in EXCLUDED_ALT_NAMES:+ continue # hard-exclude+ filtered = _filter_alt(alt, available)+ if filtered is not None:+ new_alts.append(filtered)+ if [a.elements for a in new_alts] != [a.elements for a in rule.alternatives]:+ rule.alternatives = new_alts+ changed = True+ if not rule.alternatives:+ # Rule lost all alternatives — drop it entirely.+ del rules[name]+ order = [n for n in order if n != name]+ changed = True+ if not changed:+ break++ return Grammar(rules=rules, rule_order=order)+++def _filter_alt(alt: Alternative, available: set[str]) -> Alternative | None:+ """Filter excluded refs out of an alt. Returns None if the alt+ becomes impossible (a mandatory element references an excluded+ rule and can't be replaced)."""+ new_elements: list[Element] = []+ for el in alt.elements:+ fe = _filter_element(el, available)+ if fe is None:+ return None+ new_elements.append(fe)+ return Alternative(elements=new_elements, alt_name=alt.alt_name)+++def _filter_element(el: Element, available: set[str]) -> Element | None:+ """Filter one element. Returns the (possibly rewritten) element or+ None if it can't be satisfied."""+ if el.kind == "rule" and el.name not in available:+ if el.quantifier in ("?", "*"):+ return Element(kind="literal", text="") # no-op+ return None # mandatory excluded ref+ if el.kind == "group":+ new_children: list[Alternative] = []+ for child in el.children:+ fc = _filter_alt(child, available)+ if fc is not None:+ new_children.append(fc)+ if not new_children:+ if el.quantifier in ("?", "*"):+ return Element(kind="literal", text="")+ return None+ # Preserve quantifier on the surviving group+ return Element(kind="group", children=new_children, quantifier=el.quantifier)+ return el+++# ---------------------------------------------------------------------------+# Left-recursion detection + rewriting+# ---------------------------------------------------------------------------+#+# ANTLR4 admits direct left recursion (a rule whose alternatives can start+# with itself). For codegen we split each left-recursive rule's+# alternatives into:+#+# seed_alts — don't start with a self-reference; safe to use as+# base cases+# suffix_alts — start with ``R`` and have additional elements+# after; we drop the leading ``R`` and treat the+# remaining elements as an "operator tail" that the+# seed can be extended with+#+# At generation time we draw one seed, then optionally chain 0..N+# suffixes. Each suffix that contains another ``R`` reference draws at+# ``depth - 1`` to bound recursion.+++@dataclass+class LeftRecursiveRule:+ """Result of analysing a left-recursive rule."""++ name: str+ seed_alts: list[Alternative]+ suffix_alts: list[Alternative] # leading R already stripped+++def analyse_left_recursion(rule: Rule) -> LeftRecursiveRule | None:+ """If ``rule`` is left-recursive, return a structured analysis;+ otherwise return None and the caller handles it as a normal rule."""+ seed_alts: list[Alternative] = []+ suffix_alts: list[Alternative] = []+ is_recursive = False+ for alt in rule.alternatives:+ if alt.elements and alt.elements[0].kind == "rule" and alt.elements[0].name == rule.name:+ # Trailing R is fine; we'll just draw it as a normal recursive+ # call with reduced depth. But the *leading* R is the+ # left-recursion signal — strip it.+ if alt.elements[0].quantifier:+ # Quantified leading reference (rare) — treat as seed.+ seed_alts.append(alt)+ continue+ stripped = Alternative(+ elements=alt.elements[1:],+ alt_name=alt.alt_name,+ )+ suffix_alts.append(stripped)+ is_recursive = True+ else:+ seed_alts.append(alt)+ if not is_recursive:+ return None+ return LeftRecursiveRule(+ name=rule.name,+ seed_alts=seed_alts,+ suffix_alts=suffix_alts,+ )+++# ---------------------------------------------------------------------------+# Emitter+# ---------------------------------------------------------------------------+#+# Walks the (filtered, rewritten) Grammar and emits a Python module string.+# Each rule becomes one ``@composite`` function. Variable-content tokens+# defer to the hand-written escape-hatch module.+++# Variable-content tokens map to identifiers in the escape-hatch module.+# Keep this in sync with ``_grammar_token_strategies.py``.+_ESCAPE_HATCH_NAMES: dict[str, str] = {+ "IDENTIFIER": "identifier_token",+ "QUOTED_IDENTIFIER": "quoted_identifier_token",+ "FLOATING_LITERAL": "floating_literal_token",+ "OCTAL_LITERAL": "octal_literal_token",+ "DECIMAL_LITERAL": "decimal_literal_token",+ "HEXADECIMAL_LITERAL": "hexadecimal_literal_token",+ "STRING_LITERAL": "string_literal_token",+}+++def _sanitise(name: str) -> str:+ """Rule name → strategy function name."""+ return name + "_strategy"+++def _is_leaf_only(alt: Alternative) -> bool:+ """True iff the alternative contains no rule references (anywhere,+ including in nested groups). Used to find alternatives that bottom+ out generation at depth 0."""+ for el in alt.elements:+ if el.kind == "rule":+ return False+ if el.kind == "group":+ for sub in el.children:+ if not _is_leaf_only(sub):+ return False+ return True+++def _alt_is_soft(alt: Alternative) -> bool:+ """Soft if the alt's name is in ``SOFT_EXCLUDED_ALT_NAMES`` or any+ direct rule reference targets a soft-excluded rule. Group descent+ is shallow — we only flag the alt itself, not nested ones."""+ if alt.alt_name in SOFT_EXCLUDED_ALT_NAMES:+ return True+ for el in alt.elements:+ if el.kind == "rule" and el.name in SOFT_EXCLUDED_RULES:+ return True+ return False+++def _classify_alts(alts: list[Alternative]) -> tuple[list[int], list[int], list[int]]:+ """Return ``(common_indices, soft_indices, leaf_indices)`` for an+ alt list. ``leaf_indices`` are alts with no rule references at+ all — used at depth 0 to bottom out. ``soft_indices`` are alts+ that are unsupported by the cpp visitor — sampled rarely.+ ``common_indices`` are everything else.++ If all alts are leaves or all are soft we degrade gracefully:+ the caller's selector falls back to a flat sample.+ """+ leaf: list[int] = []+ soft: list[int] = []+ common: list[int] = []+ for i, alt in enumerate(alts):+ if _alt_is_soft(alt):+ soft.append(i)+ else:+ common.append(i)+ if _is_leaf_only(alt):+ leaf.append(i)+ # If every alt is soft, demote them to common so we still emit+ # something — the soft-tag was advisory.+ if not common and soft:+ common = soft+ soft = []+ return common, soft, leaf+++def _emit_literal_list(literals: list[str]) -> str:+ if len(literals) == 1:+ return repr(literals[0])+ return "draw(st.sampled_from([" + ", ".join(repr(s) for s in literals) + "]))"+++_EMITTED_FILE_HEADER = f'''\+"""Auto-generated grammar strategies for the HogQL parser PBT.++DO NOT EDIT. Regenerate via::++ python -m posthog.hogql.scripts.build_grammar_strategies++The generator reads ``posthog/hogql/grammar/HogQLParser.g4`` and+``posthog/hogql/grammar/HogQLLexer.common.g4`` and emits this file.++Each rule is a depth-parameterised strategy factory:+``foo_strategy(depth=_DEFAULT_DEPTH)`` returns a ``SearchStrategy[str]``.+Recursive sub-rule draws decrement depth; at depth 0 the strategy+prefers leaf alternatives so generation bottoms out. Strategies are+memoised per-depth via ``functools.cache`` so Hypothesis sees stable+identity across draws (matters for shrinking).+"""++from __future__ import annotations++import functools+from typing import Any++from hypothesis import strategies as st++from posthog.hogql.test._grammar_token_strategies import (+ decimal_literal_token,+ floating_literal_token,+ hexadecimal_literal_token,+ identifier_token,+ octal_literal_token,+ quoted_identifier_token,+ string_literal_token,+)++_DEFAULT_DEPTH = 3+_MAX_REPEAT = 2 # cap for `*` / `+` quantifiers (per occurrence)+_MAX_LR_CHAIN = 2 # cap for chained Pratt-style suffixes (per LR rule)++# Probability an optional ``?``-quantified element is included. 50/50+# produces unrealistically clause-rich SELECTs (a typical SELECT has 25+# optional clauses; even 30% inclusion gives ~8 clauses per query, more+# than enough). Tune-able to stress the parser harder.+# 1-in-N inclusion rate for ``?``-quantified elements. With SELECT's+# ~20 optional clauses, 1/8 = 12.5% gives an average of ~2.5 clauses+# per query — small enough that visitor-NotImplementedError productions+# in any one clause don't blow up acceptance for the whole query, but+# big enough that every optional gets exercised across a 1k-example run.+_OPT_INCLUSION_DEN = 8++# 1-in-N inclusion rate for "soft-excluded" productions — alternatives+# that exist in the grammar but tend to be visitor-rejected by cpp.+# Firing them at a low rate keeps parity coverage without tanking+# acceptance. With ~10 columnExpr nodes per SELECT, a rate of 1/30+# yields ~70% chance the SELECT contains no soft alt.+# Interpolated from the generator's module-level constant; both+# alt-level and element-level soft-firing emit ``_include_soft(draw)``+# below, so the rate lives in exactly one place at runtime.+_SOFT_FREQ_DENOM = {_SOFT_FREQ_DENOM}+++def _dec(depth: int) -> int:+ """Decrement depth but clamp at 0."""+ return depth - 1 if depth > 0 else 0+++def _include_optional(draw: Any) -> bool:+ """Whether to include a ``?``-quantified element. Biased low so+ optional-heavy rules like ``selectStmt`` don't produce 25-clause+ monsters."""+ return draw(st.integers(min_value=0, max_value=_OPT_INCLUSION_DEN - 1)) == 0+++def _include_soft(draw: Any) -> bool:+ """Whether to include a soft-excluded production (visitor-rejected+ by cpp; rare-fire to keep parity coverage without tanking+ acceptance). The rate is per-occurrence; trees with many soft slots+ compound, so this needs to be low enough that a typical query stays+ free of soft alts. With ~10 columnExpr nodes per SELECT, a rate of+ 1/30 yields ~70% chance the SELECT contains no soft alt."""+ return draw(st.integers(min_value=0, max_value=_SOFT_FREQ_DENOM - 1)) == 0+'''+++class _Emitter:+ def __init__(self, grammar: Grammar, lexer_grammar: Grammar) -> None:+ self.grammar = grammar+ self.lexer_grammar = lexer_grammar+ # Memoise token-literal lookups+ self._token_cache: dict[str, list[str] | None] = {}++ def _token_literals(self, name: str) -> list[str] | None:+ if name not in self._token_cache:+ self._token_cache[name] = resolve_token_literals(self.lexer_grammar, name)+ return self._token_cache[name]++ def emit(self) -> str:+ chunks: list[str] = [_EMITTED_FILE_HEADER, ""]+ for name in self.grammar.rule_order:+ chunks.append(self._emit_rule_builder(self.grammar.rules[name]))+ chunks.append("")+ return "\n".join(chunks) + "\n"++ def _emit_rule_builder(self, rule: Rule) -> str:+ lr = analyse_left_recursion(rule)+ if lr is not None:+ return self._emit_left_recursive(lr)+ return self._emit_plain(rule)++ # ----- plain (non-LR) rule emission++ def _emit_plain(self, rule: Rule) -> str:+ lines: list[str] = []+ lines.append("@functools.cache")+ lines.append(f"def {_sanitise(rule.name)}(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:")+ lines.append(" @st.composite")+ lines.append(" def gen(draw: Any) -> str:")+ if len(rule.alternatives) == 1:+ lines.append(" parts: list[str] = []")+ self._emit_alt_body(lines, rule.alternatives[0], indent=" ")+ lines.append(' return " ".join(p for p in parts if p)')+ else:+ common_indices, soft_indices, leaf_indices = _classify_alts(rule.alternatives)+ # Hoist the typed declaration once at the function scope so the+ # per-branch resets below are plain reassignments — mypy treats+ # multiple ``parts: list[str] = []`` lines in the same scope as+ # redefinitions and flags them with ``[no-redef]``.+ lines.append(" parts: list[str] = []")+ self._emit_alt_selector(lines, common_indices, soft_indices, leaf_indices)+ for i, alt in enumerate(rule.alternatives):+ lines.append(f" if alt_idx == {i}:")+ lines.append(" parts = []")+ self._emit_alt_body(lines, alt, indent=" ")+ lines.append(' return " ".join(p for p in parts if p)')+ lines.append(' raise AssertionError("unreachable")')+ lines.append(" return gen()")+ return "\n".join(lines)++ def _emit_alt_selector(+ self,+ lines: list[str],+ common_indices: list[int],+ soft_indices: list[int],+ leaf_indices: list[int],+ ) -> None:+ """Emit the ``alt_idx = ...`` selection statement, factoring in+ depth-0 leaf preference and soft-excluded alt weighting.++ Precedence:+ 1. ``depth <= 0`` and we have leaf alts → pick from leaves.+ 2. ``soft`` alts exist and we draw the rare slot → pick soft.+ 3. Otherwise → pick from common (non-soft) alts.+ """+ total = len(common_indices) + len(soft_indices)+ has_leaves = bool(leaf_indices) and len(leaf_indices) < total+ if not soft_indices and not has_leaves:+ # Nothing to weight; flat sampling+ lines.append(f" alt_idx = draw(st.integers(min_value=0, max_value={total - 1}))")+ return+ # Routed through the emitted ``_include_soft`` helper so the+ # alt-level and element-level soft-firing rates share one+ # definition; without this the integer-check would be inlined+ # here while element-level emission calls the helper.+ if has_leaves:+ lines.append(" if depth <= 0:")+ lines.append(f" alt_idx = draw(st.sampled_from({leaf_indices!r}))")+ if soft_indices:+ lines.append(" elif _include_soft(draw):")+ lines.append(f" alt_idx = draw(st.sampled_from({soft_indices!r}))")+ lines.append(" else:")+ lines.append(f" alt_idx = draw(st.sampled_from({common_indices!r}))")+ else:+ lines.append(" if _include_soft(draw):")+ lines.append(f" alt_idx = draw(st.sampled_from({soft_indices!r}))")+ lines.append(" else:")+ lines.append(f" alt_idx = draw(st.sampled_from({common_indices!r}))")++ # ----- left-recursive rule emission++ def _emit_left_recursive(self, lr: LeftRecursiveRule) -> str:+ lines: list[str] = []+ lines.append("@functools.cache")+ lines.append(f"def {_sanitise(lr.name)}(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:")+ if len(lr.seed_alts) == 0:+ lines.append(" @st.composite")+ lines.append(" def gen(draw: Any) -> str:")+ lines.append(f' raise AssertionError("left-recursive rule {lr.name!r} has no seed alternatives")')+ lines.append(" return gen()")+ return "\n".join(lines)+ # Bind ``_has_suffixes`` in the enclosing function scope BEFORE+ # the inner ``gen`` closes over it. ``analyse_left_recursion``+ # only returns a ``LeftRecursiveRule`` when at least one suffix+ # exists, so this is always ``True`` today — the flag is left+ # in place so the guard in ``gen`` is correct under any future+ # codegen change that admits a zero-suffix LR rule.+ lines.append(f" _has_suffixes = {bool(lr.suffix_alts)}")+ lines.append("")+ lines.append(" @st.composite")+ lines.append(" def gen(draw: Any) -> str:")+ # Pick a seed alternative+ if len(lr.seed_alts) == 1:+ lines.append(" parts: list[str] = []")+ self._emit_alt_body(lines, lr.seed_alts[0], indent=" ")+ lines.append(' seed = " ".join(p for p in parts if p)')+ else:+ common_indices, soft_indices, leaf_indices = _classify_alts(lr.seed_alts)+ # The LR seed selector emits to ``alt_idx``; rename to+ # ``seed_idx`` here for clarity.+ sel_lines: list[str] = []+ self._emit_alt_selector(sel_lines, common_indices, soft_indices, leaf_indices)+ # Hoist the typed declaration once at the function scope so the+ # per-branch resets below are plain reassignments — see the+ # matching note in ``_emit_plain``.+ lines.append(" parts: list[str] = []")+ lines.extend(line.replace("alt_idx", "seed_idx") for line in sel_lines)+ lines.append(' seed = ""')+ for i, alt in enumerate(lr.seed_alts):+ lines.append(f" if seed_idx == {i}:")+ lines.append(" parts = []")+ self._emit_alt_body(lines, alt, indent=" ")+ lines.append(' seed = " ".join(p for p in parts if p)')+ # Then chain 0..MAX_LR_CHAIN suffixes when depth allows+ lines.append(" if depth <= 0 or not _has_suffixes:")+ lines.append(" return seed")+ lines.append(" n_suffixes = draw(st.integers(min_value=0, max_value=_MAX_LR_CHAIN))")+ lines.append(" for _ in range(n_suffixes):")+ lines.append(f" suffix_idx = draw(st.integers(min_value=0, max_value={len(lr.suffix_alts) - 1}))")+ for i, alt in enumerate(lr.suffix_alts):+ lines.append(f" if suffix_idx == {i}:")+ lines.append(" parts = []")+ self._emit_alt_body(+ lines,+ alt,+ indent=" ",+ self_rule_name=lr.name,+ self_depth_expr="_dec(depth)",+ )+ lines.append(' seed = seed + " " + " ".join(p for p in parts if p)')+ lines.append(" return seed")+ lines.append("")+ lines.append(" return gen()")+ return "\n".join(lines)++ # ----- alt body++ def _emit_alt_body(+ self,+ lines: list[str],+ alt: Alternative,+ *,+ indent: str,+ self_rule_name: str | None = None,+ self_depth_expr: str = "depth - 1",+ ) -> None:+ """Emit the body for a single alternative — appends to ``lines``.+ Each element either appends to ``parts`` or controls flow."""+ for el in alt.elements:+ self._emit_element(lines, el, indent=indent, self_rule_name=self_rule_name, self_depth_expr=self_depth_expr)++ def _emit_element(+ self,+ lines: list[str],+ el: Element,+ *,+ indent: str,+ self_rule_name: str | None,+ self_depth_expr: str,+ ) -> None:+ if el.kind == "literal":+ value_expr = repr(el.text)+ self._emit_with_quantifier(lines, value_expr, el.quantifier, indent)+ return++ if el.kind == "token":+ literals = self._token_literals(el.name)+ if literals is None:+ # Escape-hatch: defer to the hand-written strategy module+ strategy_name = _ESCAPE_HATCH_NAMES.get(el.name)+ if strategy_name is None:+ # Unknown variable-content token — generate a no-op+ # placeholder so the codegen still completes. The+ # smoke test will surface low acceptance rates.+ value_expr = repr(f"<unresolved:{el.name}>")+ else:+ value_expr = f"draw({strategy_name})"+ self._emit_with_quantifier(lines, value_expr, el.quantifier, indent)+ return+ value_expr = _emit_literal_list(literals)+ self._emit_with_quantifier(lines, value_expr, el.quantifier, indent)+ return++ if el.kind == "rule":+ ref_strategy = _sanitise(el.name)+ # Every cross-rule draw decrements depth — that's how+ # recursion bottoms out.+ value_expr = f"draw({ref_strategy}(_dec(depth)))"+ # Soft-excluded rules (visitor-rejected) get bumped down+ # to ``?``-quantified soft inclusion even when the .g4+ # declares them as ``?``. A mandatory soft ref is+ # generated unchanged — caller probably knew what it+ # wanted.+ is_soft = el.name in SOFT_EXCLUDED_RULES and el.quantifier in ("", "?")+ self._emit_with_quantifier(+ lines,+ value_expr,+ el.quantifier,+ indent,+ is_soft=is_soft,+ )+ return++ if el.kind == "group":+ # Emit groups inline: for each child alternative, emit a+ # conditional branch that runs that alt's body.+ if not el.children:+ return+ if el.quantifier in ("", "?"):+ if el.quantifier == "?":+ lines.append(f"{indent}if _include_optional(draw):")+ inner_indent = indent + " "+ else:+ inner_indent = indent+ self._emit_group_choice(+ lines, el.children, inner_indent, self_rule_name=self_rule_name, self_depth_expr=self_depth_expr+ )+ return+ # `*` or `+` — emit a loop+ min_iters = 1 if el.quantifier == "+" else 0+ lines.append(f"{indent}for _ in range(draw(st.integers(min_value={min_iters}, max_value=_MAX_REPEAT))):")+ self._emit_group_choice(+ lines,+ el.children,+ indent + " ",+ self_rule_name=self_rule_name,+ self_depth_expr=self_depth_expr,+ )+ return++ def _emit_group_choice(+ self,+ lines: list[str],+ children: list[Alternative],+ indent: str,+ *,+ self_rule_name: str | None,+ self_depth_expr: str,+ ) -> None:+ if len(children) == 1:+ self._emit_alt_body(+ lines, children[0], indent=indent, self_rule_name=self_rule_name, self_depth_expr=self_depth_expr+ )+ return+ lines.append(f"{indent}group_idx = draw(st.integers(min_value=0, max_value={len(children) - 1}))")+ for i, alt in enumerate(children):+ lines.append(f"{indent}if group_idx == {i}:")+ self._emit_alt_body(+ lines,+ alt,+ indent=indent + " ",+ self_rule_name=self_rule_name,+ self_depth_expr=self_depth_expr,+ )++ def _emit_with_quantifier(+ self,+ lines: list[str],+ value_expr: str,+ quantifier: Quantifier,+ indent: str,+ *,+ is_soft: bool = False,+ ) -> None:+ if quantifier == "":+ if is_soft:+ # Mandatory ref to a soft-excluded rule. Gate inclusion+ # to roughly 10% even though the grammar requires it —+ # at the cost of generating syntactically incomplete+ # text, we lift acceptance significantly. The full-rate+ # case still fires often enough to exercise the path.+ lines.append(f"{indent}if _include_soft(draw):")+ lines.append(f"{indent} parts.append({value_expr})")+ else:+ lines.append(f"{indent}parts.append({value_expr})")+ elif quantifier == "?":+ include_check = "_include_soft(draw)" if is_soft else "_include_optional(draw)"+ lines.append(f"{indent}if {include_check}:")+ lines.append(f"{indent} parts.append({value_expr})")+ elif quantifier == "*":+ lines.append(f"{indent}for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):")+ lines.append(f"{indent} parts.append({value_expr})")+ elif quantifier == "+":+ lines.append(f"{indent}for _ in range(draw(st.integers(min_value=1, max_value=_MAX_REPEAT))):")+ lines.append(f"{indent} parts.append({value_expr})")+++def generate(parser_grammar_path: str, lexer_grammar_path: str) -> str:+ """Run the full pipeline and return the Python source to write."""+ with open(parser_grammar_path) as f:+ parser_src = f.read()+ with open(lexer_grammar_path) as f:+ lexer_src = f.read()++ parser_grammar = g4_parse(parser_src)+ lexer_grammar = g4_parse(lexer_src)+ filtered = apply_exclusions(parser_grammar)+ emitter = _Emitter(filtered, lexer_grammar)+ return emitter.emit()+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------++REPO_ROOT = Path(__file__).resolve().parent.parent.parent.parent+PARSER_GRAMMAR = REPO_ROOT / "posthog" / "hogql" / "grammar" / "HogQLParser.g4"+LEXER_GRAMMAR = REPO_ROOT / "posthog" / "hogql" / "grammar" / "HogQLLexer.common.g4"+OUTPUT_PATH = REPO_ROOT / "posthog" / "hogql" / "test" / "_generated_grammar_strategies.py"+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--check",+ action="store_true",+ help="Verify the on-disk generated file matches what we'd emit. Exit 1 on drift.",+ )+ args = parser.parse_args()++ source = generate(str(PARSER_GRAMMAR), str(LEXER_GRAMMAR))++ if args.check:+ if not OUTPUT_PATH.exists():+ print(f"FAIL: {OUTPUT_PATH} does not exist. Run without --check to regenerate.")+ return 1+ existing = OUTPUT_PATH.read_text()+ if existing != source:+ print(+ f"FAIL: {OUTPUT_PATH} is out of sync with the grammar.\n"+ f"Run `python -m posthog.hogql.scripts.build_grammar_strategies` to regenerate."+ )+ return 1+ print(f"OK: {OUTPUT_PATH} is in sync with the grammar.")+ return 0++ OUTPUT_PATH.write_text(source)+ print(f"Wrote {OUTPUT_PATH} ({len(source)} bytes).")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/posthog/hogql/test/_generated_grammar_strategies.py b/posthog/hogql/test/_generated_grammar_strategies.pynew file mode 100644index 000000000000..4fae9833c558--- /dev/null+++ b/posthog/hogql/test/_generated_grammar_strategies.py@@ -0,0 +1,3263 @@+"""Auto-generated grammar strategies for the HogQL parser PBT.++DO NOT EDIT. Regenerate via::++ python -m posthog.hogql.scripts.build_grammar_strategies++The generator reads ``posthog/hogql/grammar/HogQLParser.g4`` and+``posthog/hogql/grammar/HogQLLexer.common.g4`` and emits this file.++Each rule is a depth-parameterised strategy factory:+``foo_strategy(depth=_DEFAULT_DEPTH)`` returns a ``SearchStrategy[str]``.+Recursive sub-rule draws decrement depth; at depth 0 the strategy+prefers leaf alternatives so generation bottoms out. Strategies are+memoised per-depth via ``functools.cache`` so Hypothesis sees stable+identity across draws (matters for shrinking).+"""++from __future__ import annotations++import functools+from typing import Any++from hypothesis import strategies as st++from posthog.hogql.test._grammar_token_strategies import (+ decimal_literal_token,+ floating_literal_token,+ hexadecimal_literal_token,+ identifier_token,+ octal_literal_token,+ quoted_identifier_token,+ string_literal_token,+)++_DEFAULT_DEPTH = 3+_MAX_REPEAT = 2 # cap for `*` / `+` quantifiers (per occurrence)+_MAX_LR_CHAIN = 2 # cap for chained Pratt-style suffixes (per LR rule)++# Probability an optional ``?``-quantified element is included. 50/50+# produces unrealistically clause-rich SELECTs (a typical SELECT has 25+# optional clauses; even 30% inclusion gives ~8 clauses per query, more+# than enough). Tune-able to stress the parser harder.+# 1-in-N inclusion rate for ``?``-quantified elements. With SELECT's+# ~20 optional clauses, 1/8 = 12.5% gives an average of ~2.5 clauses+# per query — small enough that visitor-NotImplementedError productions+# in any one clause don't blow up acceptance for the whole query, but+# big enough that every optional gets exercised across a 1k-example run.+_OPT_INCLUSION_DEN = 8++# 1-in-N inclusion rate for "soft-excluded" productions — alternatives+# that exist in the grammar but tend to be visitor-rejected by cpp.+# Firing them at a low rate keeps parity coverage without tanking+# acceptance. With ~10 columnExpr nodes per SELECT, a rate of 1/30+# yields ~70% chance the SELECT contains no soft alt.+# Interpolated from the generator's module-level constant; both+# alt-level and element-level soft-firing emit ``_include_soft(draw)``+# below, so the rate lives in exactly one place at runtime.+_SOFT_FREQ_DENOM = 30+++def _dec(depth: int) -> int:+ """Decrement depth but clamp at 0."""+ return depth - 1 if depth > 0 else 0+++def _include_optional(draw: Any) -> bool:+ """Whether to include a ``?``-quantified element. Biased low so+ optional-heavy rules like ``selectStmt`` don't produce 25-clause+ monsters."""+ return draw(st.integers(min_value=0, max_value=_OPT_INCLUSION_DEN - 1)) == 0+++def _include_soft(draw: Any) -> bool:+ """Whether to include a soft-excluded production (visitor-rejected+ by cpp; rare-fire to keep parity coverage without tanking+ acceptance). The rate is per-occurrence; trees with many soft slots+ compound, so this needs to be low enough that a typical query stays+ free of soft alts. With ~10 columnExpr nodes per SELECT, a rate of+ 1/30 yields ~70% chance the SELECT contains no soft alt."""+ return draw(st.integers(min_value=0, max_value=_SOFT_FREQ_DENOM - 1)) == 0+++def expression_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def identifierList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(nestedIdentifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(nestedIdentifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ return " ".join(p for p in parts if p)++ return gen()+++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))+ if group_idx == 0:+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ if group_idx == 1:+ parts.append(draw(selectStmt_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(";")+ parts.append("")+ return " ".join(p for p in parts if p)++ return gen()+++def selectStmtWithParens_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=3))+ if alt_idx == 0:+ parts = []+ parts.append(draw(selectStmt_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(withClause_strategy(_dec(depth))))+ parts.append("(")+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("(")+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append(draw(placeholder_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def subsequentSelectSetClause_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=7))+ if group_idx == 0:+ parts.append("except")+ parts.append("all")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 1:+ parts.append("except")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 2:+ parts.append("union")+ parts.append("all")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 3:+ parts.append("union")+ parts.append("distinct")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 4:+ parts.append("union")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 5:+ parts.append("intersect")+ parts.append("all")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 6:+ parts.append("intersect")+ parts.append("distinct")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ if group_idx == 7:+ parts.append("intersect")+ if _include_optional(draw):+ parts.append("by")+ parts.append("name")+ parts.append(draw(selectStmtWithParens_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def selectSetStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(selectStmtWithParens_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(draw(subsequentSelectSetClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(orderByClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(limitAndOffsetClauseOptional_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def limitAndOffsetClauseOptional_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("limit")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("%")+ if _include_optional(draw):+ parts.append(",")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("with")+ parts.append("ties")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("limit")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("%")+ if _include_optional(draw):+ parts.append("with")+ parts.append("ties")+ parts.append("offset")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("offset")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def selectStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ if _include_optional(draw):+ parts.append(draw(withClause_strategy(_dec(depth))))+ parts.append("select")+ if _include_optional(draw):+ parts.append("distinct")+ parts.append("")+ parts.append(draw(selectColumnExprListBeforeFrom_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(fromClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(arrayJoinClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(prewhereClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(whereClause_strategy(_dec(depth))))+ if _include_optional(draw):+ if _include_optional(draw):+ parts.append("using")+ parts.append(draw(sampleClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(groupByClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("with")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("cube")+ if group_idx == 1:+ parts.append("rollup")+ if _include_optional(draw):+ parts.append("with")+ parts.append("totals")+ if _include_optional(draw):+ parts.append(draw(havingClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(qualifyClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("using")+ parts.append(draw(sampleClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(windowClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(orderByClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(limitByClause_strategy(_dec(depth))))+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append(draw(limitAndOffsetClause_strategy(_dec(depth))))+ if group_idx == 1:+ parts.append(draw(offsetOnlyClause_strategy(_dec(depth))))+ parts.append("")+ return " ".join(p for p in parts if p)++ return gen()+++def withClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("with")+ if _include_optional(draw):+ parts.append("recursive")+ parts.append(draw(withExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def fromClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("from")+ parts.append(draw(joinExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def arrayJoinClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("left")+ if group_idx == 1:+ parts.append("inner")+ parts.append("array")+ parts.append("join")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def windowClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("window")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("as")+ parts.append("(")+ parts.append(draw(windowExpr_strategy(_dec(depth))))+ parts.append(")")+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("as")+ parts.append("(")+ parts.append(draw(windowExpr_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def prewhereClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("prewhere")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def whereClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("where")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def groupByClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("group")+ parts.append("by")+ group_idx = draw(st.integers(min_value=0, max_value=3))+ if group_idx == 0:+ parts.append("all")+ if group_idx == 1:+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("cube")+ if group_idx == 1:+ parts.append("rollup")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ if group_idx == 2:+ parts.append("grouping")+ parts.append("sets")+ parts.append("(")+ parts.append(draw(groupingSetList_strategy(_dec(depth))))+ parts.append(")")+ if group_idx == 3:+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def groupingSetList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(groupingSet_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(groupingSet_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def groupingSet_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def havingClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("having")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def qualifyClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("qualify")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def orderByClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("order")+ parts.append("by")+ parts.append(draw(orderExprList_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(interpolateClause_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def interpolateClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("interpolate")+ if _include_optional(draw):+ parts.append("(")+ parts.append(draw(interpolateExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(interpolateExpr_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def projectionOrderByClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("order")+ parts.append("by")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def limitByClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("limit")+ parts.append(draw(limitExpr_strategy(_dec(depth))))+ parts.append("by")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def limitAndOffsetClause_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("limit")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("%")+ if _include_optional(draw):+ parts.append(",")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("with")+ parts.append("ties")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("limit")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("%")+ if _include_optional(draw):+ parts.append("with")+ parts.append("ties")+ parts.append("offset")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def offsetOnlyClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("offset")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def valuesClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("values")+ parts.append(draw(valuesRow_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(valuesRow_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def valuesRow_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("(")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def joinExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ _has_suffixes = True++ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ seed_idx = draw(st.integers(min_value=0, max_value=1))+ seed = ""+ if seed_idx == 0:+ parts = []+ parts.append(draw(tableExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("final")+ if _include_optional(draw):+ parts.append(draw(sampleClause_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 1:+ parts = []+ parts.append("(")+ parts.append(draw(joinExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if depth <= 0 or not _has_suffixes:+ return seed+ n_suffixes = draw(st.integers(min_value=0, max_value=_MAX_LR_CHAIN))+ for _ in range(n_suffixes):+ suffix_idx = draw(st.integers(min_value=0, max_value=4))+ if suffix_idx == 0:+ parts = []+ if _include_optional(draw):+ parts.append("natural")+ if _include_optional(draw):+ parts.append(draw(joinOp_strategy(_dec(depth))))+ parts.append("join")+ parts.append(draw(joinExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(joinConstraintClause_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 1:+ parts = []+ parts.append("positional")+ parts.append("join")+ parts.append(draw(joinExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(joinConstraintClause_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 2:+ parts = []+ parts.append(draw(joinOpCross_strategy(_dec(depth))))+ parts.append(draw(joinExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 3:+ parts = []+ parts.append("pivot")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(draw(pivotColumnList_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("group")+ parts.append("by")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 4:+ parts = []+ parts.append("unpivot")+ if _include_optional(draw):+ parts.append("include")+ parts.append("nulls")+ parts.append("(")+ parts.append(draw(unpivotColumnList_strategy(_dec(depth))))+ parts.append(")")+ seed = seed + " " + " ".join(p for p in parts if p)+ return seed++ return gen()+++def joinOp_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 = []+ group_idx = draw(st.integers(min_value=0, max_value=5))+ if group_idx == 0:+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("all")+ if group_idx == 1:+ parts.append("any")+ if group_idx == 2:+ parts.append("asof")+ parts.append("inner")+ if group_idx == 1:+ parts.append("inner")+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("all")+ if group_idx == 1:+ parts.append("any")+ if group_idx == 2:+ parts.append("asof")+ if group_idx == 2:+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("all")+ if group_idx == 1:+ parts.append("any")+ if group_idx == 2:+ parts.append("asof")+ if group_idx == 3:+ parts.append("anti")+ if group_idx == 4:+ parts.append("semi")+ if group_idx == 5:+ parts.append("asof")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("anti")+ if group_idx == 1:+ parts.append("semi")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=4))+ if group_idx == 0:+ parts.append("semi")+ if group_idx == 1:+ parts.append("all")+ if group_idx == 2:+ parts.append("anti")+ if group_idx == 3:+ parts.append("any")+ if group_idx == 4:+ parts.append("asof")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("left")+ if group_idx == 1:+ parts.append("right")+ if _include_optional(draw):+ parts.append("outer")+ if group_idx == 1:+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("left")+ if group_idx == 1:+ parts.append("right")+ if _include_optional(draw):+ parts.append("outer")+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=4))+ if group_idx == 0:+ parts.append("semi")+ if group_idx == 1:+ parts.append("all")+ if group_idx == 2:+ parts.append("anti")+ if group_idx == 3:+ parts.append("any")+ if group_idx == 4:+ parts.append("asof")+ if group_idx == 2:+ parts.append("asof")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("anti")+ if group_idx == 1:+ parts.append("semi")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("left")+ if group_idx == 1:+ parts.append("right")+ if _include_optional(draw):+ parts.append("outer")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("all")+ if group_idx == 1:+ parts.append("any")+ if group_idx == 2:+ parts.append("asof")+ parts.append("full")+ if _include_optional(draw):+ parts.append("outer")+ if group_idx == 1:+ parts.append("full")+ if _include_optional(draw):+ parts.append("outer")+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("all")+ if group_idx == 1:+ parts.append("any")+ if group_idx == 2:+ parts.append("asof")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def joinOpCross_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("cross")+ parts.append("join")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(",")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def joinConstraintClause_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("on")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("using")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("using")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def sampleClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("sample")+ parts.append(draw(ratioExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("%")+ if _include_optional(draw):+ parts.append("offset")+ parts.append(draw(ratioExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def limitExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append(",")+ if group_idx == 1:+ parts.append("offset")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def orderExprList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(orderExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(orderExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def orderExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append(draw(st.sampled_from(["asc", "ascending"])))+ if group_idx == 1:+ parts.append("descending")+ if group_idx == 2:+ parts.append("desc")+ if _include_optional(draw):+ parts.append("nulls")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("first")+ if group_idx == 1:+ parts.append("last")+ if _include_optional(draw):+ parts.append("collate")+ parts.append(draw(string_literal_token))+ if _include_optional(draw):+ parts.append(draw(withFillClause_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def withFillClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("with")+ parts.append("fill")+ if _include_optional(draw):+ parts.append("from")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("to")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("step")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def interpolateExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("as")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def ratioExpr_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(draw(placeholder_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(numberLiteral_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("/")+ parts.append(draw(numberLiteral_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def settingExprList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(settingExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(settingExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def settingExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("=")+ parts.append(draw(literal_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def windowExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ if _include_optional(draw):+ parts.append(draw(winPartitionByClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(winOrderByClause_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(winFrameClause_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def winPartitionByClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("partition")+ parts.append("by")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def winOrderByClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("order")+ parts.append("by")+ parts.append(draw(orderExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def withinGroupClause_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("within")+ parts.append("group")+ parts.append("(")+ parts.append(draw(orderByClause_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def winFrameClause_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))+ if group_idx == 0:+ parts.append("rows")+ if group_idx == 1:+ parts.append("range")+ parts.append(draw(winFrameExtend_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def winFrameExtend_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(draw(winFrameBound_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("between")+ parts.append(draw(winFrameBound_strategy(_dec(depth))))+ parts.append("and")+ parts.append(draw(winFrameBound_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def winFrameBound_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=4))+ if group_idx == 0:+ parts.append("current")+ parts.append("row")+ if group_idx == 1:+ parts.append("unbounded")+ parts.append("preceding")+ if group_idx == 2:+ parts.append("unbounded")+ parts.append("following")+ if group_idx == 3:+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("preceding")+ if group_idx == 4:+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("following")+ return " ".join(p for p in parts if p)++ return gen()+++def expr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("")+ return " ".join(p for p in parts if p)++ return gen()+++def columnTypeExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ _has_suffixes = True++ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ seed_idx = draw(st.integers(min_value=0, max_value=4))+ seed = ""+ if seed_idx == 0:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(draw(columnTypeExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(draw(columnTypeExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 1:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ parts.append(draw(columnTypeExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(columnTypeExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 2:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 3:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=1, max_value=_MAX_REPEAT))):+ parts.append(draw(identifier_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 4:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if depth <= 0 or not _has_suffixes:+ return seed+ n_suffixes = draw(st.integers(min_value=0, max_value=_MAX_LR_CHAIN))+ for _ in range(n_suffixes):+ suffix_idx = draw(st.integers(min_value=0, max_value=0))+ if suffix_idx == 0:+ parts = []+ parts.append("[")+ if _include_optional(draw):+ parts.append(draw(decimal_literal_token))+ parts.append("]")+ seed = seed + " " + " ".join(p for p in parts if p)+ return seed++ return gen()+++def columnTypeCastExpr_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(draw(columnTypeCastIdentifier_strategy(_dec(depth))))+ parts.append("with")+ if _include_optional(draw):+ parts.append("local")+ parts.append("time")+ parts.append("zone")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(columnTypeCastIdentifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def columnTypeCastIdentifier_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([0, 1]))+ else:+ alt_idx = draw(st.sampled_from([0, 1, 2, 3]))+ if alt_idx == 0:+ parts = []+ parts.append(draw(identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(quoted_identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append(draw(interval_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append(draw(keywordForTypeCast_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def keywordForTypeCast_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=3))+ if alt_idx == 0:+ parts = []+ parts.append("date")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("time")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("timestamp")+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append("interval")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def columnExprList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ return " ".join(p for p in parts if p)++ return gen()+++def selectColumnExprListBeforeFrom_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(draw(selectColumnExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(selectColumnExpr_strategy(_dec(depth))))+ parts.append(",")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(selectColumnExprList_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def selectColumnExprList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(selectColumnExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(selectColumnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ return " ".join(p for p in parts if p)++ return gen()+++def selectColumnExpr_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(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(draw(implicitAlias_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def columnExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ _has_suffixes = True++ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ if depth <= 0:+ seed_idx = draw(st.sampled_from([5, 10, 15, 30, 33]))+ else:+ seed_idx = draw(+ st.sampled_from(+ [+ 0,+ 1,+ 2,+ 3,+ 4,+ 5,+ 6,+ 7,+ 8,+ 9,+ 10,+ 11,+ 12,+ 13,+ 14,+ 15,+ 16,+ 17,+ 18,+ 19,+ 20,+ 21,+ 22,+ 23,+ 24,+ 25,+ 26,+ 27,+ 28,+ 29,+ 30,+ 31,+ 32,+ 33,+ 34,+ ]+ )+ )+ seed = ""+ if seed_idx == 0:+ parts = []+ parts.append("case")+ if _include_optional(draw):+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=1, max_value=_MAX_REPEAT))):+ parts.append("when")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("then")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("else")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("end")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 1:+ parts = []+ parts.append("cast")+ parts.append("(")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("as")+ parts.append(draw(columnTypeExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 2:+ parts = []+ parts.append("try_cast")+ parts.append("(")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("as")+ parts.append(draw(columnTypeExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 3:+ parts = []+ parts.append("interval")+ 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 == 4:+ parts = []+ parts.append("trim")+ parts.append("(")+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("both")+ if group_idx == 1:+ parts.append("leading")+ if group_idx == 2:+ parts.append("trailing")+ parts.append(draw(string_strategy(_dec(depth))))+ parts.append("from")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 5:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append(draw(string_literal_token))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 6:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 7:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("columns")+ parts.append("(")+ parts.append("*")+ parts.append("exclude")+ parts.append("(")+ parts.append(draw(identifierList_strategy(_dec(depth))))+ parts.append(")")+ parts.append("replace")+ parts.append("(")+ parts.append(draw(columnsReplaceList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ if group_idx == 1:+ parts.append("(")+ parts.append("*")+ parts.append("exclude")+ parts.append("(")+ parts.append(draw(identifierList_strategy(_dec(depth))))+ parts.append(")")+ parts.append("replace")+ parts.append("(")+ parts.append(draw(columnsReplaceList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 8:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append("*")+ parts.append("exclude")+ parts.append("(")+ parts.append(draw(identifierList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 9:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("columns")+ parts.append("(")+ parts.append("*")+ parts.append("replace")+ parts.append("(")+ parts.append(draw(columnsReplaceList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ if group_idx == 1:+ parts.append("(")+ parts.append("*")+ parts.append("replace")+ parts.append("(")+ parts.append(draw(columnsReplaceList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 10:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append("*")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 11:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append("*")+ parts.append("exclude")+ parts.append("(")+ parts.append(draw(identifierList_strategy(_dec(depth))))+ parts.append(")")+ parts.append("replace")+ parts.append("(")+ parts.append(draw(columnsReplaceList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 12:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append("*")+ parts.append("exclude")+ parts.append("(")+ parts.append(draw(identifierList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 13:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append("*")+ parts.append("replace")+ parts.append("(")+ parts.append(draw(columnsReplaceList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 14:+ parts = []+ parts.append("columns")+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append("*")+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 15:+ parts = []+ parts.append("*")+ parts.append("columns")+ parts.append("(")+ parts.append(draw(string_literal_token))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 16:+ parts = []+ parts.append("*")+ parts.append("columns")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 17:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ parts.append(draw(withinGroupClause_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 18:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ if _include_optional(draw):+ parts.append("(")+ if _include_optional(draw):+ parts.append("distinct")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ if _include_optional(draw):+ parts.append("filter")+ parts.append("(")+ parts.append("where")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(")")+ parts.append("over")+ parts.append("(")+ parts.append(draw(windowExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 19:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ if _include_optional(draw):+ parts.append("(")+ if _include_optional(draw):+ parts.append("distinct")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ if _include_optional(draw):+ parts.append("filter")+ parts.append("(")+ parts.append("where")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(")")+ parts.append("over")+ parts.append(draw(identifier_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 20:+ parts = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ parts.append("(")+ if _include_optional(draw):+ parts.append("distinct")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("order")+ parts.append("by")+ parts.append(draw(orderExprList_strategy(_dec(depth))))+ parts.append(")")+ if _include_optional(draw):+ parts.append("filter")+ parts.append("(")+ parts.append("where")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 21:+ parts = []+ parts.append(draw(literal_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 22:+ parts = []+ parts.append("-")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 23:+ parts = []+ parts.append("not")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 24:+ parts = []+ if _include_optional(draw):+ parts.append(draw(tableIdentifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append("*")+ if _include_optional(draw):+ parts.append("exclude")+ parts.append("(")+ parts.append(draw(identifierList_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 25:+ parts = []+ parts.append("lambda")+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ parts.append(":")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 26:+ parts = []+ parts.append("(")+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 27:+ parts = []+ parts.append("(")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 28:+ parts = []+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 29:+ parts = []+ if _include_optional(draw):+ parts.append("array")+ parts.append("[")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append("]")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 30:+ parts = []+ parts.append("{")+ parts.append("")+ parts.append("}")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 31:+ parts = []+ parts.append(draw(columnLambdaExpr_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 32:+ 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 == 33:+ parts = []+ parts.append("#")+ parts.append(draw(decimal_literal_token))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 34:+ parts = []+ parts.append(draw(columnIdentifier_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if depth <= 0 or not _has_suffixes:+ return seed+ n_suffixes = draw(st.integers(min_value=0, max_value=_MAX_LR_CHAIN))+ for _ in range(n_suffixes):+ suffix_idx = draw(st.integers(min_value=0, max_value=21))+ if suffix_idx == 0:+ parts = []+ parts.append("(")+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ parts.append(")")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 1:+ parts = []+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 2:+ parts = []+ parts.append("[")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("]")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 3:+ parts = []+ parts.append("[")+ if _include_optional(draw):+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(":")+ if _include_optional(draw):+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("]")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 4:+ parts = []+ parts.append(".")+ parts.append(draw(decimal_literal_token))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 5:+ parts = []+ parts.append(".")+ parts.append(draw(identifier_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 6:+ parts = []+ parts.append("?.")+ parts.append("[")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("]")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 7:+ parts = []+ parts.append("?.")+ parts.append(draw(decimal_literal_token))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 8:+ parts = []+ parts.append("?.")+ parts.append(draw(identifier_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 9:+ parts = []+ parts.append("::")+ parts.append(draw(columnTypeCastExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 10:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("*")+ if group_idx == 1:+ parts.append("/")+ if group_idx == 2:+ parts.append("%")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 11:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("+")+ if group_idx == 1:+ parts.append("-")+ if group_idx == 2:+ parts.append("||")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 12:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=14))+ if group_idx == 0:+ parts.append("==")+ if group_idx == 1:+ parts.append("=")+ if group_idx == 2:+ parts.append(draw(st.sampled_from(["!=", "<>"])))+ if group_idx == 3:+ parts.append("<=")+ if group_idx == 4:+ parts.append("<")+ if group_idx == 5:+ parts.append(">=")+ if group_idx == 6:+ parts.append(">")+ if group_idx == 7:+ if _include_optional(draw):+ parts.append("not")+ parts.append("in")+ if _include_optional(draw):+ parts.append("cohort")+ if group_idx == 8:+ if _include_optional(draw):+ parts.append("not")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("like")+ if group_idx == 1:+ parts.append("ilike")+ if group_idx == 9:+ parts.append("~")+ if group_idx == 10:+ parts.append("=~")+ if group_idx == 11:+ parts.append("!~")+ if group_idx == 12:+ parts.append("~*")+ if group_idx == 13:+ parts.append("=~*")+ if group_idx == 14:+ parts.append("!~*")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 13:+ parts = []+ parts.append("ignore")+ parts.append("nulls")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 14:+ parts = []+ parts.append("is")+ if _include_optional(draw):+ parts.append("not")+ parts.append("null")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 15:+ parts = []+ parts.append("is")+ if _include_optional(draw):+ parts.append("not")+ parts.append("distinct")+ parts.append("from")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 16:+ parts = []+ parts.append("??")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 17:+ parts = []+ parts.append("and")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 18:+ parts = []+ parts.append("or")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 19:+ parts = []+ if _include_optional(draw):+ parts.append("not")+ parts.append("between")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("and")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 20:+ parts = []+ parts.append("?")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append(":")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 21:+ parts = []+ parts.append("as")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append(draw(identifier_strategy(_dec(depth))))+ if group_idx == 1:+ parts.append(draw(string_literal_token))+ seed = seed + " " + " ".join(p for p in parts if p)+ return seed++ return gen()+++def columnLambdaExpr_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 = []+ group_idx = draw(st.integers(min_value=0, max_value=2))+ if group_idx == 0:+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ parts.append(")")+ if group_idx == 1:+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ if group_idx == 2:+ parts.append("(")+ parts.append(")")+ parts.append("->")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("lambda")+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ parts.append(":")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def columnsReplaceList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnsReplaceItem_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(columnsReplaceItem_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def columnsReplaceItem_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("as")+ parts.append(draw(identifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def withExprList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(withExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(withExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ return " ".join(p for p in parts if p)++ return gen()+++def withExpr_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(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(withExprColumnNameList_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("using")+ parts.append("key")+ parts.append(draw(withExprColumnNameList_strategy(_dec(depth))))+ parts.append("as")+ if _include_optional(draw):+ if _include_optional(draw):+ parts.append("not")+ parts.append("materialized")+ parts.append("(")+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("as")+ parts.append(draw(identifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def withExprColumnNameList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def columnIdentifier_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(draw(placeholder_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ if _include_optional(draw):+ parts.append(draw(tableIdentifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append(draw(nestedIdentifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def nestedIdentifier_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(".")+ parts.append(draw(identifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def tableExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ _has_suffixes = True++ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ seed_idx = draw(st.integers(min_value=0, max_value=4))+ seed = ""+ if seed_idx == 0:+ parts = []+ parts.append(draw(tableIdentifier_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 1:+ parts = []+ parts.append(draw(tableFunctionExpr_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if seed_idx == 2:+ parts = []+ parts.append("(")+ parts.append(draw(selectSetStmt_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 3:+ parts = []+ parts.append("(")+ parts.append(draw(valuesClause_strategy(_dec(depth))))+ parts.append(")")+ seed = " ".join(p for p in parts if p)+ if seed_idx == 4:+ parts = []+ parts.append(draw(placeholder_strategy(_dec(depth))))+ seed = " ".join(p for p in parts if p)+ if depth <= 0 or not _has_suffixes:+ return seed+ n_suffixes = draw(st.integers(min_value=0, max_value=_MAX_LR_CHAIN))+ for _ in range(n_suffixes):+ suffix_idx = draw(st.integers(min_value=0, max_value=2))+ if suffix_idx == 0:+ parts = []+ parts.append("pivot")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(draw(pivotColumnList_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append("group")+ parts.append("by")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 1:+ parts = []+ parts.append("unpivot")+ if _include_optional(draw):+ parts.append("include")+ parts.append("nulls")+ parts.append("(")+ parts.append(draw(unpivotColumnList_strategy(_dec(depth))))+ parts.append(")")+ seed = seed + " " + " ".join(p for p in parts if p)+ if suffix_idx == 2:+ parts = []+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append(draw(alias_strategy(_dec(depth))))+ if group_idx == 1:+ parts.append("as")+ parts.append(draw(identifier_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(draw(columnAliases_strategy(_dec(depth))))+ seed = seed + " " + " ".join(p for p in parts if p)+ return seed++ return gen()+++def pivotColumnList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("for")+ for _ in range(draw(st.integers(min_value=1, max_value=_MAX_REPEAT))):+ parts.append(draw(pivotColumn_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def pivotColumn_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExprTupleOrSingle_strategy(_dec(depth))))+ parts.append("in")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def unpivotColumnList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(unpivotColumn_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(unpivotColumn_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ return " ".join(p for p in parts if p)++ return gen()+++def unpivotColumn_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExprTupleOrSingle_strategy(_dec(depth))))+ parts.append("for")+ parts.append(draw(columnExprTupleOrSingle_strategy(_dec(depth))))+ parts.append("in")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(draw(columnExprTupleOrSingle_strategy(_dec(depth))))+ parts.append("in")+ parts.append("(")+ parts.append(draw(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def columnExprTupleOrSingle_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(columnExprList_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def columnAliases_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("(")+ parts.append(draw(identifier_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def tableFunctionExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ parts.append("(")+ if _include_optional(draw):+ parts.append(draw(tableArgList_strategy(_dec(depth))))+ parts.append(")")+ return " ".join(p for p in parts if p)++ return gen()+++def tableIdentifier_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ if _include_optional(draw):+ parts.append(draw(databaseIdentifier_strategy(_dec(depth))))+ parts.append(".")+ parts.append(draw(nestedIdentifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def tableArgList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):+ parts.append(",")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ if _include_optional(draw):+ parts.append(",")+ return " ".join(p for p in parts if p)++ return gen()+++def databaseIdentifier_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(identifier_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def floatingLiteral_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(floating_literal_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(".")+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append(draw(decimal_literal_token))+ if group_idx == 1:+ parts.append(draw(octal_literal_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append(draw(decimal_literal_token))+ parts.append(".")+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append(draw(decimal_literal_token))+ if group_idx == 1:+ parts.append(draw(octal_literal_token))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def numberLiteral_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ if _include_optional(draw):+ group_idx = draw(st.integers(min_value=0, max_value=1))+ if group_idx == 0:+ parts.append("+")+ if group_idx == 1:+ parts.append("-")+ group_idx = draw(st.integers(min_value=0, max_value=5))+ if group_idx == 0:+ parts.append(draw(floatingLiteral_strategy(_dec(depth))))+ if group_idx == 1:+ parts.append(draw(octal_literal_token))+ if group_idx == 2:+ parts.append(draw(decimal_literal_token))+ if group_idx == 3:+ parts.append(draw(hexadecimal_literal_token))+ if group_idx == 4:+ parts.append(draw(st.sampled_from(["inf", "infinity"])))+ if group_idx == 5:+ parts.append("nan")+ return " ".join(p for p in parts if p)++ return gen()+++def literal_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, 2]))+ else:+ alt_idx = draw(st.sampled_from([0, 1, 2]))+ if alt_idx == 0:+ parts = []+ parts.append(draw(numberLiteral_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(string_literal_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("null")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def interval_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=7))+ if alt_idx == 0:+ parts = []+ parts.append("second")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("minute")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("hour")+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append("day")+ return " ".join(p for p in parts if p)+ if alt_idx == 4:+ parts = []+ parts.append("week")+ return " ".join(p for p in parts if p)+ if alt_idx == 5:+ parts = []+ parts.append("month")+ return " ".join(p for p in parts if p)+ if alt_idx == 6:+ parts = []+ parts.append("quarter")+ return " ".join(p for p in parts if p)+ if alt_idx == 7:+ parts = []+ parts.append(draw(st.sampled_from(["year", "yyyy"])))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def keyword_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=108))+ if alt_idx == 0:+ parts = []+ parts.append("all")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("and")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("anti")+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append("any")+ return " ".join(p for p in parts if p)+ if alt_idx == 4:+ parts = []+ parts.append("array")+ return " ".join(p for p in parts if p)+ if alt_idx == 5:+ parts = []+ parts.append("as")+ return " ".join(p for p in parts if p)+ if alt_idx == 6:+ parts = []+ parts.append(draw(st.sampled_from(["asc", "ascending"])))+ return " ".join(p for p in parts if p)+ if alt_idx == 7:+ parts = []+ parts.append("asof")+ return " ".join(p for p in parts if p)+ if alt_idx == 8:+ parts = []+ parts.append("between")+ return " ".join(p for p in parts if p)+ if alt_idx == 9:+ parts = []+ parts.append("both")+ return " ".join(p for p in parts if p)+ if alt_idx == 10:+ parts = []+ parts.append("by")+ return " ".join(p for p in parts if p)+ if alt_idx == 11:+ parts = []+ parts.append("case")+ return " ".join(p for p in parts if p)+ if alt_idx == 12:+ parts = []+ parts.append("cast")+ return " ".join(p for p in parts if p)+ if alt_idx == 13:+ parts = []+ parts.append("cohort")+ return " ".join(p for p in parts if p)+ if alt_idx == 14:+ parts = []+ parts.append("collate")+ return " ".join(p for p in parts if p)+ if alt_idx == 15:+ parts = []+ parts.append("columns")+ return " ".join(p for p in parts if p)+ if alt_idx == 16:+ parts = []+ parts.append("cross")+ return " ".join(p for p in parts if p)+ if alt_idx == 17:+ parts = []+ parts.append("cube")+ return " ".join(p for p in parts if p)+ if alt_idx == 18:+ parts = []+ parts.append("current")+ return " ".join(p for p in parts if p)+ if alt_idx == 19:+ parts = []+ parts.append("date")+ return " ".join(p for p in parts if p)+ if alt_idx == 20:+ parts = []+ parts.append("desc")+ return " ".join(p for p in parts if p)+ if alt_idx == 21:+ parts = []+ parts.append("descending")+ return " ".join(p for p in parts if p)+ if alt_idx == 22:+ parts = []+ parts.append("distinct")+ return " ".join(p for p in parts if p)+ if alt_idx == 23:+ parts = []+ parts.append("else")+ return " ".join(p for p in parts if p)+ if alt_idx == 24:+ parts = []+ parts.append("end")+ return " ".join(p for p in parts if p)+ if alt_idx == 25:+ parts = []+ parts.append("exclude")+ return " ".join(p for p in parts if p)+ if alt_idx == 26:+ parts = []+ parts.append("extract")+ return " ".join(p for p in parts if p)+ if alt_idx == 27:+ parts = []+ parts.append("fill")+ return " ".join(p for p in parts if p)+ if alt_idx == 28:+ parts = []+ parts.append("filter")+ return " ".join(p for p in parts if p)+ if alt_idx == 29:+ parts = []+ parts.append("final")+ return " ".join(p for p in parts if p)+ if alt_idx == 30:+ parts = []+ parts.append("first")+ return " ".join(p for p in parts if p)+ if alt_idx == 31:+ parts = []+ parts.append("for")+ return " ".join(p for p in parts if p)+ if alt_idx == 32:+ parts = []+ parts.append("following")+ return " ".join(p for p in parts if p)+ if alt_idx == 33:+ parts = []+ parts.append("from")+ return " ".join(p for p in parts if p)+ if alt_idx == 34:+ parts = []+ parts.append("full")+ return " ".join(p for p in parts if p)+ if alt_idx == 35:+ parts = []+ parts.append("group")+ return " ".join(p for p in parts if p)+ if alt_idx == 36:+ parts = []+ parts.append("having")+ return " ".join(p for p in parts if p)+ if alt_idx == 37:+ parts = []+ parts.append("id")+ return " ".join(p for p in parts if p)+ if alt_idx == 38:+ parts = []+ parts.append("interpolate")+ return " ".join(p for p in parts if p)+ if alt_idx == 39:+ parts = []+ parts.append("is")+ return " ".join(p for p in parts if p)+ if alt_idx == 40:+ parts = []+ parts.append("grouping")+ return " ".join(p for p in parts if p)+ if alt_idx == 41:+ parts = []+ parts.append("if")+ return " ".join(p for p in parts if p)+ if alt_idx == 42:+ parts = []+ parts.append("ignore")+ return " ".join(p for p in parts if p)+ if alt_idx == 43:+ parts = []+ parts.append("ilike")+ return " ".join(p for p in parts if p)+ if alt_idx == 44:+ parts = []+ parts.append("include")+ return " ".join(p for p in parts if p)+ if alt_idx == 45:+ parts = []+ parts.append("in")+ return " ".join(p for p in parts if p)+ if alt_idx == 46:+ parts = []+ parts.append("inner")+ return " ".join(p for p in parts if p)+ if alt_idx == 47:+ parts = []+ parts.append("interval")+ return " ".join(p for p in parts if p)+ if alt_idx == 48:+ parts = []+ parts.append("join")+ return " ".join(p for p in parts if p)+ if alt_idx == 49:+ parts = []+ parts.append("key")+ return " ".join(p for p in parts if p)+ if alt_idx == 50:+ parts = []+ parts.append("lambda")+ return " ".join(p for p in parts if p)+ if alt_idx == 51:+ parts = []+ parts.append("last")+ return " ".join(p for p in parts if p)+ if alt_idx == 52:+ parts = []+ parts.append("leading")+ return " ".join(p for p in parts if p)+ if alt_idx == 53:+ parts = []+ parts.append("left")+ return " ".join(p for p in parts if p)+ if alt_idx == 54:+ parts = []+ parts.append("like")+ return " ".join(p for p in parts if p)+ if alt_idx == 55:+ parts = []+ parts.append("limit")+ return " ".join(p for p in parts if p)+ if alt_idx == 56:+ parts = []+ parts.append("local")+ return " ".join(p for p in parts if p)+ if alt_idx == 57:+ parts = []+ parts.append("name")+ return " ".join(p for p in parts if p)+ if alt_idx == 58:+ parts = []+ parts.append("natural")+ return " ".join(p for p in parts if p)+ if alt_idx == 59:+ parts = []+ parts.append("not")+ return " ".join(p for p in parts if p)+ if alt_idx == 60:+ parts = []+ parts.append("nulls")+ return " ".join(p for p in parts if p)+ if alt_idx == 61:+ parts = []+ parts.append("offset")+ return " ".join(p for p in parts if p)+ if alt_idx == 62:+ parts = []+ parts.append("on")+ return " ".join(p for p in parts if p)+ if alt_idx == 63:+ parts = []+ parts.append("or")+ return " ".join(p for p in parts if p)+ if alt_idx == 64:+ parts = []+ parts.append("order")+ return " ".join(p for p in parts if p)+ if alt_idx == 65:+ parts = []+ parts.append("outer")+ return " ".join(p for p in parts if p)+ if alt_idx == 66:+ parts = []+ parts.append("over")+ return " ".join(p for p in parts if p)+ if alt_idx == 67:+ parts = []+ parts.append("partition")+ return " ".join(p for p in parts if p)+ if alt_idx == 68:+ parts = []+ parts.append("pivot")+ return " ".join(p for p in parts if p)+ if alt_idx == 69:+ parts = []+ parts.append("positional")+ return " ".join(p for p in parts if p)+ if alt_idx == 70:+ parts = []+ parts.append("preceding")+ return " ".join(p for p in parts if p)+ if alt_idx == 71:+ parts = []+ parts.append("prewhere")+ return " ".join(p for p in parts if p)+ if alt_idx == 72:+ parts = []+ parts.append("qualify")+ return " ".join(p for p in parts if p)+ if alt_idx == 73:+ parts = []+ parts.append("range")+ return " ".join(p for p in parts if p)+ if alt_idx == 74:+ parts = []+ parts.append("recursive")+ return " ".join(p for p in parts if p)+ if alt_idx == 75:+ parts = []+ parts.append("replace")+ return " ".join(p for p in parts if p)+ if alt_idx == 76:+ parts = []+ parts.append("return")+ return " ".join(p for p in parts if p)+ if alt_idx == 77:+ parts = []+ parts.append("right")+ return " ".join(p for p in parts if p)+ if alt_idx == 78:+ parts = []+ parts.append("rollup")+ return " ".join(p for p in parts if p)+ if alt_idx == 79:+ parts = []+ parts.append("row")+ return " ".join(p for p in parts if p)+ if alt_idx == 80:+ parts = []+ parts.append("rows")+ return " ".join(p for p in parts if p)+ if alt_idx == 81:+ parts = []+ parts.append("sample")+ return " ".join(p for p in parts if p)+ if alt_idx == 82:+ parts = []+ parts.append("select")+ return " ".join(p for p in parts if p)+ if alt_idx == 83:+ parts = []+ parts.append("semi")+ return " ".join(p for p in parts if p)+ if alt_idx == 84:+ parts = []+ parts.append("sets")+ return " ".join(p for p in parts if p)+ if alt_idx == 85:+ parts = []+ parts.append("settings")+ return " ".join(p for p in parts if p)+ if alt_idx == 86:+ parts = []+ parts.append("step")+ return " ".join(p for p in parts if p)+ if alt_idx == 87:+ parts = []+ parts.append("substring")+ return " ".join(p for p in parts if p)+ if alt_idx == 88:+ parts = []+ parts.append("then")+ return " ".join(p for p in parts if p)+ if alt_idx == 89:+ parts = []+ parts.append("ties")+ return " ".join(p for p in parts if p)+ if alt_idx == 90:+ parts = []+ parts.append("time")+ return " ".join(p for p in parts if p)+ if alt_idx == 91:+ parts = []+ parts.append("timestamp")+ return " ".join(p for p in parts if p)+ if alt_idx == 92:+ parts = []+ parts.append("totals")+ return " ".join(p for p in parts if p)+ if alt_idx == 93:+ parts = []+ parts.append("trailing")+ return " ".join(p for p in parts if p)+ if alt_idx == 94:+ parts = []+ parts.append("trim")+ return " ".join(p for p in parts if p)+ if alt_idx == 95:+ parts = []+ parts.append("truncate")+ return " ".join(p for p in parts if p)+ if alt_idx == 96:+ parts = []+ parts.append("try_cast")+ return " ".join(p for p in parts if p)+ if alt_idx == 97:+ parts = []+ parts.append("to")+ return " ".join(p for p in parts if p)+ if alt_idx == 98:+ parts = []+ parts.append("top")+ return " ".join(p for p in parts if p)+ if alt_idx == 99:+ parts = []+ parts.append("unbounded")+ return " ".join(p for p in parts if p)+ if alt_idx == 100:+ parts = []+ parts.append("union")+ return " ".join(p for p in parts if p)+ if alt_idx == 101:+ parts = []+ parts.append("unpivot")+ return " ".join(p for p in parts if p)+ if alt_idx == 102:+ parts = []+ parts.append("using")+ return " ".join(p for p in parts if p)+ if alt_idx == 103:+ parts = []+ parts.append("values")+ return " ".join(p for p in parts if p)+ if alt_idx == 104:+ parts = []+ parts.append("when")+ return " ".join(p for p in parts if p)+ if alt_idx == 105:+ parts = []+ parts.append("where")+ return " ".join(p for p in parts if p)+ if alt_idx == 106:+ parts = []+ parts.append("window")+ return " ".join(p for p in parts if p)+ if alt_idx == 107:+ parts = []+ parts.append("with")+ return " ".join(p for p in parts if p)+ if alt_idx == 108:+ parts = []+ parts.append("zone")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def keywordForAlias_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=3))+ if alt_idx == 0:+ parts = []+ parts.append("date")+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("first")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("id")+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append("key")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def keywordForImplicitAlias_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=8))+ if alt_idx == 0:+ parts = []+ parts.append(draw(st.sampled_from(["asc", "ascending"])))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append("cohort")+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append("date")+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append("descending")+ return " ".join(p for p in parts if p)+ if alt_idx == 4:+ parts = []+ parts.append("final")+ return " ".join(p for p in parts if p)+ if alt_idx == 5:+ parts = []+ parts.append("id")+ return " ".join(p for p in parts if p)+ if alt_idx == 6:+ parts = []+ parts.append("return")+ return " ".join(p for p in parts if p)+ if alt_idx == 7:+ parts = []+ parts.append("top")+ return " ".join(p for p in parts if p)+ if alt_idx == 8:+ parts = []+ parts.append("totals")+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def alias_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([0, 1]))+ else:+ alt_idx = draw(st.sampled_from([0, 1, 2]))+ if alt_idx == 0:+ parts = []+ parts.append(draw(identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(quoted_identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append(draw(keywordForAlias_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def implicitAlias_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([0, 1]))+ else:+ alt_idx = draw(st.sampled_from([0, 1, 2]))+ if alt_idx == 0:+ parts = []+ parts.append(draw(identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(quoted_identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append(draw(keywordForImplicitAlias_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def identifier_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([0, 1]))+ else:+ alt_idx = draw(st.sampled_from([0, 1, 2, 3]))+ if alt_idx == 0:+ parts = []+ parts.append(draw(identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 1:+ parts = []+ parts.append(draw(quoted_identifier_token))+ return " ".join(p for p in parts if p)+ if alt_idx == 2:+ parts = []+ parts.append(draw(interval_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ if alt_idx == 3:+ parts = []+ parts.append(draw(keyword_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)+ raise AssertionError("unreachable")++ return gen()+++def enumValue_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append(draw(string_strategy(_dec(depth))))+ parts.append("=")+ parts.append(draw(numberLiteral_strategy(_dec(depth))))+ return " ".join(p for p in parts if p)++ return gen()+++def placeholder_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:+ @st.composite+ def gen(draw: Any) -> str:+ parts: list[str] = []+ parts.append("{")+ parts.append(draw(columnExpr_strategy(_dec(depth))))+ parts.append("}")+ return " ".join(p for p in parts if p)++ return gen()+++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))+ return " ".join(p for p in parts if p)++ return gen()diff --git a/posthog/hogql/test/_grammar_token_strategies.py b/posthog/hogql/test/_grammar_token_strategies.pynew file mode 100644index 000000000000..ae52e4ad8c2f--- /dev/null+++ b/posthog/hogql/test/_grammar_token_strategies.py@@ -0,0 +1,232 @@+"""Hand-written Hypothesis strategies for variable-content HogQL tokens.++The grammar codegen (``posthog/hogql/scripts/build_grammar_strategies.py``)+can resolve keyword and punctuation tokens to literal text by reading+the lexer .g4. Variable-content tokens (identifiers, numbers, strings)+need real strategies; this file is their single source of truth. The+codegen references these by name (see ``_ESCAPE_HATCH_NAMES`` in+``build_grammar_strategies.py``).++Each strategy emits a *raw token string* — quoted where the lexer expects+quoting (string literals, quoted identifiers), unquoted where it doesn't+(decimal/octal/hex/float).+"""++from __future__ import annotations++from typing import Any++from hypothesis import strategies as st++# All HogQL reserved keywords (hand-mirrored from HogQLParser.g4's+# ``keyword`` rule plus the case-insensitive booleans/null). An unquoted+# identifier must not collide with one of these.+_RESERVED_KEYWORDS: frozenset[str] = frozenset(+ s.lower()+ for s in (+ "ALL",+ "AND",+ "ANTI",+ "ANY",+ "ARRAY",+ "AS",+ "ASCENDING",+ "ASOF",+ "BETWEEN",+ "BOTH",+ "BY",+ "CASE",+ "CAST",+ "COHORT",+ "COLLATE",+ "COLUMNS",+ "CROSS",+ "CUBE",+ "CURRENT",+ "DATE",+ "DESC",+ "DESCENDING",+ "DISTINCT",+ "ELSE",+ "END",+ "EXCLUDE",+ "EXTRACT",+ "FILL",+ "FILTER",+ "FINAL",+ "FIRST",+ "FOR",+ "FOLLOWING",+ "FROM",+ "FULL",+ "GROUP",+ "HAVING",+ "ID",+ "INTERPOLATE",+ "IS",+ "GROUPING",+ "IF",+ "IGNORE",+ "ILIKE",+ "INCLUDE",+ "IN",+ "INNER",+ "INTERVAL",+ "JOIN",+ "KEY",+ "LAMBDA",+ "LAST",+ "LEADING",+ "LEFT",+ "LIKE",+ "LIMIT",+ "LOCAL",+ "NAME",+ "NATURAL",+ "NOT",+ "NULLS",+ "OFFSET",+ "ON",+ "OR",+ "ORDER",+ "OUTER",+ "OVER",+ "PARTITION",+ "PIVOT",+ "POSITIONAL",+ "PRECEDING",+ "PREWHERE",+ "QUALIFY",+ "RANGE",+ "RECURSIVE",+ "REPLACE",+ "RETURN",+ "RIGHT",+ "ROLLUP",+ "ROW",+ "ROWS",+ "SAMPLE",+ "SELECT",+ "SEMI",+ "SETS",+ "SETTINGS",+ "STEP",+ "SUBSTRING",+ "THEN",+ "TIES",+ "TIME",+ "TIMESTAMP",+ "TOTALS",+ "TRAILING",+ "TRIM",+ "TRUNCATE",+ "TRY_CAST",+ "TO",+ "TOP",+ "UNBOUNDED",+ "UNION",+ "UNPIVOT",+ "USING",+ "VALUES",+ "WHEN",+ "WHERE",+ "WINDOW",+ "WITH",+ "ZONE",+ "NULL",+ "INF",+ "NAN",+ "SECOND",+ "MINUTE",+ "HOUR",+ "DAY",+ "WEEK",+ "MONTH",+ "QUARTER",+ "YEAR",+ "TRUE",+ "FALSE",+ "TEAM_ID",+ "FN",+ "FUN",+ "LET",+ "THROW",+ "TRY",+ "CATCH",+ "FINALLY",+ "WHILE",+ "MATERIALIZED",+ )+)+++# Plain unquoted identifier per the lexer:+# IDENTIFIER : (LETTER | UNDERSCORE | DOLLAR) (LETTER | UNDERSCORE | DEC_DIGIT | DOLLAR)*+# We restrict to lowercase ASCII + digits + underscore to keep the+# generated strings recognisable; that's still a valid HogQL identifier.+identifier_token: st.SearchStrategy[str] = st.from_regex(r"[a-z][a-z0-9_]{0,7}", fullmatch=True).filter(+ lambda s: s.lower() not in _RESERVED_KEYWORDS+)+++# Quoted identifier: double-quoted form. The lexer also accepts+# backquoted, but mixing in a smoke test only complicates things.+# The alphabet deliberately includes space — quoted identifiers can+# legally contain whitespace (``"abc def"`` is one identifier), and+# the jiggler-layer guards (``_whitespace_jiggle``, ``_comment_jiggle``)+# track ``"`` quoting so they don't break identifiers like that. The+# unquoted ``identifier_token`` above has no such allowance and must+# also dodge ``_RESERVED_KEYWORDS``; quoted identifiers ignore both.+quoted_identifier_token: st.SearchStrategy[str] = st.text(alphabet="abcdefghijklmnopq _", min_size=1, max_size=8).map(+ lambda s: f'"{s}"'+)+++# Single-quoted string literal with no escapes — keep simple for the+# initial smoke. The codegen will pull this in for STRING_LITERAL+# references everywhere they occur (column expressions, DATE 'literal',+# settings clauses, etc.).+string_literal_token: st.SearchStrategy[str] = st.text(alphabet="abcdefghijklmnop ", min_size=0, max_size=8).map(+ lambda s: "'" + s + "'"+)+++# Decimal integer literal — must be non-negative; sign is handled by the+# parser as unary minus.+decimal_literal_token: st.SearchStrategy[str] = st.integers(min_value=0, max_value=999_999).map(str)+++# Octal and hexadecimal literals per the lexer:+# OCTAL_LITERAL : '0' OCT_DIGIT+ -- OCT_DIGIT = [0-7]+# HEXADECIMAL_LITERAL : '0' [xX] HEX_DIGIT++# Emit real ``0...`` / ``0x...`` text rather than decimal-shaped+# fallbacks so the PBT actually exercises these productions. There is+# a known cpp visitor bug — ``visitColumnExprLiteral`` in+# ``common/hogql_parser/parser_json.cpp`` calls ``std::stoll(text)``+# with the default base of 10 and so silently parses ``0x1F`` as ``0``+# — which makes the comparison fail at this token on the buggy wheel.+# That divergence is the whole point: it's the bidirectional contract+# in ``_assert_backends_agree`` doing its job, the same outcome we+# wanted when ``_CPP_KNOWN_BUG_PATTERNS`` was dropped. The cpp fix+# landed upstream in ``common/hogql_parser`` 1.3.42; once+# ``pyproject.toml`` pins that wheel (or newer), these draws will+# stop tripping the divergence.+octal_literal_token: st.SearchStrategy[str] = st.from_regex(r"0[0-7]{1,6}", fullmatch=True)++hexadecimal_literal_token: st.SearchStrategy[str] = st.from_regex(r"0[xX][0-9a-fA-F]{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>``.+def _floating_literal(draw: Any) -> str:+ whole = draw(st.integers(min_value=0, max_value=9999))+ frac = draw(st.integers(min_value=0, max_value=9999))+ if draw(st.booleans()):+ exp_sign = draw(st.sampled_from(["", "+", "-"]))+ exp = draw(st.integers(min_value=0, max_value=99))+ return f"{whole}.{frac}e{exp_sign}{exp}"+ return f"{whole}.{frac}"+++floating_literal_token: st.SearchStrategy[str] = _floating_literal()diff --git a/posthog/hogql/test/test_parser_grammar_pbt.py b/posthog/hogql/test/test_parser_grammar_pbt.pynew file mode 100644index 000000000000..70e0ad8d53bb--- /dev/null+++ b/posthog/hogql/test/test_parser_grammar_pbt.py@@ -0,0 +1,367 @@+"""Grammar-driven property-based tests for the HogQL parser.++Strategies are auto-generated from ``HogQLParser.g4`` /+``HogQLLexer.common.g4`` by+``posthog/hogql/scripts/build_grammar_strategies.py`` and imported+from ``_generated_grammar_strategies``. Variable-content tokens are+hand-written once in ``_grammar_token_strategies``.++The stylistic-jiggle layer (case-flipping, whitespace, comment+insertion) wraps grammar-generated text to cover lexical axes that are+awkward to encode as grammar productions — exactly where the two+backends are most likely to disagree.++Contract — **bidirectional parity** between the two backends:++ 1. If both accept, ``clear_locations(a) == clear_locations(b)``.+ 2. If both reject, the example is discarded.+ 3. If one accepts and the other rejects → test fails: the two+ backends must agree on the accepted grammar surface.++The comparison is between the Python parser (the original reference+implementation, an ANTLR4-generated parser + a parse-tree visitor in+``HogQLParseTreeConverter``) and the C++ parser (a hand-ported visitor+over the same ANTLR4-generated parser, exposed to Python via the+``hogql_parser`` wheel). Both consume the same ``.g4`` grammar; AST+divergences here are visitor-implementation bugs in one of them.++Opt-in via ``RUN_PBT=1`` — the grind is slow and intended for offline+audit runs rather than every CI build.+"""++from __future__ import annotations++import os+from typing import Any++import pytest++from hypothesis import (+ HealthCheck,+ assume,+ given,+ settings,+ strategies as st,+)++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.visitor import clear_locations++pytestmark = pytest.mark.skipif(+ not os.environ.get("RUN_PBT"),+ reason="grammar PBT is slow and primarily for offline runs; set RUN_PBT=1 to opt in",+)+++# ---------------------------------------------------------------------------+# Stylistic-jiggle layer+# ---------------------------------------------------------------------------+#+# Applied as a post-pass on grammar-generated text. Covers lexical axes+# (case, whitespace, comment placement) that are awkward to express+# inside grammar productions.++_KEYWORDS_FOR_CASE_VARIATION = (+ "SELECT",+ "DISTINCT",+ "FROM",+ "WHERE",+ "GROUP",+ "BY",+ "HAVING",+ "ORDER",+ "LIMIT",+ "OFFSET",+ "ASC",+ "DESC",+ "AND",+ "OR",+ "NOT",+ "LIKE",+ "ILIKE",+ "AS",+ "WITH",+ "JOIN",+ "ON",+ "USING",+ "UNION",+ "INTERSECT",+ "EXCEPT",+ "ALL",+ "ANY",+ "CASE",+ "WHEN",+ "THEN",+ "ELSE",+ "END",+ "IN",+ "IS",+ "BETWEEN",+ "INTERVAL",+ "OVER",+ "PARTITION",+ "WINDOW",+ "FILTER",+)+++def _case_jiggle(draw: Any, query: str) -> str:+ """Randomise keyword case (preserves the rest of the string).+ Skipped inside single-quoted strings and double-quoted identifiers+ — quoted identifiers are case-sensitive, so flipping a fragment+ that happens to share text with a keyword (e.g. ``in`` inside+ ``"abc in def"``) would change the identifier's value."""++ def _flip(word: str) -> str:+ choice = draw(st.sampled_from(["upper", "lower", "title", "as-is"]))+ if choice == "upper":+ return word.upper()+ if choice == "lower":+ return word.lower()+ if choice == "title":+ return word.capitalize()+ return word++ out: list[str] = []+ in_squote = False+ in_dquote = False+ for token in query.split(" "):+ in_string = in_squote or in_dquote+ stripped = token.strip(",()")+ if not in_string and stripped.upper() in _KEYWORDS_FOR_CASE_VARIATION:+ out.append(token.replace(stripped, _flip(stripped)))+ else:+ out.append(token)+ if token.count("'") % 2 == 1:+ in_squote = not in_squote+ if token.count('"') % 2 == 1:+ in_dquote = not in_dquote+ return " ".join(out)+++def _whitespace_jiggle(draw: Any, query: str) -> str:+ """Replace single spaces with whitespace variants — spaces, tabs,+ newlines, multi-space runs. Skipped inside single-quoted string+ literals and double-quoted identifiers, both of which can legally+ contain a space character (``quoted_identifier_token`` draws from+ an alphabet that includes spaces, so identifiers like+ ``"abc def"`` exist; replacing the internal space would change+ the identifier's value rather than its surrounding whitespace)."""+ out: list[str] = []+ in_string = False+ quote: str | None = None+ for ch in query:+ if not in_string and ch in ("'", '"'):+ in_string = True+ quote = ch+ out.append(ch)+ continue+ if in_string and ch == quote:+ in_string = False+ quote = None+ out.append(ch)+ continue+ if ch == " " and not in_string:+ ws = draw(st.sampled_from([" ", " ", "\t", "\n", " \n ", "\t\n"]))+ out.append(ws)+ else:+ out.append(ch)+ return "".join(out)+++def _comment_jiggle(draw: Any, query: str) -> str:+ """Insert block / line comments before clause-keyword tokens.+ Skipped inside single-quoted strings and double-quoted identifiers+ — both alphabets include space, so a literal like ``"abc in def"``+ splits to ``["abc, in, def"]`` and the inner ``in`` would otherwise+ match the ``IN`` keyword and receive a comment, producing a+ lexically broken identifier."""+ out: list[str] = []+ in_squote = False+ in_dquote = False+ for tok in query.split(" "):+ in_string = in_squote or in_dquote+ if (+ not in_string+ and tok.upper() in _KEYWORDS_FOR_CASE_VARIATION+ and draw(st.integers(min_value=0, max_value=4)) == 0+ ):+ # ``--...\n`` is a separate lexical path from ``/* ... */``+ # — line comments must extend to end-of-line, so they+ # exercise ``\n``-terminated lookaheads that the block-comment+ # form doesn't reach. No space between ``--`` and the body+ # so the whole token is hostile to ``_whitespace_jiggle``+ # substitution (which would otherwise turn the space into a+ # ``\n`` and terminate the comment prematurely).+ comment = draw(+ st.sampled_from(+ [+ "/* note */",+ "/**/",+ "/* multi\nline */",+ "--note\n",+ ]+ )+ )+ out.append(comment)+ if tok.count("'") % 2 == 1:+ in_squote = not in_squote+ if tok.count('"') % 2 == 1:+ in_dquote = not in_dquote+ out.append(tok)+ return " ".join(out)+++def _apply_jiggle(query: str) -> st.SearchStrategy[str]:+ """Compose the three jiggles. Each is independently optional.++ Ordering matters: ``_case_jiggle`` and ``_comment_jiggle`` both+ locate clause keywords via ``query.split(" ")``, which only splits+ on literal space. ``_whitespace_jiggle`` rewrites single spaces to+ tabs / newlines / runs, after which a later ``split(" ")`` lands+ the whole query in one "token" and finds no keywords. So run the+ keyword-aware jiggles first and whitespace last."""++ @st.composite+ def _inner(draw: Any) -> str:+ result = query+ if draw(st.booleans()):+ result = draw(_case_jiggle(result))+ if draw(st.booleans()):+ result = draw(_comment_jiggle(result))+ if draw(st.booleans()):+ result = draw(_whitespace_jiggle(result))+ return result++ return _inner()+++# ---------------------------------------------------------------------------+# Differential parsing harness+# ---------------------------------------------------------------------------++# The two backends under comparison. Both implement the same `.g4`+# grammar — the Python one via an ANTLR4-generated parser + a+# HogQLParseTreeConverter visitor, the C++ one via a hand-ported+# visitor exposed through the `hogql_parser` wheel.+_BACKEND_A = "python"+_BACKEND_B = "cpp-json"+++def _try_parse(query: str, rule: str, backend: str) -> tuple[bool, ast.AST | None]:+ """Return ``(accepted, ast_or_none)``. Only ``BaseHogQLError`` counts+ as rejection — that covers both grammar-level errors+ (``SyntaxError``) and visitor-level "Unsupported rule" failures+ (``NotImplementedError``), which are the legitimate "this backend+ declined to handle the input" outcomes.++ Any other exception type (``RecursionError``, ``TypeError``,+ ``AssertionError``, ``MemoryError``, …) is a real bug in the+ backend under test and is allowed to propagate so pytest records+ 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]+ return True, clear_locations(node)+ except BaseHogQLError:+ return False, None+++def _assert_backends_agree(query: str, rule: str) -> None:+ """Bidirectional contract: both backends must accept the same+ grammar surface, and on accepted inputs the ASTs must match+ (post-`clear_locations`).++ There is intentionally no known-bug discard list — every+ divergence the grind surfaces is a real bug in one of the two+ visitors. Drop the failing example into a regression test, fix+ the bug, and let the grind continue.+ """+ a_ok, a_ast = _try_parse(query, rule, _BACKEND_A)+ b_ok, b_ast = _try_parse(query, rule, _BACKEND_B)++ if not a_ok and not b_ok:+ # Both rejected — uninteresting; the grammar generator can+ # over-produce strings that neither visitor accepts. ``assume(False)``+ # raises ``UnsatisfiedAssumption`` to skip the example.+ assume(False)++ if a_ok != b_ok:+ accepted, rejected = (_BACKEND_A, _BACKEND_B) if a_ok else (_BACKEND_B, _BACKEND_A)+ raise AssertionError(f"{accepted!r} accepted but {rejected!r} rejected ({rule!r}): {query!r}")++ if a_ast != b_ast:+ raise AssertionError(+ f"AST mismatch for {rule!r}: {query!r}\n {_BACKEND_A}: {a_ast!r}\n {_BACKEND_B}: {b_ast!r}"+ )+++# Shared Hypothesis settings. Strategies overgenerate (semantic-visitor+# rejection drops a sizable fraction); ``filter_too_much`` is silenced.+_PBT_SETTINGS = settings(+ max_examples=int(os.environ.get("GRAMMAR_PBT_EXAMPLES", "1000")),+ deadline=None,+ # ``too_slow`` and ``filter_too_much`` are characteristics of the+ # grind itself (deep ASTs, semantic-visitor rejections drop a+ # sizable fraction). ``data_too_large`` is deliberately *not*+ # suppressed — if it fires, the strategy is producing inputs+ # larger than Hypothesis's default buffer, which usually means an+ # unbounded path slipped past the ``_MAX_REPEAT``,+ # ``_MAX_LR_CHAIN``, or depth-decrement guards. That's a real+ # signal worth fixing rather than masking.+ suppress_health_check=[+ HealthCheck.too_slow,+ HealthCheck.filter_too_much,+ ],+)++# Wall-clock timeout per test (via pytest-timeout, which is already a+# project dependency). Hypothesis shrinking on a deep AST tree can run+# for many minutes; cap each test so a stuck shrink loop doesn't block+# the loop. Override with ``GRAMMAR_PBT_TIMEOUT=600`` for longer runs.+_PBT_TIMEOUT_SECONDS = int(os.environ.get("GRAMMAR_PBT_TIMEOUT", "300"))+++# ---------------------------------------------------------------------------+# Tests+# ---------------------------------------------------------------------------++[email protected](_PBT_TIMEOUT_SECONDS)+class TestExpressionGrammarPBT:+ """``parse_expr`` differential parity over the full ``columnExpr``+ grammar surface — auto-generated from .g4."""++ @given(query=expr_strategy())+ @_PBT_SETTINGS+ def test_expression_backends_agree(self, query: str) -> None:+ _assert_backends_agree(query, rule="expr")++ @given(query=expr_strategy().flatmap(_apply_jiggle))+ @_PBT_SETTINGS+ def test_expression_backends_agree_with_jiggle(self, query: str) -> None:+ _assert_backends_agree(query, rule="expr")++[email protected](_PBT_TIMEOUT_SECONDS)+class TestSelectGrammarPBT:+ """``parse_select`` differential parity over the full ``select``+ grammar surface — auto-generated from .g4."""++ @given(query=select_strategy())+ @_PBT_SETTINGS+ def test_select_backends_agree(self, query: str) -> None:+ _assert_backends_agree(query, rule="select")++ @given(query=select_strategy().flatmap(_apply_jiggle))+ @_PBT_SETTINGS+ def test_select_backends_agree_with_jiggle(self, query: str) -> None:+ _assert_backends_agree(query, rule="select")