Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(hogql): tooling improvements for parser-parity diagnostics (#58823)

Robbie0884eaf05c6d
diff --git a/.gitignore b/.gitignore
index 39a08a9db548..248400f6663c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,8 @@ __pycache__/
.hypothesis
.mypy_cache
.parcel-cache
+pbt-divergences.jsonl
+posthog/hogql/test/fixtures/real_queries/
.posthog/
.postgres-backups/
.python-version
diff --git a/posthog/hogql/scripts/_diagnostic_common.py b/posthog/hogql/scripts/_diagnostic_common.py
index 9a4122ae3020..f8afa50a657d 100644
--- a/posthog/hogql/scripts/_diagnostic_common.py
+++ b/posthog/hogql/scripts/_diagnostic_common.py
@@ -1,3 +1,4 @@
+# ruff: noqa: T201
"""Shared helpers for the HogQL parser-parity diagnostic scripts.
Imported by `pbt_diagnostic.py`, `pbt_corpus.py`, `parser_bench.py`,
@@ -25,14 +26,32 @@ Importing this module pulls `posthog.hogql.*` — callers must have run
from __future__ import annotations
+import os
import re
+import sys
+import json
+import signal
+import traceback
+import subprocess
import dataclasses
+from collections import Counter
+from collections.abc import Callable
+from pathlib import Path
from typing import Any
from posthog.hogql.errors import BaseHogQLError
-from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.parser import parse_expr, parse_program, parse_select
from posthog.hogql.visitor import clear_locations
+# Maps a diagnostic `--rule` value to its parser entry point. `program`
+# covers the Hog imperative-statement layer (let / if / while / for /
+# fn / try-catch / return / throw / blocks).
+_PARSER_FOR_RULE: dict[str, Callable[..., Any]] = {
+ "expr": parse_expr,
+ "select": parse_select,
+ "program": parse_program,
+}
+
# ---------------------------------------------------------------------------
# AST diff path
# ---------------------------------------------------------------------------
@@ -206,9 +225,9 @@ def _safe_parse(query: str, rule: str, backend: str) -> tuple[str, Any, str | No
`KeyboardInterrupt` / `SystemExit` are `BaseException`, not
`Exception` — a manual Ctrl-C still propagates past this handler."""
- parser_fn = parse_expr if rule == "expr" else parse_select
+ parser_fn = _PARSER_FOR_RULE[rule]
try:
- node = parser_fn(query, backend=backend) # type: ignore[arg-type]
+ node = parser_fn(query, backend=backend)
except BaseHogQLError as e:
return "reject", None, _normalize_error(str(e))
except Exception as e:
@@ -227,9 +246,9 @@ def _probe_backend(rule: str, backend: str) -> str | None:
error message. Bypasses `_try_parse` deliberately — `_try_parse`
swallows `BaseHogQLError` (legitimate rejections) AND would let an
invalid backend name raising `KeyError` through silently."""
- probe_fn = parse_expr if rule == "expr" else parse_select
+ probe_fn = _PARSER_FOR_RULE[rule]
try:
- probe_fn("1", backend=backend) # type: ignore[arg-type]
+ probe_fn("1", backend=backend)
except BaseHogQLError:
# Rejecting `"1"` would be surprising but isn't a backend
# failure — `_try_parse` would also classify this as a reject.
@@ -261,3 +280,401 @@ def _shape_for(
if o_ast == c_ast:
return None
return _ast_mismatch_shape((_node_type(o_ast), _node_type(c_ast)), _diff_path(o_ast, c_ast))
+
+
+# ===========================================================================
+# Corpus diagnostic machinery
+# ===========================================================================
+#
+# Shared by `log_corpus_diagnostic.py` (HogQL queries from ClickHouse
+# `system.query_log`) and `hog_corpus_diagnostic.py` (Hog programs from the
+# Aurora Postgres `posthog_hogfunction` table). Metabase access, the
+# paginated download, the oracle-vs-candidate parity grind, and the failure
+# report are identical across both — only the SQL and its redaction dialect
+# (ClickHouse `replaceRegexpAll` vs Postgres `regexp_replace`) differ, and
+# those stay in the per-corpus scripts.
+
+# Metabase's `/api/dataset` endpoint truncates every response to 2000 rows
+# regardless of the SQL `LIMIT`; anything larger is fetched by paging.
+MB_PAGE_SIZE = 2000
+
+
+def hogli_bin(repo_root: Path) -> str:
+ """Absolute path to `bin/hogli` — `$PATH` has it under flox for
+ interactive shells but agent / CI shells often don't."""
+ cand = repo_root / "bin" / "hogli"
+ if not cand.is_file():
+ raise RuntimeError(f"bin/hogli not found at {cand} — is the repo root correct?")
+ return str(cand)
+
+
+def repo_relative(path: Path, repo_root: Path) -> str:
+ """Repo-rooted string when `path` is inside `repo_root`, else verbatim —
+ so an out-of-worktree `--input` still prints cleanly."""
+ if path.is_absolute() and path.is_relative_to(repo_root):
+ return str(path.relative_to(repo_root))
+ return str(path)
+
+
+def discover_metabase_db(
+ region: str,
+ engine: str,
+ repo_root: Path,
+ *,
+ prefer_name_substring: str | None = None,
+) -> int:
+ """Return a Metabase database id for the given `engine` (`clickhouse`
+ / `postgres`), preferring one whose name contains `prefer_name_substring`
+ (case-insensitive) when given, else the lowest id for determinism.
+ Raises if `hogli metabase:databases` fails — usually a stale cookie
+ (`hogli metabase:login` first)."""
+ out = subprocess.check_output(
+ [hogli_bin(repo_root), "metabase:databases", "--region", region, "--format", "json"],
+ cwd=repo_root,
+ text=True,
+ timeout=60, # don't hang forever on a stalled Metabase / auth wait
+ )
+ dbs = json.loads(out)
+ # case-insensitive: Metabase has drifted casing on metadata fields.
+ matching = [db for db in dbs if db.get("engine", "").lower() == engine.lower()]
+ if not matching:
+ raise RuntimeError(f"No {engine} databases listed for region={region!r}")
+ if prefer_name_substring:
+ sub = prefer_name_substring.lower()
+ preferred = sorted(
+ (db for db in matching if sub in db.get("name", "").lower()),
+ key=lambda d: d["id"],
+ )
+ if preferred:
+ chosen = preferred[0]
+ print(f" using {engine} db id={chosen['id']} name={chosen['name']!r}")
+ return int(chosen["id"])
+ print(f" no {engine} DB name matched {prefer_name_substring!r}; falling back to lowest id")
+ chosen = sorted(matching, key=lambda d: d["id"])[0]
+ print(f" using {engine} db id={chosen['id']} name={chosen['name']!r}")
+ return int(chosen["id"])
+
+
+def _fetch_metabase_page(region: str, database_id: int, sql: str, tmp_path: Path, repo_root: Path) -> dict:
+ """Run one SQL query via `hogli metabase:query`, returning the parsed
+ Metabase `/api/dataset` JSON. hogli writes to `tmp_path`."""
+ subprocess.run(
+ [
+ hogli_bin(repo_root),
+ "metabase:query",
+ "--region",
+ region,
+ "--database-id",
+ str(database_id),
+ "--format",
+ "json",
+ "--save",
+ str(tmp_path),
+ # SQL goes over stdin; `--timeout` covers the slow scan.
+ "--timeout",
+ "300",
+ ],
+ input=sql,
+ text=True,
+ check=True,
+ cwd=repo_root,
+ timeout=360, # process-level backstop above hogli's own `--timeout 300`
+ )
+ with open(tmp_path) as f:
+ return json.load(f)
+
+
+def download_corpus(
+ region: str,
+ database_id: int,
+ dump_path: Path,
+ sql_limit: int,
+ build_sql: Callable[[int, int], str],
+ repo_root: Path,
+) -> None:
+ """Fetch up to `sql_limit` corpus rows and write them to `dump_path`
+ (Metabase `/api/dataset` JSON shape: `{"data": {"cols", "rows"}}`).
+
+ `build_sql(limit, offset)` produces the corpus SQL for one page.
+ Metabase caps responses at `MB_PAGE_SIZE`, so larger pulls are paged
+ and concatenated. Written via a `.tmp` sibling + `os.replace` so an
+ interrupted scan can't leave a half-written dump."""
+ dump_path.parent.mkdir(parents=True, exist_ok=True)
+ cols: list | None = None
+ all_rows: list = []
+ offset = 0
+ page_tmp = dump_path.with_suffix(dump_path.suffix + ".page.tmp")
+ try:
+ while len(all_rows) < sql_limit:
+ page_limit = min(MB_PAGE_SIZE, sql_limit - len(all_rows))
+ print(f" downloading rows {offset:,}–{offset + page_limit:,} via `hogli metabase:query` …")
+ body = _fetch_metabase_page(region, database_id, build_sql(page_limit, offset), page_tmp, repo_root)
+ data = body.get("data") if isinstance(body, dict) else None
+ if not data or "rows" not in data or "cols" not in data:
+ status = body.get("status") if isinstance(body, dict) else "<unknown>"
+ error = body.get("error") if isinstance(body, dict) else None
+ raise RuntimeError(
+ f"Metabase page at offset {offset} isn't a success payload (status={status!r}, error={error!r})"
+ )
+ if cols is None:
+ cols = data["cols"]
+ rows = data["rows"]
+ all_rows.extend(rows)
+ if len(rows) < page_limit:
+ break # short page → corpus exhausted
+ offset += page_limit
+ finally:
+ page_tmp.unlink(missing_ok=True)
+ merged = {"data": {"cols": cols or [], "rows": all_rows}, "status": "completed", "row_count": len(all_rows)}
+ tmp_path = dump_path.with_suffix(dump_path.suffix + ".tmp")
+ try:
+ with open(tmp_path, "w") as f:
+ json.dump(merged, f)
+ os.replace(tmp_path, dump_path)
+ finally:
+ tmp_path.unlink(missing_ok=True)
+ print(
+ f" saved {len(all_rows):,} rows ({dump_path.stat().st_size:,} bytes) to {repo_relative(dump_path, repo_root)}"
+ )
+
+
+def load_corpus_rows(path: Path, *, text_col: str, count_col: str | None = None) -> list[tuple[str, int]]:
+ """Read a Metabase JSON dump into `(text, n_occurrences)` pairs,
+ skipping rows whose `text_col` is empty/blank. Columns are resolved
+ by name so the reader survives column-order changes in the SQL."""
+ if not path.exists():
+ raise FileNotFoundError(
+ f"corpus dump not found at {path}\n"
+ " hint: drop --skip-download to fetch it from Metabase, or pass --input PATH"
+ )
+ with open(path) as f:
+ payload = json.load(f)
+ data = payload.get("data") if isinstance(payload, dict) else None
+ if not data or "rows" not in data or "cols" not in data:
+ status = payload.get("status") if isinstance(payload, dict) else "<unknown>"
+ error = payload.get("error") if isinstance(payload, dict) else None
+ raise RuntimeError(
+ f"dump at {path} isn't a Metabase /api/dataset success payload (status={status!r}, error={error!r})"
+ )
+ col_idx = {c.get("name"): i for i, c in enumerate(data["cols"])}
+ if text_col not in col_idx:
+ raise RuntimeError(f"dump columns {list(col_idx)} don't include {text_col!r} — re-run without --skip-download")
+ text_i = col_idx[text_col]
+ count_i = col_idx.get(count_col) if count_col else None
+ out: list[tuple[str, int]] = []
+ for row in data["rows"]:
+ text = row[text_i]
+ if not isinstance(text, str) or not text.strip():
+ continue
+ n = 1
+ if count_i is not None:
+ try:
+ n = int(row[count_i])
+ except (TypeError, ValueError):
+ n = 1
+ out.append((text, n))
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Error bucketing — group same-cause rejects / crashes together
+# ---------------------------------------------------------------------------
+
+_AT_RE = re.compile(r"at\s+(line\s+\d+|offset\s+\d+|position\s+\d+|\d+:\d+)", re.IGNORECASE)
+
+
+def bucket_error(msg: str) -> str:
+ """Normalise a reject message so same-cause rejects bucket together —
+ drops `got <X>` operands and `at <pos>` suffixes, clips to 160."""
+ return _AT_RE.sub("at <pos>", _GOT_RE.sub("got <X>", msg)).strip()[:160]
+
+
+def crash_signature(tb: str) -> str:
+ """Bucket a crash by its traceback's last line (`ExcType: message`)."""
+ lines = [ln for ln in tb.splitlines() if ln.strip()]
+ return bucket_error(lines[-1]) if lines else "<empty traceback>"
+
+
+def corpus_try_parse(query: str, rule: str, backend: str) -> tuple[str, Any, str | None]:
+ """Parse `query` for the corpus grind. Returns `(status, ast, detail)`:
+ `ok` (AST `clear_locations`-normalised), `reject` (detail = the raw
+ `BaseHogQLError` message), or `crash` (detail = full traceback).
+ Ctrl-C still propagates (`BaseException`, not `Exception`)."""
+ parser_fn = _PARSER_FOR_RULE[rule]
+ try:
+ node = parser_fn(query, backend=backend)
+ return "ok", clear_locations(node), None
+ except BaseHogQLError as e:
+ return "reject", None, str(e)
+ except Exception:
+ return "crash", None, traceback.format_exc()
+
+
+# ---------------------------------------------------------------------------
+# Failure file
+# ---------------------------------------------------------------------------
+
+
[email protected](frozen=True)
+class Failure:
+ """One failing-corpus-entry record for the failure file."""
+
+ # "candidate_reject" | "candidate_crash" | "ast_mismatch" | "oracle_crash"
+ kind: str
+ query: str
+ detail: str # rejection message, crash traceback, or formatted diff path
+ n_occurrences: int
+
+
+def write_failures(path: Path, failures: list[Failure], repo_root: Path, *, title: str) -> None:
+ """One block per failing entry, separated by a `-- =====` ruler,
+ carrying the rejection / traceback / AST diff so a follow-up triage
+ pass can bucket by root cause. Written via a `.tmp` sibling +
+ `os.replace` so a crash mid-write can't leave a truncated file."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ by_kind = Counter(fa.kind for fa in failures)
+ breakdown = ", ".join(f"{n} {kind}" for kind, n in sorted(by_kind.items())) or "none"
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
+ with open(tmp_path, "w") as f:
+ f.write(f"-- {title} — {len(failures)} entries\n")
+ f.write(f"-- ({breakdown})\n")
+ f.write("-- Each block: occurrences count, failure kind + detail, then the entry.\n\n")
+ for i, fa in enumerate(failures):
+ f.write("-- " + "=" * 76 + "\n")
+ f.write(f"-- [{i + 1}/{len(failures)}] seen {fa.n_occurrences}x in last 7d\n")
+ f.write(f"-- kind: {fa.kind}\n")
+ for line in fa.detail.splitlines() or [""]:
+ f.write(f"-- {line}\n" if line else "--\n")
+ f.write("\n")
+ f.write(fa.query.rstrip("\n") + "\n\n")
+ os.replace(tmp_path, path)
+
+
+# ---------------------------------------------------------------------------
+# Parity grind
+# ---------------------------------------------------------------------------
+
+
+class ParityResult:
+ """Outcome of `run_corpus_parity`: tallies, per-failure records, and
+ the bucket counters for the summary."""
+
+ counts: Counter
+ failures: list[Failure]
+ oracle_reject_buckets: Counter
+ reject_buckets: Counter
+ crash_buckets: Counter
+ mismatch_buckets: Counter
+ interrupted: bool
+
+
+def run_corpus_parity(
+ rows: list[tuple[str, int]],
+ *,
+ rule: str,
+ oracle: str,
+ candidate: str,
+ verbose: bool = False,
+ noun: str = "query",
+) -> ParityResult:
+ """Parse every `(text, n_occurrences)` row with the oracle then the
+ candidate and classify the outcome: pass / candidate_reject /
+ candidate_crash / ast_mismatch, plus oracle_reject (skipped) and
+ oracle_crash. A SIGINT flushes partial results — the loop checks an
+ interrupt flag at each iteration boundary so an interrupted run still
+ returns everything accumulated so far."""
+ counts: Counter[str] = Counter()
+ failures: list[Failure] = []
+ oracle_reject_buckets: Counter[str] = Counter()
+ reject_buckets: Counter[str] = Counter()
+ crash_buckets: Counter[str] = Counter()
+ mismatch_buckets: Counter[tuple[str, str]] = Counter()
+ interrupted = False
+
+ def _on_sigint(_signum: int, _frame: object) -> None:
+ nonlocal interrupted
+ interrupted = True
+
+ prev_sigint = signal.signal(signal.SIGINT, _on_sigint)
+ try:
+ for i, (query, n_occ) in enumerate(rows):
+ if interrupted:
+ print(f"\nInterrupted at {i}/{len(rows)} — writing partial results…")
+ break
+ if (i + 1) % 50 == 0:
+ sys.stderr.write(
+ f"\r [{noun}] {i + 1}/{len(rows)} processed (pass={counts['pass']} "
+ f"reject={counts['candidate_reject']} mismatch={counts['ast_mismatch']} "
+ f"crash={counts['candidate_crash'] + counts['oracle_crash']} "
+ f"skip={counts['oracle_reject']})"
+ )
+ sys.stderr.flush()
+ counts["total"] += 1
+ o_status, o_ast, o_detail = corpus_try_parse(query, rule, oracle)
+ if o_status == "reject":
+ counts["oracle_reject"] += 1
+ oracle_reject_buckets[bucket_error(o_detail or "")] += 1
+ continue
+ if o_status == "crash":
+ counts["oracle_crash"] += 1
+ crash_buckets[crash_signature(o_detail or "")] += 1
+ failures.append(Failure("oracle_crash", query, o_detail or "<no traceback>", n_occ))
+ continue
+ c_status, c_ast, c_detail = corpus_try_parse(query, rule, candidate)
+ if c_status == "reject":
+ counts["candidate_reject"] += 1
+ reject_buckets[bucket_error(c_detail or "")] += 1
+ failures.append(Failure("candidate_reject", query, c_detail or "<no message>", n_occ))
+ continue
+ if c_status == "crash":
+ counts["candidate_crash"] += 1
+ crash_buckets[crash_signature(c_detail or "")] += 1
+ failures.append(Failure("candidate_crash", query, c_detail or "<no traceback>", n_occ))
+ continue
+ if o_ast == c_ast:
+ counts["pass"] += 1
+ continue
+ counts["ast_mismatch"] += 1
+ bucket = (_node_type(o_ast), _node_type(c_ast))
+ mismatch_buckets[bucket] += 1
+ failures.append(Failure("ast_mismatch", query, _format_diff_path(_diff_path(o_ast, c_ast)), n_occ))
+ if verbose:
+ print(f" MISMATCH (seen {n_occ}x): {bucket[0]} vs {bucket[1]}")
+ finally:
+ signal.signal(signal.SIGINT, prev_sigint)
+ sys.stderr.write("\r" + " " * 110 + "\r")
+ return ParityResult(
+ counts=counts,
+ failures=failures,
+ oracle_reject_buckets=oracle_reject_buckets,
+ reject_buckets=reject_buckets,
+ crash_buckets=crash_buckets,
+ mismatch_buckets=mismatch_buckets,
+ interrupted=interrupted,
+ )
+
+
+def print_corpus_summary(result: ParityResult, *, oracle: str, candidate: str) -> None:
+ """Print the `=== Summary ===` tally and the per-bucket breakdowns."""
+ counts = result.counts
+ print()
+ print("=== Summary ===")
+ for k in ("total", "pass", "candidate_reject", "candidate_crash", "ast_mismatch", "oracle_crash", "oracle_reject"):
+ print(f" {k:25s} {counts[k]}")
+
+ def _dump(label: str, buckets: Counter, limit: int) -> None:
+ if not buckets:
+ return
+ print()
+ print(f"=== {label} ({sum(buckets.values())} total) ===")
+ for sig, n in buckets.most_common(limit):
+ shown = sig if isinstance(sig, str) else f"{sig[0]:25s} vs {sig[1]}"
+ print(f" {n:5d} {shown}")
+ if len(buckets) > limit:
+ print(f" … and {len(buckets) - limit} more buckets")
+
+ _dump(f"Oracle ({oracle}) reject buckets", result.oracle_reject_buckets, 20)
+ _dump(f"Candidate ({candidate}) reject buckets", result.reject_buckets, 30)
+ _dump("Crash buckets (non-HogQL exceptions)", result.crash_buckets, 30)
+ _dump("AST mismatch buckets", result.mismatch_buckets, 30)
diff --git a/posthog/hogql/scripts/build_grammar_strategies.py b/posthog/hogql/scripts/build_grammar_strategies.py
index e2a32974c759..d87c90c048a2 100755
--- a/posthog/hogql/scripts/build_grammar_strategies.py
+++ b/posthog/hogql/scripts/build_grammar_strategies.py
@@ -599,30 +599,19 @@ EXCLUDED_RULES: frozenset[str] = frozenset(
"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` — Hog dict key/value pairs. Not a
+ # program statement; left excluded so enabling Hog programs
+ # doesn't also widen the expression-strategy surface.
"kvPair",
"kvPairList",
}
)
+# NB: the Hog program rules (`program`, `declaration`, `statement`,
+# `returnStmt` / `throwStmt` / `tryCatchStmt` / `catchBlock` /
+# `ifStmt` / `whileStmt` / `forStmt` / `forInStmt` / `funcStmt` /
+# `varDecl` / `varAssignment` / `exprStmt` / `emptyStmt` / `block`)
+# are intentionally NOT excluded — the grammar PBT drives Hog-program
+# parity via the generated `program_strategy`.
# Alternatives the cpp-json backend (ANTLR parser + Python visitor)
# unconditionally rejects. The PBT contract is one-sided — we only
@@ -941,9 +930,9 @@ from posthog.hogql.test._grammar_token_strategies import (
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)
+_DEFAULT_DEPTH = 5
+_MAX_REPEAT = 4 # cap for `*` / `+` quantifiers (per occurrence)
+_MAX_LR_CHAIN = 4 # 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
diff --git a/posthog/hogql/scripts/hog_corpus_diagnostic.py b/posthog/hogql/scripts/hog_corpus_diagnostic.py
new file mode 100644
index 000000000000..fdb8d23192f5
--- /dev/null
+++ b/posthog/hogql/scripts/hog_corpus_diagnostic.py
@@ -0,0 +1,286 @@
+# ruff: noqa: T201, E402
+"""Hog-program corpus parser-parity diagnostic.
+
+Pulls real Hog program source from the `posthog_hogfunction` table on
+Aurora Postgres (the `hog` column — destinations, transformations and
+other CDP functions), runs both the oracle and candidate parsers over
+each, and reports where they disagree.
+
+Sibling of `log_corpus_diagnostic.py`: that runs over real HogQL
+*queries* from ClickHouse `system.query_log`; this runs over real Hog
+*programs* (the `program` grammar rule — let / if / while / for / fn /
+try-catch / return / blocks) from Postgres. Both are real-usage
+complements to `pbt_diagnostic.py`'s grammar-generated surface, and the
+shared machinery lives in `_diagnostic_common.py`.
+
+## Pipeline
+
+1. **Auto-discover the Aurora Postgres database id** via
+ `hogli metabase:databases` (engine `postgres`, name containing
+ `aurora`).
+2. **Download a redacted dump** via `hogli metabase:query` to the
+ gitignored `posthog/hogql/scripts/.local/hog_corpus.json`. The
+ embedded SQL applies the same `regexp_replace` redaction chain the
+ HogQL corpus uses (emails, UUIDs, IPv4/6, tokens, hex catch-all),
+ server-side, so raw source never reaches the dump.
+3. **Skip the download** with `--skip-download` to reuse an existing
+ dump when iterating on a candidate parser locally.
+4. **For each unique program**: parse with `--oracle` (default
+ `cpp-json`); oracle reject → skipped. Otherwise parse with
+ `--candidate` — reject, crash, AST mismatch, or pass. ASTs are
+ compared after `clear_locations()`.
+
+Only Hog functions belonging to organisations that have opted into AI
+data processing (`posthog_organization.is_ai_data_processing_approved`)
+are sampled — the Postgres equivalent of the HogQL corpus's
+`log_comment.ai_data_processing_approved` gate.
+
+## Usage
+
+ # Default — auto-discover, download, run cpp-vs-python parity:
+ PYTHONPATH=. python posthog/hogql/scripts/hog_corpus_diagnostic.py
+
+ # Iterate on a candidate parser without re-pulling the corpus:
+ PYTHONPATH=. python posthog/hogql/scripts/hog_corpus_diagnostic.py \\
+ --skip-download \\
+ --candidate rust-allstar-json \\
+ --write-failures /tmp/hog-fails.hog
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import argparse
+import traceback
+import subprocess
+from pathlib import Path
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+from posthog.hogql.scripts._diagnostic_common import (
+ _probe_backend,
+ discover_metabase_db,
+ download_corpus,
+ load_corpus_rows,
+ print_corpus_summary,
+ repo_relative,
+ run_corpus_parity,
+ write_failures,
+)
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+DEFAULT_DUMP = REPO_ROOT / "posthog" / "hogql" / "scripts" / ".local" / "hog_corpus.json"
+
+# Hog functions are heavily template-instantiated, so unique `hog`
+# sources number only a few thousand — well under any page ceiling.
+_DEFAULT_SQL_LIMIT = 10000
+
+
+# ---------------------------------------------------------------------------
+# Embedded SQL — keep the source of the corpus reproducible from the script
+# ---------------------------------------------------------------------------
+
+# Redaction passes over the Hog source, applied in list order (each wraps
+# the previous). Mirrors `log_corpus_diagnostic._REDACTION_PASSES` but in
+# Postgres regex dialect — `\y` is the word boundary (Postgres has no
+# `\b`); `\d`, char classes and the `\1` replacement backreference carry
+# over unchanged.
+_REDACTION_PASSES: list[tuple[str, str]] = [
+ (r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", "<email>"),
+ (
+ r"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}",
+ "<uuid>",
+ ),
+ (r"\yph[a-z]_[A-Za-z0-9]{10,}", "<ph_token>"),
+ (r"\yeyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+", "<jwt>"),
+ (r"\y[sprk]k_(live|test)_[A-Za-z0-9]{10,}", "<stripe_key>"),
+ (r"\y(AKIA|ASIA)[A-Z0-9]{16}\y", "<aws_key>"),
+ (r"\ygh[posru]_[A-Za-z0-9]{30,}", "<gh_token>"),
+ (r"\ygithub_pat_[A-Za-z0-9_]{20,}", "<gh_token>"),
+ (r"\yxox[bpoars]-[A-Za-z0-9-]{10,}", "<slack_token>"),
+ (r"([0-9a-fA-F]{1,4}:){3,7}[0-9a-fA-F]{1,4}", "<ipv6>"),
+ (r"(^|[^.0-9])(\d{1,3}\.){3}\d{1,3}\y", r"\1<ipv4>"),
+ (r"\y[a-fA-F0-9]{32,}\y", "<hex>"),
+]
+
+
+def _sql_str_literal(s: str) -> str:
+ """Escape a string for a Postgres single-quoted literal."""
+ return s.replace("\\", "\\\\").replace("'", "''")
+
+
+def _build_redaction_expr() -> str:
+ """Nest `_REDACTION_PASSES` into one `regexp_replace(…, 'g')` chain
+ over the `hog` column."""
+ expr = "hf.hog"
+ for pattern, replacement in _REDACTION_PASSES:
+ expr = f"regexp_replace({expr}, '{_sql_str_literal(pattern)}', '{_sql_str_literal(replacement)}', 'g')"
+ return expr
+
+
+def _build_corpus_sql(limit: int, offset: int = 0) -> str:
+ """Build the corpus query. `limit`/`offset` page the scan; the
+ `ORDER BY` carries `hog` as a tiebreaker so pagination is a stable
+ total order. Only non-deleted functions from AI-data-processing
+ consenting organisations are sampled."""
+ return f"""
+SELECT
+ {_build_redaction_expr()} AS hog,
+ count(*) AS n_occurrences
+FROM posthog_hogfunction hf
+JOIN posthog_team t ON t.id = hf.team_id
+JOIN posthog_organization o ON o.id = t.organization_id
+WHERE hf.deleted = false
+ AND o.is_ai_data_processing_approved
+ AND length(hf.hog) > 0
+GROUP BY hog
+ORDER BY n_occurrences DESC, hog
+LIMIT {int(limit)} OFFSET {int(offset)}
+"""
+
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("--region", choices=("us", "eu", "dev"), default="us", help="Metabase region (default: us)")
+ p.add_argument(
+ "--database-id",
+ type=int,
+ default=None,
+ help="Aurora Postgres Metabase DB id. Default: auto-discover (engine postgres, name ~ 'aurora').",
+ )
+ p.add_argument(
+ "--input",
+ type=Path,
+ default=DEFAULT_DUMP,
+ help=f"Path to the redacted JSON dump (default: {repo_relative(DEFAULT_DUMP, REPO_ROOT)})",
+ )
+ p.add_argument(
+ "--skip-download",
+ action="store_true",
+ help="Reuse the existing JSON dump at --input rather than re-running the Metabase query",
+ )
+ p.add_argument(
+ "--oracle",
+ default=os.environ.get("ORACLE_BACKEND", "cpp-json"),
+ help="Source-of-truth backend (default: cpp-json)",
+ )
+ p.add_argument(
+ "--candidate",
+ default=os.environ.get("CANDIDATE_BACKEND", "python"),
+ help="Backend under test (default: python; override for forks)",
+ )
+ p.add_argument(
+ "--write-failures",
+ metavar="PATH",
+ default=None,
+ help="Output file for failing programs (default: <dump>.failures.hog alongside the dump)",
+ )
+ p.add_argument(
+ "--limit",
+ type=int,
+ default=None,
+ help="Cap to first N unique programs (also caps the SQL scan for a fast Metabase round-trip).",
+ )
+ p.add_argument("--verbose", action="store_true", help="Print one line per AST mismatch")
+ args = p.parse_args()
+ if args.limit is not None and args.limit <= 0:
+ p.error("--limit must be a positive integer")
+
+ # Fail fast on a bad backend name (the `program` rule, since that's
+ # what Hog source parses as).
+ for label, backend in (("oracle", args.oracle), ("candidate", args.candidate)):
+ err = _probe_backend("program", backend)
+ if err is not None:
+ print(f"ERROR: {label} backend {backend!r} unavailable: {err}")
+ return 1
+ if args.oracle == args.candidate:
+ print(
+ f"WARNING: --oracle and --candidate are both {args.oracle!r} — "
+ f"this is not a parity check; every program will trivially 'pass'."
+ )
+
+ print(f"=== Hog-program corpus diagnostic: oracle={args.oracle} candidate={args.candidate} ===")
+ print()
+
+ # 1. Acquire the dump.
+ if args.skip_download:
+ if not args.input.exists():
+ print(f"ERROR: --skip-download but no dump at {args.input}")
+ return 1
+ print(f"Reusing existing dump: {args.input}")
+ else:
+ print(f"Region: {args.region}")
+ if args.database_id is None:
+ print("Auto-discovering Aurora Postgres DB id …")
+ try:
+ args.database_id = discover_metabase_db(
+ args.region, "postgres", REPO_ROOT, prefer_name_substring="aurora"
+ )
+ except subprocess.CalledProcessError as e:
+ print(f"ERROR: `hogli metabase:databases` failed (exit {e.returncode})")
+ print(f" hint: run `./bin/hogli metabase:login --region {args.region}` first")
+ return 1
+ except subprocess.TimeoutExpired:
+ print("ERROR: `hogli metabase:databases` timed out after 60s")
+ return 1
+ else:
+ print(f"Using --database-id {args.database_id}")
+ sql_limit = args.limit if args.limit and args.limit < _DEFAULT_SQL_LIMIT else _DEFAULT_SQL_LIMIT
+ try:
+ download_corpus(args.region, args.database_id, args.input, sql_limit, _build_corpus_sql, REPO_ROOT)
+ except subprocess.CalledProcessError as e:
+ print(f"ERROR: `hogli metabase:query` failed (exit {e.returncode})")
+ return 1
+ except subprocess.TimeoutExpired:
+ print("ERROR: `hogli metabase:query` timed out — narrow with --limit, or retry")
+ return 1
+
+ # 2. Load.
+ rows = load_corpus_rows(args.input, text_col="hog", count_col="n_occurrences")
+ print(f"Loaded {len(rows)} unique programs from {repo_relative(args.input, REPO_ROOT)}")
+ if args.limit is not None and args.limit < len(rows):
+ rows = rows[: args.limit]
+ print(f" (capped to first {args.limit} via --limit)")
+
+ # 3. Parity grind.
+ print()
+ print("Running parity check (oracle then candidate per program)…")
+ print()
+ result = run_corpus_parity(
+ rows,
+ rule="program",
+ oracle=args.oracle,
+ candidate=args.candidate,
+ verbose=args.verbose,
+ noun="program",
+ )
+ print_corpus_summary(result, oracle=args.oracle, candidate=args.candidate)
+
+ # 4. Failure dump.
+ if result.failures:
+ out_path = Path(args.write_failures) if args.write_failures else args.input.with_suffix(".failures.hog")
+ write_failures(out_path, result.failures, REPO_ROOT, title="hog_corpus_failures")
+ print()
+ print(f"Wrote {len(result.failures)} failing programs to {repo_relative(out_path, REPO_ROOT)}")
+
+ return 130 if result.interrupted else 0
+
+
+if __name__ == "__main__":
+ try:
+ raise SystemExit(main())
+ except KeyboardInterrupt:
+ print("\nInterrupted.", file=sys.stderr)
+ sys.exit(130)
+ except Exception:
+ traceback.print_exc()
+ sys.exit(1)
diff --git a/posthog/hogql/scripts/log_corpus_diagnostic.py b/posthog/hogql/scripts/log_corpus_diagnostic.py
index d2dd183cf1ac..ecb42c86d562 100644
--- a/posthog/hogql/scripts/log_corpus_diagnostic.py
+++ b/posthog/hogql/scripts/log_corpus_diagnostic.py
@@ -1,36 +1,35 @@
# ruff: noqa: T201, E402
"""HogQL log-corpus parser-parity diagnostic.
-Pulls the last 7 days of HogQL queries that team_id=2 (PostHog's own
-internal team) ran against production ClickHouse, runs both the oracle
-and candidate parsers over each, and reports where they disagree.
+Pulls the last 7 days of HogQL queries run against production
+ClickHouse by any team that has opted into AI data processing
+(`log_comment.ai_data_processing_approved`), runs both the oracle and
+candidate parsers over each, and reports where they disagree.
-Complement to `pbt_diagnostic.py`: that grinds randomly-generated
-grammar surface (what HogQL *permits*); this runs over real HogQL
-source text as the product emits it (what production *uses*) — insight
-queries, hand-rolled HogQL panels, warehouse view materialisation, and
-whatever Cloud users trigger via the API. Both are worth running.
+Sibling of `hog_corpus_diagnostic.py` (which does the same for Hog
+*programs* from Postgres). Both are real-usage complements to
+`pbt_diagnostic.py`'s grammar-generated surface; the Metabase access,
+paginated download, parity grind and failure report are shared via
+`_diagnostic_common.py`.
## Pipeline
1. **Auto-discover the ClickHouse database id** via
- `hogli metabase:databases --region us --format json`, preferring a
- DB whose name contains `OFFLINE` so the `system.query_log` scan goes
- to the background-workload cluster, not the live one.
-2. **Download a redacted dump** via `hogli metabase:query --format json`
- to the gitignored `posthog/hogql/scripts/.local/hogql_log_corpus.json`.
- JSON not TSV — Metabase's TSV writer doesn't escape embedded
- newlines and HogQL queries are routinely multi-line. The embedded
- SQL applies a chain of `replaceRegexpAll` redaction passes (emails,
- UUIDs, IPv4/6, PostHog API tokens, plus defence-in-depth passes for
- JWT / Stripe / AWS / GitHub / Slack credentials, and a broad hex
- catch-all).
+ `hogli metabase:databases`, preferring an `OFFLINE` shard so the
+ `system.query_log` scan goes to the background-workload cluster.
+2. **Download a redacted dump** via `hogli metabase:query` to the
+ gitignored `posthog/hogql/scripts/.local/hogql_log_corpus.json`.
+ The embedded SQL applies a chain of `replaceRegexpAll` redaction
+ passes (emails, UUIDs, IPv4/6, PostHog API tokens, plus
+ defence-in-depth passes for JWT / Stripe / AWS / GitHub / Slack
+ credentials, and a broad hex catch-all). Metabase caps responses at
+ 2000 rows, so larger pulls are paged.
3. **Skip the download** with `--skip-download` to reuse an existing
dump when iterating on a candidate parser locally.
4. **For each unique query**: parse with `--oracle` (default
`cpp-json`); oracle reject → skipped. Otherwise parse with
- `--candidate` — reject, crash (non-HogQL exception), AST mismatch,
- or pass. ASTs are compared after `clear_locations()`.
+ `--candidate` — reject, crash, AST mismatch, or pass. ASTs are
+ compared after `clear_locations()`.
## Usage
@@ -42,24 +41,15 @@ whatever Cloud users trigger via the API. Both are worth running.
--skip-download \\
--candidate rust-backtrack-json \\
--write-failures /tmp/rust-backtrack-log-fails.sql
-
- # Override the dump path entirely:
- PYTHONPATH=. python posthog/hogql/scripts/log_corpus_diagnostic.py \\
- --input /some/other/dump.json
"""
from __future__ import annotations
import os
-import re
import sys
-import json
-import signal
import argparse
import traceback
import subprocess
-import dataclasses
-from collections import Counter
from pathlib import Path
import django
@@ -67,11 +57,16 @@ import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
django.setup()
-from posthog.hogql import ast
-from posthog.hogql.errors import BaseHogQLError
-from posthog.hogql.parser import parse_select
-from posthog.hogql.scripts._diagnostic_common import _GOT_RE, _diff_path, _format_diff_path, _node_type, _probe_backend
-from posthog.hogql.visitor import clear_locations
+from posthog.hogql.scripts._diagnostic_common import (
+ _probe_backend,
+ discover_metabase_db,
+ download_corpus,
+ load_corpus_rows,
+ print_corpus_summary,
+ repo_relative,
+ run_corpus_parity,
+ write_failures,
+)
REPO_ROOT = Path(__file__).resolve().parents[3]
DEFAULT_DUMP = REPO_ROOT / "posthog" / "hogql" / "scripts" / ".local" / "hogql_log_corpus.json"
@@ -140,9 +135,10 @@ def _build_redaction_expr() -> str:
return expr
-def _build_redaction_sql(limit: int) -> str:
- """Build the corpus query. `limit` caps the scan at the SQL level so
- quick `--limit 50` runs don't fetch rows we'll never look at."""
+def _build_corpus_sql(limit: int, offset: int = 0) -> str:
+ """Build the corpus query. `limit`/`offset` page the scan; the
+ `ORDER BY` carries `hogql` as a tiebreaker so pagination is a stable
+ total order (occurrence count alone has ties)."""
return f"""
SELECT
{_build_redaction_expr()} AS hogql,
@@ -151,243 +147,19 @@ FROM clusterAllReplicas(posthog, system, query_log)
WHERE event_time > now() - INTERVAL 7 DAY
AND type = 'QueryFinish'
AND is_initial_query
- AND JSONExtractInt(log_comment, 'team_id') = 2
+ -- Only teams that have opted into AI data processing — this widens
+ -- the corpus beyond PostHog's own team 2 to any consenting team's
+ -- real HogQL, while keeping queries from non-consenting teams out.
+ AND JSONExtractString(log_comment, 'ai_data_processing_approved') = 'true'
AND JSONExtractString(log_comment, 'query', 'kind') = 'HogQLQuery'
AND length(JSONExtractString(log_comment, 'query', 'query')) > 0
GROUP BY hogql
-ORDER BY n_occurrences DESC
-LIMIT {int(limit)}
+ORDER BY n_occurrences DESC, hogql
+LIMIT {int(limit)} OFFSET {int(offset)}
SETTINGS log_comment = '{_LOG_COMMENT_TAG}'
"""
-def _repo_relative(path: Path) -> str:
- """Repo-rooted string when `path` is inside `REPO_ROOT`, else
- verbatim — so an out-of-worktree `--input` still prints cleanly."""
- if path.is_absolute() and path.is_relative_to(REPO_ROOT):
- return str(path.relative_to(REPO_ROOT))
- return str(path)
-
-
-# ---------------------------------------------------------------------------
-# hogli wrappers
-# ---------------------------------------------------------------------------
-
-
-def _hogli_bin() -> str:
- """Absolute path to `bin/hogli` — `$PATH` has it under flox for
- interactive shells but agent / CI shells often don't."""
- cand = REPO_ROOT / "bin" / "hogli"
- if not cand.is_file():
- raise RuntimeError(f"bin/hogli not found at {cand} — is the repo root correct?")
- return str(cand)
-
-
-def _discover_clickhouse_db_id(region: str, prefer_offline: bool) -> int:
- """Return a ClickHouse DB id from Metabase, preferring an `OFFLINE`
- shard when `prefer_offline`. Raises if `hogli metabase:databases`
- fails — usually a missing cookie (`hogli metabase:login` first)."""
- out = subprocess.check_output(
- [_hogli_bin(), "metabase:databases", "--region", region, "--format", "json"],
- cwd=REPO_ROOT,
- text=True,
- timeout=60, # don't hang forever on a stalled Metabase / auth wait
- )
- dbs = json.loads(out)
- # case-insensitive: Metabase has drifted casing on metadata fields
- clickhouse_dbs = [db for db in dbs if db.get("engine", "").lower() == "clickhouse"]
- if not clickhouse_dbs:
- raise RuntimeError(f"No ClickHouse databases listed for region={region!r}")
- if prefer_offline:
- offline = [db for db in clickhouse_dbs if "offline" in db.get("name", "").lower()]
- if offline:
- # Any OFFLINE shard has the same `clusterAllReplicas` reach;
- # sort by id just for determinism.
- offline.sort(key=lambda d: d["id"])
- chosen = offline[0]
- print(f" using OFFLINE ClickHouse db id={chosen['id']} name={chosen['name']!r}")
- return int(chosen["id"])
- print(" no OFFLINE ClickHouse DB matched; falling back to first online")
- chosen = sorted(clickhouse_dbs, key=lambda d: d["id"])[0]
- print(f" using ClickHouse db id={chosen['id']} name={chosen['name']!r}")
- return int(chosen["id"])
-
-
-def _download_corpus(region: str, database_id: int, dump_path: Path, sql_limit: int) -> None:
- """Run the redaction SQL via `hogli metabase:query`, saving the JSON
- response to `dump_path` (shape: see `_load_queries`).
-
- hogli writes to a `.tmp` sibling we then `os.replace` into place —
- an interrupted scan can't leave a half-written dump that a later
- `--skip-download` would silently read as truncated JSON."""
- dump_path.parent.mkdir(parents=True, exist_ok=True)
- tmp_path = dump_path.with_suffix(dump_path.suffix + ".tmp")
- print(f" downloading top {sql_limit} via `hogli metabase:query --region {region} --database-id {database_id}` …")
- try:
- subprocess.run(
- [
- _hogli_bin(),
- "metabase:query",
- "--region",
- region,
- "--database-id",
- str(database_id),
- "--format",
- "json",
- "--save",
- str(tmp_path),
- # SQL goes over stdin; `--timeout` covers the slow query_log scan.
- "--timeout",
- "300",
- ],
- input=_build_redaction_sql(sql_limit),
- text=True,
- check=True,
- cwd=REPO_ROOT,
- timeout=360, # process-level backstop above hogli's own `--timeout 300`
- )
- os.replace(tmp_path, dump_path)
- finally:
- tmp_path.unlink(missing_ok=True) # no-op after a successful replace
- print(f" saved {dump_path.stat().st_size:,} bytes to {_repo_relative(dump_path)}")
-
-
-# ---------------------------------------------------------------------------
-# JSON reader
-# ---------------------------------------------------------------------------
-
-
-def _load_queries(path: Path) -> list[tuple[str, int]]:
- """Read the JSON from `hogli metabase:query --format json` into
- `(hogql, n_occurrences)` pairs, skipping empty HogQL. Columns are
- resolved by name (`{"data": {"cols": [...], "rows": [...]}}`) so the
- reader survives column-order changes in the embedded SQL."""
- if not path.exists():
- raise FileNotFoundError(
- f"corpus dump not found at {path}\n hint: drop --skip-download to fetch it from Metabase, or pass --input PATH"
- )
- with open(path) as f:
- payload = json.load(f)
- data = payload.get("data") if isinstance(payload, dict) else None
- if not data or "rows" not in data or "cols" not in data:
- status = payload.get("status") if isinstance(payload, dict) else "<unknown>"
- error = payload.get("error") if isinstance(payload, dict) else None
- raise RuntimeError(
- f"dump at {path} isn't a Metabase /api/dataset success payload (status={status!r}, error={error!r})"
- )
- col_idx = {c.get("name"): i for i, c in enumerate(data["cols"])}
- if "hogql" not in col_idx:
- raise RuntimeError(
- f"dump columns {list(col_idx)} don't include 'hogql' — re-run without --skip-download to refresh the dump"
- )
- hogql_i = col_idx["hogql"]
- n_i = col_idx.get("n_occurrences")
- out: list[tuple[str, int]] = []
- for row in data["rows"]:
- query = row[hogql_i]
- if not isinstance(query, str) or not query.strip():
- continue
- n = 1
- if n_i is not None:
- try:
- n = int(row[n_i])
- except (TypeError, ValueError):
- n = 1
- out.append((query, n))
- return out
-
-
-# ---------------------------------------------------------------------------
-# Parser dispatch
-# ---------------------------------------------------------------------------
-
-
-def _try_parse(query: str, backend: str) -> tuple[str, ast.AST | None, str | None]:
- """Parse `query` with `backend`. Returns `(status, ast_or_none, detail)`:
-
- - `("ok", ast, None)` — parsed; AST is `clear_locations`-normalised
- so callers can `==`-compare oracle vs candidate.
- - `("reject", None, error)` — backend declined it (`BaseHogQLError`).
- - `("crash", None, traceback)` — backend raised something else
- (`RecursionError`, …). A crash is itself a finding worth
- recording, so we bucket it rather than abort the run. Ctrl-C
- (`BaseException`, not `Exception`) still propagates."""
- try:
- node = parse_select(query, backend=backend) # type: ignore[arg-type]
- return "ok", clear_locations(node), None
- except BaseHogQLError as e:
- return "reject", None, str(e)
- except Exception:
- return "crash", None, traceback.format_exc()
-
-
-# ---------------------------------------------------------------------------
-# Error bucketing
-# ---------------------------------------------------------------------------
-
-# `_GOT_RE` is shared with the other diagnostic scripts; `_AT_RE` is local —
-# only this script's `_bucket_error` strips position suffixes.
-_AT_RE = re.compile(r"at\s+(line\s+\d+|offset\s+\d+|position\s+\d+|\d+:\d+)", re.IGNORECASE)
-
-
-def _bucket_error(msg: str) -> str:
- """Normalise an error message so same-cause rejects group together —
- drops position-dependent suffixes (`got <X>`, `at line N`), clips
- to 160 chars."""
- msg = _GOT_RE.sub("got <X>", msg)
- msg = _AT_RE.sub("at <pos>", msg)
- return msg.strip()[:160]
-
-
-def _crash_signature(tb: str) -> str:
- """Bucket a crash by its traceback's last line (the
- `ExceptionType: message`) so same-cause crashes group together."""
- lines = [ln for ln in tb.splitlines() if ln.strip()]
- return _bucket_error(lines[-1]) if lines else "<empty traceback>"
-
-
-# ---------------------------------------------------------------------------
-# Failure file writer
-# ---------------------------------------------------------------------------
-
-
[email protected](frozen=True)
-class Failure:
- """Single failing-query record for the failure file."""
-
- # "candidate_reject" | "candidate_crash" | "ast_mismatch" | "oracle_crash"
- kind: str
- query: str
- detail: str # rejection error, crash traceback, or formatted diff path
- n_occurrences: int
-
-
-def _write_failures(path: Path, failures: list[Failure]) -> None:
- """One block per failing query, separated by a `-- =====` ruler,
- carrying the rejection error / crash traceback / AST diff path so a
- follow-up triage pass can bucket by root cause. Written via a
- `.tmp` sibling + `os.replace` so a crash mid-write can't leave a
- truncated file."""
- path.parent.mkdir(parents=True, exist_ok=True)
- by_kind = Counter(fa.kind for fa in failures)
- breakdown = ", ".join(f"{n} {kind}" for kind, n in sorted(by_kind.items())) or "none"
- tmp_path = path.with_suffix(path.suffix + ".tmp")
- with open(tmp_path, "w") as f:
- f.write(f"-- hogql_log_corpus_failures.sql — {len(failures)} entries\n")
- f.write(f"-- ({breakdown})\n")
- f.write("-- Each block: occurrences count, failure kind + detail, then the query.\n")
- f.write("-- Generated by posthog/hogql/scripts/log_corpus_diagnostic.py\n\n")
- for i, fa in enumerate(failures):
- f.write("-- " + "=" * 76 + "\n")
- f.write(f"-- [{i + 1}/{len(failures)}] seen {fa.n_occurrences}x in last 7d\n")
- f.write(f"-- kind: {fa.kind}\n")
- for line in fa.detail.splitlines() or [""]:
- f.write(f"-- {line}\n" if line else "--\n")
- f.write("\n")
- f.write(fa.query.rstrip("\n") + "\n\n")
- os.replace(tmp_path, path)
-
-
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
@@ -395,17 +167,12 @@ def _write_failures(path: Path, failures: list[Failure]) -> None:
def main() -> int:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- p.add_argument(
- "--region",
- choices=("us", "eu", "dev"),
- default="us",
- help="Metabase region (default: us; team 2 is PostHog's own US team)",
- )
+ p.add_argument("--region", choices=("us", "eu", "dev"), default="us", help="Metabase region (default: us)")
p.add_argument(
"--database-id",
type=int,
default=None,
- help="ClickHouse Metabase DB id. Default: auto-discover via `hogli metabase:databases`, preferring OFFLINE shards.",
+ help="ClickHouse Metabase DB id. Default: auto-discover, preferring OFFLINE shards.",
)
p.add_argument(
"--prefer-online",
@@ -416,7 +183,7 @@ def main() -> int:
"--input",
type=Path,
default=DEFAULT_DUMP,
- help=f"Path to the redacted JSON dump (default: {_repo_relative(DEFAULT_DUMP)})",
+ help=f"Path to the redacted JSON dump (default: {repo_relative(DEFAULT_DUMP, REPO_ROOT)})",
)
p.add_argument(
"--skip-download",
@@ -437,7 +204,7 @@ def main() -> int:
"--write-failures",
metavar="PATH",
default=None,
- help="Output file for SQLs the candidate rejects (default: <dump>.failures.sql alongside the dump)",
+ help="Output file for failing queries (default: <dump>.failures.sql alongside the dump)",
)
p.add_argument(
"--limit",
@@ -449,19 +216,17 @@ def main() -> int:
f"we pull up to {_DEFAULT_SQL_LIMIT} rows."
),
)
- p.add_argument("--verbose", action="store_true", help="Print one line per failure / skip with the error")
+ p.add_argument("--verbose", action="store_true", help="Print one line per AST mismatch")
args = p.parse_args()
if args.limit is not None and args.limit <= 0:
p.error("--limit must be a positive integer")
- # Fail fast on a bad backend name — `_probe_backend` bypasses the
- # `except Exception` in `_try_parse` that would swallow a typo's `KeyError`.
+ # Fail fast on a bad backend name.
for label, backend in (("oracle", args.oracle), ("candidate", args.candidate)):
err = _probe_backend("select", backend)
if err is not None:
print(f"ERROR: {label} backend {backend!r} unavailable: {err}")
return 1
-
if args.oracle == args.candidate:
print(
f"WARNING: --oracle and --candidate are both {args.oracle!r} — "
@@ -483,32 +248,34 @@ def main() -> int:
if args.database_id is None:
print("Auto-discovering ClickHouse DB id …")
try:
- args.database_id = _discover_clickhouse_db_id(args.region, prefer_offline=not args.prefer_online)
+ args.database_id = discover_metabase_db(
+ args.region,
+ "clickhouse",
+ REPO_ROOT,
+ prefer_name_substring=None if args.prefer_online else "offline",
+ )
except subprocess.CalledProcessError as e:
print(f"ERROR: `hogli metabase:databases` failed (exit {e.returncode})")
print(f" hint: run `./bin/hogli metabase:login --region {args.region}` first")
return 1
except subprocess.TimeoutExpired:
print("ERROR: `hogli metabase:databases` timed out after 60s")
- print(f" hint: run `./bin/hogli metabase:login --region {args.region}` first")
return 1
else:
print(f"Using --database-id {args.database_id}")
- # `--limit N` also caps the SQL `LIMIT` so quick runs stay fast.
sql_limit = args.limit if args.limit and args.limit < _DEFAULT_SQL_LIMIT else _DEFAULT_SQL_LIMIT
try:
- _download_corpus(args.region, args.database_id, args.input, sql_limit)
+ download_corpus(args.region, args.database_id, args.input, sql_limit, _build_corpus_sql, REPO_ROOT)
except subprocess.CalledProcessError as e:
print(f"ERROR: `hogli metabase:query` failed (exit {e.returncode})")
return 1
except subprocess.TimeoutExpired:
- print("ERROR: `hogli metabase:query` timed out after 360s")
- print(" hint: narrow the scan with --limit, or retry — the query_log scan can be slow")
+ print("ERROR: `hogli metabase:query` timed out — narrow the scan with --limit, or retry")
return 1
# 2. Load.
- rows = _load_queries(args.input)
- print(f"Loaded {len(rows)} unique queries from {_repo_relative(args.input)}")
+ rows = load_corpus_rows(args.input, text_col="hogql", count_col="n_occurrences")
+ print(f"Loaded {len(rows)} unique queries from {repo_relative(args.input, REPO_ROOT)}")
if args.limit is not None and args.limit < len(rows):
rows = rows[: args.limit]
print(f" (capped to first {args.limit} via --limit)")
@@ -517,161 +284,24 @@ def main() -> int:
print()
print("Running parity check (oracle then candidate per query)…")
print()
- counts: Counter[str] = Counter()
- reject_buckets: Counter[str] = Counter()
- crash_buckets: Counter[str] = Counter()
- mismatch_buckets: Counter[tuple[str, str]] = Counter()
- oracle_reject_buckets: Counter[str] = Counter()
- failures: list[Failure] = []
-
- # Flush partial results on Ctrl-C: a grind over thousands of
- # queries takes minutes, and the failure file is the whole point
- # of the run. A SIGINT sets a flag the loop checks at the next
- # iteration boundary, so the summary + failure dump below still
- # run against whatever was accumulated rather than being lost.
- interrupted = False
-
- def _on_sigint(_signum: int, _frame: object) -> None:
- nonlocal interrupted
- interrupted = True
-
- prev_sigint = signal.signal(signal.SIGINT, _on_sigint)
-
- for i, (query, n_occ) in enumerate(rows):
- if interrupted:
- print(f"\nInterrupted at {i}/{len(rows)} — writing partial results…")
- break
- if (i + 1) % 50 == 0:
- sys.stderr.write(
- f"\r {i + 1}/{len(rows)} processed (pass={counts['pass']} reject={counts['candidate_reject']} "
- f"mismatch={counts['ast_mismatch']} crash={counts['candidate_crash'] + counts['oracle_crash']} "
- f"skip={counts['oracle_reject']})"
- )
- sys.stderr.flush()
- counts["total"] += 1
- oracle_status, oracle_ast, oracle_detail = _try_parse(query, args.oracle)
- if oracle_status == "reject":
- counts["oracle_reject"] += 1
- sig = _bucket_error(oracle_detail or "")
- oracle_reject_buckets[sig] += 1
- if args.verbose:
- print(f" SKIP: {sig}")
- continue
- if oracle_status == "crash":
- # Oracle crash is a finding too; record it, but with no
- # oracle AST there's nothing to compare — skip the candidate.
- counts["oracle_crash"] += 1
- crash_buckets[_crash_signature(oracle_detail or "")] += 1
- failures.append(
- Failure(
- kind="oracle_crash",
- query=query,
- detail=oracle_detail or "<no traceback>",
- n_occurrences=n_occ,
- )
- )
- if args.verbose:
- print(f" ORACLE CRASH (seen {n_occ}x): {_crash_signature(oracle_detail or '')}")
- continue
- candidate_status, candidate_ast, candidate_detail = _try_parse(query, args.candidate)
- if candidate_status == "reject":
- counts["candidate_reject"] += 1
- sig = _bucket_error(candidate_detail or "")
- reject_buckets[sig] += 1
- failures.append(
- Failure(
- kind="candidate_reject",
- query=query,
- detail=candidate_detail or "<no message>",
- n_occurrences=n_occ,
- )
- )
- if args.verbose:
- print(f" REJECT (seen {n_occ}x): {sig}")
- continue
- if candidate_status == "crash":
- counts["candidate_crash"] += 1
- sig = _crash_signature(candidate_detail or "")
- crash_buckets[sig] += 1
- failures.append(
- Failure(
- kind="candidate_crash",
- query=query,
- detail=candidate_detail or "<no traceback>",
- n_occurrences=n_occ,
- )
- )
- if args.verbose:
- print(f" CANDIDATE CRASH (seen {n_occ}x): {sig}")
- continue
- if oracle_ast == candidate_ast:
- counts["pass"] += 1
- continue
- counts["ast_mismatch"] += 1
- steps = _diff_path(oracle_ast, candidate_ast)
- bucket = (_node_type(oracle_ast), _node_type(candidate_ast))
- mismatch_buckets[bucket] += 1
- failures.append(
- Failure(
- kind="ast_mismatch",
- query=query,
- detail=_format_diff_path(steps),
- n_occurrences=n_occ,
- )
- )
- if args.verbose:
- print(f" MISMATCH (seen {n_occ}x): {bucket[0]} vs {bucket[1]}")
-
- signal.signal(signal.SIGINT, prev_sigint)
- sys.stderr.write("\r" + " " * 110 + "\r")
-
- # 4. Summary.
- print()
- print("=== Summary ===")
- for k in ("total", "pass", "candidate_reject", "candidate_crash", "ast_mismatch", "oracle_crash", "oracle_reject"):
- print(f" {k:25s} {counts[k]}")
-
- if oracle_reject_buckets:
- print()
- print(f"=== Oracle ({args.oracle}) reject buckets ({sum(oracle_reject_buckets.values())} total) ===")
- for sig, n in oracle_reject_buckets.most_common(20):
- print(f" {n:5d} {sig}")
- if len(oracle_reject_buckets) > 20:
- print(f" … and {len(oracle_reject_buckets) - 20} more buckets")
-
- if reject_buckets:
- print()
- print(f"=== Candidate ({args.candidate}) reject buckets ({sum(reject_buckets.values())} total) ===")
- for sig, n in reject_buckets.most_common(30):
- print(f" {n:5d} {sig}")
- if len(reject_buckets) > 30:
- print(f" … and {len(reject_buckets) - 30} more buckets")
-
- if crash_buckets:
- print()
- print(f"=== Crash buckets ({sum(crash_buckets.values())} total — non-HogQL exceptions) ===")
- for sig, n in crash_buckets.most_common(30):
- print(f" {n:5d} {sig}")
- if len(crash_buckets) > 30:
- print(f" … and {len(crash_buckets) - 30} more buckets")
+ result = run_corpus_parity(
+ rows,
+ rule="select",
+ oracle=args.oracle,
+ candidate=args.candidate,
+ verbose=args.verbose,
+ noun="query",
+ )
+ print_corpus_summary(result, oracle=args.oracle, candidate=args.candidate)
- if mismatch_buckets:
- print()
- print(f"=== AST mismatch buckets ({sum(mismatch_buckets.values())} total) ===")
- print(f" {'count':>5} {'oracle':25s} vs candidate")
- for (o_root, c_root), n in mismatch_buckets.most_common(30):
- print(f" {n:5d} {o_root:25s} vs {c_root}")
- if len(mismatch_buckets) > 30:
- print(f" … and {len(mismatch_buckets) - 30} more buckets")
-
- # 5. Failure dump.
- if failures:
+ # 4. Failure dump.
+ if result.failures:
out_path = Path(args.write_failures) if args.write_failures else args.input.with_suffix(".failures.sql")
- _write_failures(out_path, failures)
+ write_failures(out_path, result.failures, REPO_ROOT, title="hogql_log_corpus_failures.sql")
print()
- print(f"Wrote {len(failures)} failing queries to {_repo_relative(out_path)}")
+ print(f"Wrote {len(result.failures)} failing queries to {repo_relative(out_path, REPO_ROOT)}")
- return 130 if interrupted else 0
+ return 130 if result.interrupted else 0
if __name__ == "__main__":
diff --git a/posthog/hogql/scripts/parser_bench.py b/posthog/hogql/scripts/parser_bench.py
index d76f599a054c..47e2974257bf 100644
--- a/posthog/hogql/scripts/parser_bench.py
+++ b/posthog/hogql/scripts/parser_bench.py
@@ -50,8 +50,21 @@ DEFAULT_N = 1_000 # iterations per row; override with --n
# `--n` (e.g. a 50-iteration sanity check) is never raised back up.
N_PER_QUERY: dict[str, int] = {
"pathological_deep": 100,
+ # cpp is comparatively slow on this one; cap iterations so the row
+ # stays a few seconds rather than tens.
+ "nested_maybe_quadratic": 200,
}
+
+def _nested_replace(depth: int) -> str:
+ """`columns(* replace(… as b))` nested `depth` levels deep — the
+ `nested_maybe_quadratic` bench query (see EXPR_QUERIES)."""
+ inner = "a"
+ for _ in range(depth):
+ inner = f"columns(* replace({inner} as b))"
+ return inner
+
+
EXPR_QUERIES: dict[str, str] = {
"int_literal": "1",
"arith": "1 + 2 * 3",
@@ -109,6 +122,17 @@ EXPR_QUERIES: dict[str, str] = {
AND (properties.url LIKE '%admin%' OR properties.url LIKE '%dashboard%')
AND NOT (properties.os = 'Linux' AND properties.device = 'Desktop')
""",
+ # Deeply-nested `columns(* replace(… as b))`. Each REPLACE item
+ # parse runs a forward scan (`find_replace_item_as_pos`, and the
+ # sibling `find_cast_separator_pos`) to locate the item's
+ # separating `AS`; that scan is O(remaining input) and re-runs at
+ # every nesting level, so a hand-rolled parser is O(N^2) here
+ # while ANTLR (cpp) stays linear. This row is the canary for that
+ # scan: if the candidate's per-call µs — or the cpp/candidate
+ # ratio — degrades, the AS-position scan has regressed. The scan
+ # constant is a raw byte walk, so at this depth the candidate
+ # should still parse it in well under a millisecond.
+ "nested_maybe_quadratic": _nested_replace(50),
}
SELECT_QUERIES: dict[str, str] = {
diff --git a/posthog/hogql/scripts/pbt_corpus.py b/posthog/hogql/scripts/pbt_corpus.py
index d1f2110bafc6..28454a210148 100644
--- a/posthog/hogql/scripts/pbt_corpus.py
+++ b/posthog/hogql/scripts/pbt_corpus.py
@@ -55,8 +55,8 @@ from posthog.hogql.scripts._diagnostic_common import (
DivergenceShape,
_ast_mismatch_shape,
_probe_backend,
- _safe_parse,
_shape_for,
+ corpus_try_parse,
)
@@ -171,16 +171,16 @@ def cmd_check(args: argparse.Namespace) -> int:
return 2
probed.add((oracle, candidate, rule))
# `_shape_for` returns None for TWO distinct cases: oracle
- # and candidate agree (genuinely fixed), OR the oracle now
- # rejects the query. Every corpus entry was recorded
- # *because* the oracle accepted it, so an oracle rejection
- # is a behaviour change in the oracle itself — classifying
- # it as "fixed" would let a regressed oracle masquerade as
- # a clean run. Check the oracle independently first and
- # bucket those separately. (The startup probe only checks
- # the oracle is reachable via a trivial `"1"` parse — it
- # can't catch a per-query behaviour change.)
- o_status, _, _ = _safe_parse(entry["query"], rule, oracle)
+ # and candidate agree (genuinely fixed), OR the oracle no
+ # longer cleanly accepts the query. Every corpus entry was
+ # recorded *because* the oracle accepted it, so an oracle
+ # reject/crash is a behaviour change in the oracle itself —
+ # classifying it as "fixed" would let a regressed oracle
+ # masquerade as a clean run. Check the oracle independently
+ # first and bucket those separately. (The startup probe
+ # only checks the oracle is reachable via a trivial `"1"`
+ # parse — it can't catch a per-query behaviour change.)
+ o_status, _, _ = corpus_try_parse(entry["query"], rule, oracle)
if o_status != "ok":
counts["oracle_rejects"] += 1
if len(sample["oracle_rejects"]) < args.max_samples:
diff --git a/posthog/hogql/scripts/pbt_diagnostic.py b/posthog/hogql/scripts/pbt_diagnostic.py
index c74ae94cd483..50f8e3437d8f 100644
--- a/posthog/hogql/scripts/pbt_diagnostic.py
+++ b/posthog/hogql/scripts/pbt_diagnostic.py
@@ -68,7 +68,7 @@ import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
django.setup()
-from hypothesis import given, settings
+from hypothesis import assume, given, settings
from posthog.hogql.scripts._diagnostic_common import (
DivergenceShape,
@@ -80,7 +80,7 @@ from posthog.hogql.scripts._diagnostic_common import (
_safe_parse,
_shape_for,
)
-from posthog.hogql.test._generated_grammar_strategies import expr_strategy, select_strategy
+from posthog.hogql.test._generated_grammar_strategies import expr_strategy, program_strategy, select_strategy
from posthog.hogql.test.test_parser_grammar_pbt import _PBT_SETTINGS, _apply_jiggle
# ---------------------------------------------------------------------------
@@ -191,8 +191,18 @@ def _print_failure_sample(
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--n", type=int, default=int(os.environ.get("N", "500")))
- parser.add_argument("--rule", choices=("expr", "select"), default="expr")
+ parser.add_argument("--rule", choices=("expr", "select", "program"), default="expr")
parser.add_argument("--jiggle", action="store_true")
+ parser.add_argument(
+ "--accepted-only",
+ action="store_true",
+ help=(
+ "Make `--n` count only examples the ORACLE accepts: oracle "
+ "rejects/crashes are `assume()`d out (Hypothesis keeps "
+ "generating until --n oracle-accepted examples are reached), "
+ "so the match denominator is exactly --n."
+ ),
+ )
parser.add_argument(
"--oracle",
default=os.environ.get("ORACLE_BACKEND", "cpp-json"),
@@ -254,7 +264,11 @@ def main() -> int:
# abort the whole grind. Keyed by normalised `<ExcType>: …`.
crash_buckets: dict[str, list[str]] = {}
- base_strategy = expr_strategy() if args.rule == "expr" else select_strategy()
+ base_strategy = {
+ "expr": expr_strategy,
+ "select": select_strategy,
+ "program": program_strategy,
+ }[args.rule]()
strategy = base_strategy.flatmap(_apply_jiggle) if args.jiggle else base_strategy
# Stream JSONL during the run rather than collecting everything in
@@ -287,12 +301,19 @@ def main() -> int:
o_status, o_ast, _ = _safe_parse(query, args.rule, oracle)
if o_status == "reject":
counts["oracle_reject"] += 1
+ # `--accepted-only`: discard so this doesn't count toward
+ # `max_examples` — Hypothesis regenerates until `--n`
+ # oracle-accepted examples land.
+ if args.accepted_only:
+ assume(False)
return
if o_status == "crash":
# The oracle (source of truth) crashing is its own kind of
# finding — count it, but with no oracle AST there's
# nothing to compare the candidate against, so stop here.
counts["oracle_crash"] += 1
+ if args.accepted_only:
+ assume(False)
return
c_status, c_ast, c_detail = _safe_parse(query, args.rule, candidate)
diff --git a/posthog/hogql/test/_generated_grammar_strategies.py b/posthog/hogql/test/_generated_grammar_strategies.py
index 4451bf9eb8d9..668fcfb0f18b 100644
--- a/posthog/hogql/test/_generated_grammar_strategies.py
+++ b/posthog/hogql/test/_generated_grammar_strategies.py
@@ -32,9 +32,9 @@ from posthog.hogql.test._grammar_token_strategies import (
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)
+_DEFAULT_DEPTH = 5
+_MAX_REPEAT = 4 # cap for `*` / `+` quantifiers (per occurrence)
+_MAX_LR_CHAIN = 4 # 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
@@ -80,6 +80,38 @@ def _include_soft(draw: Any) -> bool:
return draw(st.integers(min_value=0, max_value=_SOFT_FREQ_DENOM - 1)) == 0
+def program_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(declaration_strategy(_dec(depth))))
+ parts.append("")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def declaration_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(varDecl_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(statement_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
@functools.cache
def expression_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
@@ -91,6 +123,21 @@ def expression_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
return gen()
+def varDecl_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("let")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(":=")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
@functools.cache
def identifierList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
@@ -107,6 +154,296 @@ def identifierList_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[st
return gen()
+def statement_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=11))
+ if alt_idx == 0:
+ parts = []
+ parts.append(draw(returnStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 1:
+ parts = []
+ parts.append(draw(throwStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 2:
+ parts = []
+ parts.append(draw(tryCatchStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 3:
+ parts = []
+ parts.append(draw(ifStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 4:
+ parts = []
+ parts.append(draw(whileStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 5:
+ parts = []
+ parts.append(draw(forInStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 6:
+ parts = []
+ parts.append(draw(forStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 7:
+ parts = []
+ parts.append(draw(funcStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 8:
+ parts = []
+ parts.append(draw(varAssignment_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 9:
+ parts = []
+ parts.append(draw(block_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 10:
+ parts = []
+ parts.append(draw(exprStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ if alt_idx == 11:
+ parts = []
+ parts.append(draw(emptyStmt_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+ raise AssertionError("unreachable")
+
+ return gen()
+
+
+def returnStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("return")
+ if _include_optional(draw):
+ parts.append(draw(expression_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def throwStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("throw")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def catchBlock_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("catch")
+ if _include_optional(draw):
+ parts.append("(")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(":")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ parts.append(")")
+ parts.append(draw(block_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def tryCatchStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("try")
+ parts.append(draw(block_strategy(_dec(depth))))
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(catchBlock_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append("finally")
+ parts.append(draw(block_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def ifStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("if")
+ parts.append("(")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(")")
+ parts.append(draw(statement_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append("else")
+ parts.append(draw(statement_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def whileStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("while")
+ parts.append("(")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(")")
+ parts.append(draw(statement_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def forStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("for")
+ parts.append("(")
+ if _include_optional(draw):
+ group_idx = draw(st.integers(min_value=0, max_value=2))
+ if group_idx == 0:
+ parts.append(draw(varDecl_strategy(_dec(depth))))
+ if group_idx == 1:
+ parts.append(draw(varAssignment_strategy(_dec(depth))))
+ if group_idx == 2:
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(";")
+ if _include_optional(draw):
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(";")
+ if _include_optional(draw):
+ group_idx = draw(st.integers(min_value=0, max_value=2))
+ if group_idx == 0:
+ parts.append(draw(varDecl_strategy(_dec(depth))))
+ if group_idx == 1:
+ parts.append(draw(varAssignment_strategy(_dec(depth))))
+ if group_idx == 2:
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(")")
+ parts.append(draw(statement_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def forInStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("for")
+ parts.append("(")
+ parts.append("let")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(",")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ parts.append("in")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(")")
+ parts.append(draw(statement_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def funcStmt_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("fn")
+ if group_idx == 1:
+ parts.append("fun")
+ parts.append(draw(identifier_strategy(_dec(depth))))
+ parts.append("(")
+ if _include_optional(draw):
+ parts.append(draw(identifierList_strategy(_dec(depth))))
+ parts.append(")")
+ parts.append(draw(block_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def varAssignment_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(expression_strategy(_dec(depth))))
+ parts.append(":=")
+ parts.append(draw(expression_strategy(_dec(depth))))
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def exprStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(draw(expression_strategy(_dec(depth))))
+ if _include_optional(draw):
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def emptyStmt_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append(";")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
+def block_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
+ @st.composite
+ def gen(draw: Any) -> str:
+ parts: list[str] = []
+ parts.append("{")
+ for _ in range(draw(st.integers(min_value=0, max_value=_MAX_REPEAT))):
+ parts.append(draw(declaration_strategy(_dec(depth))))
+ parts.append("}")
+ return " ".join(p for p in parts if p)
+
+ return gen()
+
+
@functools.cache
def select_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[str]:
@st.composite
@@ -2105,7 +2442,11 @@ def columnLambdaExpr_strategy(depth: int = _DEFAULT_DEPTH) -> st.SearchStrategy[
parts.append("(")
parts.append(")")
parts.append("->")
- parts.append(draw(columnExpr_strategy(_dec(depth))))
+ group_idx = draw(st.integers(min_value=0, max_value=1))
+ if group_idx == 0:
+ parts.append(draw(columnExpr_strategy(_dec(depth))))
+ if group_idx == 1:
+ parts.append(draw(block_strategy(_dec(depth))))
return " ".join(p for p in parts if p)
if alt_idx == 1:
parts = []