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): parser-parity diagnostic tooling in posthog/hogql/scripts/ (#58633)

Robbie09dd47e67903
diff --git a/.gitignore b/.gitignore
index 6ab119051052..39a08a9db548 100644
--- a/.gitignore
+++ b/.gitignore
@@ -203,3 +203,8 @@ junit.xml
# Downloaded GitHub issues for signals
products/signals/backend/github_issues/
.pnpm-store
+
+# Local-only HogQL log-corpus dumps (downloaded from Metabase by
+# posthog/hogql/scripts/log_corpus_diagnostic.py — contains
+# redacted production queries; not for git).
+posthog/hogql/scripts/.local/
diff --git a/posthog/hogql/scripts/_diagnostic_common.py b/posthog/hogql/scripts/_diagnostic_common.py
new file mode 100644
index 000000000000..9a4122ae3020
--- /dev/null
+++ b/posthog/hogql/scripts/_diagnostic_common.py
@@ -0,0 +1,263 @@
+"""Shared helpers for the HogQL parser-parity diagnostic scripts.
+
+Imported by `pbt_diagnostic.py`, `pbt_corpus.py`, `parser_bench.py`,
+and `log_corpus_diagnostic.py` in this directory. Not a CLI itself —
+the leading underscore marks it as a private helper module.
+
+Holds the cross-script vocabulary:
+
+- **Parse** — `_safe_parse` parses a query and classifies the outcome
+ `ok` / `reject` / `crash`, never propagating a backend crash (a CLI
+ diagnostic buckets crashes rather than aborting the grind).
+- **AST diff path** — `_node_type` / `_diff_path` / `_format_diff_path`
+ walk two ASTs together and pinpoint the first divergence.
+- **Divergence shape** — `DivergenceShape` / `_ast_mismatch_shape` /
+ `_shape_for` reduce a divergence to a structural key two examples of
+ the same bug compare equal under.
+- **Error normalisation** — `_normalize_error` strips position-dependent
+ payloads so same-cause rejects/crashes bucket together.
+- **Backend probe** — `_probe_backend` fails fast on an unusable
+ `--oracle` / `--candidate`.
+
+Importing this module pulls `posthog.hogql.*` — callers must have run
+`django.setup()` first (every script here does, before its imports).
+"""
+
+from __future__ import annotations
+
+import re
+import dataclasses
+from typing import Any
+
+from posthog.hogql.errors import BaseHogQLError
+from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.visitor import clear_locations
+
+# ---------------------------------------------------------------------------
+# AST diff path
+# ---------------------------------------------------------------------------
+
+
+def _node_type(node: Any) -> str:
+ """Top-level AST node type label, e.g. `Call` / `ExprCall` / `Not`."""
+ return type(node).__name__ if node is not None else "<None>"
+
+
+def _node_fields(node: Any) -> list[tuple[str, Any]]:
+ """`(field_name, value)` pairs for an AST node in declaration order.
+ HogQL AST nodes are `__slots__` dataclasses, so `dataclasses.fields()`
+ is the canonical accessor; non-dataclass leaves return `[]` and fall
+ through to the value-terminal branch in `_diff_path`."""
+ if not dataclasses.is_dataclass(node):
+ return []
+ return [(f.name, getattr(node, f.name, None)) for f in dataclasses.fields(node)]
+
+
+def _diff_path(oracle: Any, candidate: Any, path: list | None = None, depth: int = 0) -> list:
+ """Walk both ASTs together; return the `.field` / `[i]` breadcrumbs
+ from root to the first divergence, terminating with a 3-tuple
+ `(label, oracle_repr, candidate_repr)`. Depth-bounded so pathological
+ deep trees don't blow the stack."""
+ path = path or []
+ if depth > 64:
+ return [*path, ("<depth-limit>", repr(oracle)[:120], repr(candidate)[:120])]
+ if oracle == candidate:
+ return path
+ o_t = _node_type(oracle)
+ c_t = _node_type(candidate)
+ if o_t != c_t:
+ return [*path, ("<type>", o_t, c_t)]
+
+ if isinstance(oracle, list) and isinstance(candidate, list):
+ if len(oracle) != len(candidate):
+ return [*path, ("<len>", str(len(oracle)), str(len(candidate)))]
+ for i, (a, b) in enumerate(zip(oracle, candidate)):
+ if a != b:
+ return _diff_path(a, b, [*path, f"[{i}]"], depth + 1)
+ return path
+ if isinstance(oracle, dict) and isinstance(candidate, dict):
+ if set(oracle) != set(candidate):
+ return [*path, ("<keys>", str(sorted(oracle)), str(sorted(candidate)))]
+ for k in oracle:
+ if oracle[k] != candidate[k]:
+ return _diff_path(oracle[k], candidate[k], [*path, f"[{k!r}]"], depth + 1)
+ return path
+ o_fields = _node_fields(oracle)
+ c_fields = dict(_node_fields(candidate))
+ if o_fields:
+ for name, ov in o_fields:
+ cv = c_fields.get(name)
+ if ov == cv:
+ continue
+ return _diff_path(ov, cv, [*path, f".{name}"], depth + 1)
+ return [*path, ("<unequal-but-fields-match>", repr(oracle)[:120], repr(candidate)[:120])]
+ return [*path, ("<value>", repr(oracle), repr(candidate))]
+
+
+def _format_diff_path(steps: list) -> str:
+ """Format a diff path as breadcrumbs ending with the differing
+ oracle/candidate values."""
+ if not steps:
+ return " (no diff)"
+ breadcrumbs: list[str] = []
+ terminal: tuple[str, str, str] | None = None
+ for step in steps:
+ if isinstance(step, tuple):
+ terminal = step
+ else:
+ breadcrumbs.append(step)
+ label = "root" + "".join(breadcrumbs)
+ if terminal is None:
+ return f" {label}: (no terminal value)"
+ field, o_repr, c_repr = terminal
+ return f" {label}{field}\n oracle: {o_repr[:200]}\n candidate: {c_repr[:200]}"
+
+
+# ---------------------------------------------------------------------------
+# Divergence shape (a stable bucket key — used for shrinking + corpus dedup)
+# ---------------------------------------------------------------------------
+#
+# Two divergences are "the same shape" if they reach the same terminal
+# diff at the same root-type pair, OR they're the same kind of reject
+# (matching error message).
+
+
[email protected](frozen=True)
+class DivergenceShape:
+ """Structural-only divergence descriptor — designed so two examples
+ of the same divergence (with different leaf values) compare equal.
+
+ For ast_mismatch:
+ - `kind` = "ast_mismatch"
+ - `root_pair` = (oracle_root_type, candidate_root_type)
+ - `terminal_kind` = the kind tag of the final diff step
+ (`<type>` / `<value>` / `<keys>` / `<len>` /
+ `<unequal-but-fields-match>` / `<depth-limit>`).
+ - `terminal_types` = for `<type>` terminals only, the
+ (oracle_type, candidate_type) pair that diverged. None for
+ all other terminal kinds — those are inherently structural.
+
+ For candidate_reject:
+ - `kind` = "candidate_reject"
+ - `reject_signature` = the normalised error message
+ """
+
+ kind: str
+ root_pair: tuple[str, str] | None = None
+ terminal_kind: str | None = None
+ terminal_types: tuple[str, str] | None = None
+ reject_signature: str | None = None
+
+
+def _ast_mismatch_shape(root_pair: tuple[str, str], steps: list) -> DivergenceShape:
+ """Build a structural `DivergenceShape` for an ast_mismatch from the
+ root-type pair and the diff-path output. Accepts both tuple-form
+ steps (in-memory) and list-form (after JSON round-trip). Leaf VALUES
+ of `<value>` / `<keys>` / `<len>` are intentionally dropped — two
+ divergences are "the same shape" if they reach the same kind of leaf
+ at the same root, regardless of which specific value differed."""
+ terminal: tuple[str, str, str] | None = None
+ for s in reversed(steps):
+ if isinstance(s, tuple) and len(s) == 3:
+ terminal = s
+ break
+ if isinstance(s, list) and len(s) == 3 and all(isinstance(x, str) for x in s):
+ terminal = (s[0], s[1], s[2])
+ break
+ if terminal is None:
+ return DivergenceShape(kind="ast_mismatch", root_pair=root_pair)
+ kind_tag = terminal[0]
+ types = (terminal[1], terminal[2]) if kind_tag == "<type>" else None
+ return DivergenceShape(
+ kind="ast_mismatch",
+ root_pair=root_pair,
+ terminal_kind=kind_tag,
+ terminal_types=types,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Error normalisation
+# ---------------------------------------------------------------------------
+
+_GOT_RE = re.compile(r"got\s+\S+", re.IGNORECASE)
+
+
+def _normalize_error(msg: str) -> str:
+ """Strip position-dependent suffixes so similar rejects bucket
+ together — e.g. `expected ), got Keyword(Order)` and `expected ),
+ got Number` collapse to `expected ), got <X>`."""
+ return _GOT_RE.sub("got <X>", msg)[:120]
+
+
+def _safe_parse(query: str, rule: str, backend: str) -> tuple[str, Any, str | None]:
+ """Parse `query` for a diagnostic that must not abort mid-grind.
+ Returns `(status, ast_or_none, detail)`:
+
+ - `("ok", ast, None)` — parsed; AST is `clear_locations`-normalised
+ so callers can `==`-compare oracle vs candidate.
+ - `("reject", None, signature)` — `BaseHogQLError`; a legitimate
+ "not valid HogQL". `signature` is the normalised error message.
+ - `("crash", None, signature)` — any other exception
+ (`RecursionError`, a half-built backend's `RuntimeError`, …). The
+ pytest PBT's own `_try_parse` lets these propagate so pytest
+ records the failure; a CLI diagnostic instead buckets the crash
+ as a finding and keeps going. `signature` is `<ExcType>: …`.
+
+ `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
+ try:
+ node = parser_fn(query, backend=backend) # type: ignore[arg-type]
+ except BaseHogQLError as e:
+ return "reject", None, _normalize_error(str(e))
+ except Exception as e:
+ return "crash", None, _normalize_error(f"{type(e).__name__}: {e}")
+ return "ok", clear_locations(node), None
+
+
+# ---------------------------------------------------------------------------
+# Backend probe + divergence classifier
+# ---------------------------------------------------------------------------
+
+
+def _probe_backend(rule: str, backend: str) -> str | None:
+ """Sanity-probe a backend by parsing `"1"` directly through the
+ parser entry point. Returns None on success, or a human-readable
+ 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
+ try:
+ probe_fn("1", backend=backend) # type: ignore[arg-type]
+ except BaseHogQLError:
+ # Rejecting `"1"` would be surprising but isn't a backend
+ # failure — `_try_parse` would also classify this as a reject.
+ return None
+ except Exception as e:
+ return str(e)
+ return None
+
+
+def _shape_for(
+ query: str,
+ rule: str,
+ oracle_backend: str,
+ candidate_backend: str,
+) -> DivergenceShape | None:
+ """Determine the divergence shape of `query`, or None if there's no
+ divergence to track. Returns None when the oracle doesn't cleanly
+ accept (reject or crash — nothing to compare against) and when the
+ candidate crashes (a crash isn't a stable `DivergenceShape`, so the
+ shrinker simply won't reduce toward one)."""
+ o_status, o_ast, _ = _safe_parse(query, rule, oracle_backend)
+ if o_status != "ok":
+ return None
+ c_status, c_ast, c_detail = _safe_parse(query, rule, candidate_backend)
+ if c_status == "reject":
+ return DivergenceShape(kind="candidate_reject", reject_signature=c_detail)
+ if c_status == "crash":
+ return None
+ 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))
diff --git a/posthog/hogql/scripts/log_corpus_diagnostic.py b/posthog/hogql/scripts/log_corpus_diagnostic.py
new file mode 100644
index 000000000000..d2dd183cf1ac
--- /dev/null
+++ b/posthog/hogql/scripts/log_corpus_diagnostic.py
@@ -0,0 +1,685 @@
+# 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.
+
+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.
+
+## 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).
+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()`.
+
+## Usage
+
+ # Default — auto-discover, download, run cpp-vs-python parity:
+ PYTHONPATH=. python posthog/hogql/scripts/log_corpus_diagnostic.py
+
+ # Iterate on a candidate parser without re-pulling the corpus:
+ PYTHONPATH=. python posthog/hogql/scripts/log_corpus_diagnostic.py \\
+ --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
+
+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
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+DEFAULT_DUMP = REPO_ROOT / "posthog" / "hogql" / "scripts" / ".local" / "hogql_log_corpus.json"
+
+
+# ---------------------------------------------------------------------------
+# Embedded SQL — keep the source of the corpus reproducible from the script
+# ---------------------------------------------------------------------------
+
+_DEFAULT_SQL_LIMIT = 10000
+
+# Stamped into our own `log_comment` so this scan is attributable in
+# `system.query_log` rather than an anonymous ad-hoc Metabase query.
+_LOG_COMMENT_TAG = '{"source": "hogql_log_corpus_diagnostic"}'
+
+# Redaction passes over the HogQL text, applied in list order (each
+# wraps the previous). Order matters: email before the hex/IPv6 passes
+# that would otherwise eat `@`-content; specific token shapes before
+# the broad `[a-fA-F0-9]{32,}` catch-all; IPv6 before IPv4. Patterns
+# are re2 source — `_build_redaction_expr` escapes them for SQL.
+_REDACTION_PASSES: list[tuple[str, str]] = [
+ (r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", "<email>"),
+ # UUID — case-insensitive (raw user HogQL needn't be lowercase).
+ (
+ 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>",
+ ),
+ # PostHog API tokens: phc_/phx_/phs_ today, any future ph?_ prefix.
+ (r"\bph[a-z]_[A-Za-z0-9]{10,}", "<ph_token>"),
+ # Credential shapes below ~never appear in HogQL text — kept as
+ # defence-in-depth against a stray paste reaching the dump.
+ (r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+", "<jwt>"),
+ (r"\b[sprk]k_(live|test)_[A-Za-z0-9]{10,}", "<stripe_key>"),
+ (r"\b(AKIA|ASIA)[A-Z0-9]{16}\b", "<aws_key>"),
+ (r"\bgh[posru]_[A-Za-z0-9]{30,}", "<gh_token>"),
+ (r"\bgithub_pat_[A-Za-z0-9_]{20,}", "<gh_token>"),
+ (r"\bxox[bpoars]-[A-Za-z0-9-]{10,}", "<slack_token>"),
+ # IPv6 — 4+ colon-separated hex groups, so `HH:MM:SS` timestamps
+ # inside toDateTime() literals don't false-positive.
+ (r"([0-9a-fA-F]{1,4}:){3,7}[0-9a-fA-F]{1,4}", "<ipv6>"),
+ # IPv4 — `(^|[^.\d])` captures the char before so a `.`-preceded
+ # match (e.g. `1.2.3.4` inside the tuple access `t.1.2.3.4`) is
+ # skipped; re2 has no lookbehind, so the captured char is re-emitted
+ # via the `\1` backreference. A digit prefix is excluded too, to
+ # keep the original `\b`-start semantics.
+ (r"(^|[^.\d])(\d{1,3}\.){3}\d{1,3}\b", r"\1<ipv4>"),
+ # Broad catch-all: 32+ contiguous hex (hashes / opaque ids).
+ (r"\b[a-fA-F0-9]{32,}\b", "<hex>"),
+]
+
+
+def _sql_str_literal(s: str) -> str:
+ """Escape a string for a ClickHouse single-quoted literal — double
+ backslashes, escape quotes. Applied to both the pattern and the
+ replacement so `_REDACTION_PASSES` can hold plain re2 source,
+ including replacements with `\\1` backreferences."""
+ return s.replace("\\", "\\\\").replace("'", "\\'")
+
+
+def _build_redaction_expr() -> str:
+ """Nest `_REDACTION_PASSES` into one `replaceRegexpAll(…)` chain over
+ the HogQL column."""
+ expr = "JSONExtractString(log_comment, 'query', 'query')"
+ for pattern, replacement in _REDACTION_PASSES:
+ expr = f"replaceRegexpAll({expr}, '{_sql_str_literal(pattern)}', '{_sql_str_literal(replacement)}')"
+ 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."""
+ return f"""
+SELECT
+ {_build_redaction_expr()} AS hogql,
+ count() AS n_occurrences
+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
+ 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)}
+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
+# ---------------------------------------------------------------------------
+
+
+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(
+ "--database-id",
+ type=int,
+ default=None,
+ help="ClickHouse Metabase DB id. Default: auto-discover via `hogli metabase:databases`, preferring OFFLINE shards.",
+ )
+ p.add_argument(
+ "--prefer-online",
+ action="store_true",
+ help="Override the default OFFLINE-preference during auto-discovery (don't do this unless you know why).",
+ )
+ p.add_argument(
+ "--input",
+ type=Path,
+ default=DEFAULT_DUMP,
+ help=f"Path to the redacted JSON dump (default: {_repo_relative(DEFAULT_DUMP)})",
+ )
+ 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 SQLs the candidate rejects (default: <dump>.failures.sql alongside the dump)",
+ )
+ p.add_argument(
+ "--limit",
+ type=int,
+ default=None,
+ help=(
+ f"Cap to first N unique queries (for fast iteration). When downloading, the SQL's "
+ f"`LIMIT` is set to N as well so the Metabase round-trip stays fast; without --limit "
+ 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")
+ 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`.
+ 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} — "
+ f"this is not a parity check; every query will trivially 'pass'."
+ )
+
+ print(f"=== HogQL log-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}")
+ print(" drop --skip-download to fetch it, or pass --input PATH to point at an existing dump")
+ return 1
+ print(f"Reusing existing dump: {args.input}")
+ else:
+ print(f"Region: {args.region}")
+ 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)
+ 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)
+ 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")
+ return 1
+
+ # 2. Load.
+ rows = _load_queries(args.input)
+ print(f"Loaded {len(rows)} unique queries from {_repo_relative(args.input)}")
+ 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 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")
+
+ 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:
+ out_path = Path(args.write_failures) if args.write_failures else args.input.with_suffix(".failures.sql")
+ _write_failures(out_path, failures)
+ print()
+ print(f"Wrote {len(failures)} failing queries to {_repo_relative(out_path)}")
+
+ return 130 if 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/parser_bench.py b/posthog/hogql/scripts/parser_bench.py
new file mode 100644
index 000000000000..d76f599a054c
--- /dev/null
+++ b/posthog/hogql/scripts/parser_bench.py
@@ -0,0 +1,357 @@
+# ruff: noqa: T201, E402, I001
+# CLI benchmark tool: print() is the report channel, and the imports
+# are deferred until after `django.setup()` so the order is intentional.
+"""Side-by-side parser performance benchmark — backend-agnostic.
+
+`--oracle` defaults to `cpp-json`. `--candidate` is REQUIRED (no
+default) — the Python backend is several orders of magnitude slower
+than cpp on most queries and would take tens of minutes per row, so
+we refuse to default to a useless target. Pass any other backend
+explicitly when one is available in a feature branch.
+
+The query corpus mirrors what the diagnostic PBT runner uses, so
+bench timings line up with parity numbers from the same workload.
+
+Run from repo root:
+
+ CANDIDATE_BACKEND=<some-fast-backend> \\
+ PYTHONPATH=. python posthog/hogql/scripts/parser_bench.py
+
+Queries the candidate can't parse are flagged and the row is skipped.
+For comparable queries the script reports per-call microseconds and a
+`oracle/candidate` ratio.
+
+The script is intentionally dependency-free beyond what's already in
+the backend environment so it can stay around as a quick perf sanity
+check as parser implementations evolve.
+"""
+
+import argparse
+import os
+import sys
+import timeit
+from typing import Any
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+from posthog.hogql.parser import clear_parse_caches, parse_expr, parse_select
+from posthog.hogql.scripts._diagnostic_common import _probe_backend
+
+DEFAULT_N = 1_000 # iterations per row; override with --n
+
+# Per-query iteration ceilings for queries cpp parses too slowly for
+# the default N. Total wall-clock per row should stay well under a
+# minute; cpp can be ~250ms+ on `pathological_deep` so 1000 iterations
+# would burn 4+ minutes before the candidate row even starts. Applied
+# as `min(override, n)` so they only ever LOWER the count — a small
+# `--n` (e.g. a 50-iteration sanity check) is never raised back up.
+N_PER_QUERY: dict[str, int] = {
+ "pathological_deep": 100,
+}
+
+EXPR_QUERIES: dict[str, str] = {
+ "int_literal": "1",
+ "arith": "1 + 2 * 3",
+ "parens": "(1 + 2) * 3",
+ "field": "events.timestamp",
+ "field_deep": "events.properties.foo.bar.baz",
+ "compare": "events.event = '$pageview'",
+ "in_clause": "event IN ('$ai_generation', '$ai_span', '$ai_trace')",
+ "not_in_clause": "event NOT IN ('$pageview', '$autocapture')",
+ "like": "url LIKE '%admin%'",
+ "call_simple": "count()",
+ "call_args": "toStartOfDay(timestamp)",
+ "call_nested": "if(event = '$pageview', 1, 0)",
+ "and_or": "event = 'a' AND (status = 'ok' OR status = 'pending')",
+ "is_null": "events.foo IS NULL",
+ "between": "value BETWEEN 1 AND 10",
+ "ternary": "x > 0 ? x : -x",
+ "alias": "count() AS total",
+ "tuple_access": "t.1",
+ "typical_where": "event = '$pageview' AND timestamp > now() AND properties.foo = 'bar'",
+ "and_chain_10": "a = 1 AND b = 2 AND c = 3 AND d = 4 AND e = 5 AND f = 6 AND g = 7 AND h = 8 AND i = 9 AND j = 10",
+ # Worst-case backtracking probe — twelve BETWEENs in an array
+ # literal, with each body chosen to absorb the separator `AND`
+ # into a non-AND-rooted subtree (lambda body, AS-alias, named-arg,
+ # ternary else). For a hand-rolled parser that resolves BETWEEN
+ # by speculating across the body's `low AND high` split this
+ # forces the slowest recovery path on every BETWEEN, and the last
+ # four rows nest an inner BETWEEN inside the outer's body via
+ # parens — so the inner is re-parsed once per outer speculation
+ # alternative, doubling speculation work.
+ #
+ # For ANTLR ALL(*) (cpp) this is just twelve linear-lookahead
+ # disambiguations — the ratio against `between` (a single trivial
+ # BETWEEN) is the speculation-overhead signal: if `nasty_backtrack`
+ # is significantly slower per BETWEEN than `between` on the
+ # candidate, speculation cost is showing up.
+ "nasty_backtrack": """[
+ x1 BETWEEN lambda a : a AND b1,
+ x2 BETWEEN col AS y2 AND c2,
+ x3 BETWEEN p := 1 AND b3,
+ x4 BETWEEN c1 ? c2 : c3 AND b4,
+ x5 BETWEEN lambda e : e AND b5,
+ x6 BETWEEN q := 2 AND b6,
+ x7 BETWEEN d AS y7 AND b7,
+ x8 BETWEEN f1 ? f2 : f3 AND b8,
+ x9 BETWEEN lambda g : (h BETWEEN col AS i AND j) AND b9,
+ x10 BETWEEN lambda k : (l BETWEEN p2 := 3 AND m) AND b10,
+ x11 BETWEEN col AS y11 AND (n BETWEEN f4 ? f5 : f6 AND o),
+ x12 BETWEEN q2 := 4 AND (r BETWEEN lambda s : s AND t)
+ ]""",
+ "mixed_and_or": """
+ (event = '$pageview' OR event = '$autocapture' OR event = '$identify')
+ AND timestamp > now()
+ AND properties.foo IN ('Chrome', 'Firefox', 'Safari')
+ AND (properties.url LIKE '%admin%' OR properties.url LIKE '%dashboard%')
+ AND NOT (properties.os = 'Linux' AND properties.device = 'Desktop')
+ """,
+}
+
+SELECT_QUERIES: dict[str, str] = {
+ "tiny": "SELECT 1",
+ "events_simple": "SELECT count() FROM events WHERE event = '$exception'",
+ "events_in_clause": "SELECT count() FROM events WHERE event IN ('$ai_generation', '$ai_span', '$ai_trace')",
+ "join_persons": """
+ SELECT e.event, e.timestamp, p.id FROM events AS e
+ JOIN persons AS p ON p.id = e.person_id
+ WHERE e.event = '$ai_generation'
+ """,
+ "subquery_with_filters": """
+ SELECT day_start, sum(c) FROM (
+ SELECT count() AS c, toStartOfDay(timestamp) AS day_start, properties.foo AS f
+ FROM events
+ WHERE event = '$pageview' AND timestamp > now() - INTERVAL 30 DAY
+ GROUP BY day_start, f
+ HAVING c > 10
+ )
+ GROUP BY day_start ORDER BY day_start LIMIT 50
+ """,
+ "trends_like_breakdown": """
+ SELECT groupArray(day_start)[1], arrayMap(x -> sum(x), counts), breakdown_value FROM (
+ SELECT day_start,
+ sum(count) OVER (PARTITION BY breakdown_value ORDER BY day_start) AS counts,
+ breakdown_value
+ FROM (
+ SELECT count(DISTINCT person_id) AS count, toStartOfDay(timestamp) AS day_start,
+ properties.$some_property AS breakdown_value FROM events
+ WHERE event = 'sign up' AND timestamp > now() - INTERVAL 7 DAY
+ GROUP BY day_start, breakdown_value
+ )
+ GROUP BY day_start, breakdown_value, counts
+ ORDER BY day_start
+ )
+ GROUP BY breakdown_value LIMIT 50
+ """,
+ "pathological_deep": """
+ WITH active_users AS (
+ SELECT distinct_id, min(timestamp) AS first_seen, max(timestamp) AS last_seen, count() AS event_count,
+ sum(if(event = '$pageview', 1, 0)) AS pageview_count,
+ sum(if(event = '$autocapture', 1, 0)) AS autocapture_count,
+ sum(if(event = 'sign up', 1, 0)) AS signup_count,
+ sum(if(event = 'product viewed', 1, 0)) AS product_count,
+ sum(if(event = 'purchase', 1, 0)) AS purchase_count
+ FROM events
+ WHERE timestamp > now() - INTERVAL 30 DAY
+ AND event IN ('$pageview', '$autocapture', 'sign up', 'product viewed', 'item added to cart',
+ 'purchase', 'subscription started', 'subscription cancelled', '$identify', '$set',
+ '$exception', '$web_vitals', '$ai_generation', '$feature_flag_called')
+ AND properties.$browser IN ('Chrome', 'Firefox', 'Safari', 'Edge', 'Opera', 'Brave')
+ AND properties.$os IN ('macOS', 'Windows', 'Linux', 'iOS', 'Android')
+ GROUP BY distinct_id
+ HAVING event_count > 3 AND pageview_count > 1
+ ),
+ breakdown_pre AS (
+ SELECT toStartOfDay(e.timestamp) AS day_start, e.properties.$some_property AS breakdown_value,
+ e.properties.$browser AS browser, e.properties.$os AS os,
+ e.properties.$device_type AS device, e.properties.$current_url AS url,
+ count(DISTINCT e.person_id) AS count,
+ sum(if(e.event = 'sign up', 1, 0)) AS signups,
+ sum(if(e.event = 'purchase', 1, 0)) AS purchases
+ FROM events AS e
+ JOIN active_users AS au ON e.distinct_id = au.distinct_id
+ LEFT JOIN persons AS p ON p.id = e.person_id
+ WHERE e.event IN ('sign up', 'purchase', '$pageview', 'subscription started')
+ AND e.timestamp > now() - INTERVAL 14 DAY
+ AND e.properties.$ai_generation IS NULL AND e.properties.$exception IS NULL
+ AND coalesce(e.properties.value, 0) > 0
+ GROUP BY day_start, breakdown_value, browser, os, device, url
+ ),
+ combined AS (
+ SELECT day_start, count, signups, purchases, breakdown_value, browser, os, device, url
+ FROM breakdown_pre
+ WHERE count > 5 AND signups > 0
+ UNION ALL
+ SELECT toStartOfDay(timestamp) AS day_start, count() AS count, 0 AS signups, 0 AS purchases,
+ properties.$some_property AS breakdown_value, properties.$browser AS browser,
+ properties.$os AS os, properties.$device_type AS device, properties.$current_url AS url
+ FROM events
+ WHERE event = '$exception' AND timestamp > now() - INTERVAL 7 DAY
+ GROUP BY day_start, breakdown_value, browser, os, device, url
+ )
+ SELECT groupArray(day_start)[1] AS first_day,
+ arraySum(arrayMap(x -> x, groupArray(count))) AS total_count,
+ arraySum(groupArray(signups)) AS total_signups,
+ arraySum(groupArray(purchases)) AS total_purchases,
+ breakdown_value, browser, os, device, count(DISTINCT url) AS distinct_urls
+ FROM combined
+ GROUP BY breakdown_value, browser, os, device
+ """,
+}
+
+
+def run(parse_fn, n: int) -> float:
+ """Per-call microseconds for `n` iterations of `parse_fn()`. The
+ caller is expected to pre-bind the query (and backend) via a
+ closure so this stays a single-arity callable. Clears the cache
+ before each invocation so we measure cold parse cost rather than
+ the cache hit path."""
+
+ def body() -> Any:
+ clear_parse_caches()
+ return parse_fn()
+
+ # Warm up to surface errors before we time.
+ body()
+ secs = timeit.timeit(body, number=n)
+ return secs / n * 1e6
+
+
+def bench(
+ label: str,
+ parse_fn,
+ queries: dict[str, str],
+ n: int,
+ oracle: str,
+ candidate: str,
+) -> int:
+ # Some rows have per-query iteration overrides (slow cpp queries
+ # would otherwise burn minutes), so make that explicit in the
+ # header — a reader correlating header `N` to a row's µs needs to
+ # know the row may have used a different N.
+ # Show only overrides that actually take effect at this `n` — with a
+ # small `--n` the `min(override, n)` ceiling collapses to `n`, so the
+ # override is a no-op and listing it would mislead.
+ overrides_in_use = {
+ name: min(N_PER_QUERY[name], n) for name in queries if name in N_PER_QUERY and N_PER_QUERY[name] < n
+ }
+ override_note = f", overrides: {overrides_in_use}" if overrides_in_use else ""
+ print(f"\n{label} (N={n} per row, oracle={oracle}, candidate={candidate}{override_note})")
+ print(f"{'query':<30} {'chars':>6} {'oracle(us)':>12} {'candidate(us)':>14} {'oracle/cand':>12}")
+ print("-" * 78)
+
+ oracle_total, cand_total, comparable = 0.0, 0.0, 0
+ for name, q in queries.items():
+ nq = min(N_PER_QUERY.get(name, n), n)
+ # Annotate the row name when its N differs from the header so a
+ # reader doesn't have to cross-reference the override map to
+ # interpret the µs value.
+ row_label = name if nq == n else f"{name} [N={nq}]"
+ try:
+ oracle_us = run(lambda q=q: parse_fn(q, backend=oracle), nq)
+ except Exception as e:
+ print(f"{row_label:<30} {len(q):>6} {'ERROR':>12} {'-':>14} {'-':>12} ({oracle}: {e})")
+ continue
+ try:
+ cand_us = run(lambda q=q: parse_fn(q, backend=candidate), nq)
+ except Exception as e:
+ print(f"{row_label:<30} {len(q):>6} {oracle_us:>12.3f} {'(skip)':>14} {'-':>12} ({candidate}: {e})")
+ continue
+ ratio = oracle_us / cand_us if cand_us > 0 else float("nan")
+ print(f"{row_label:<30} {len(q):>6} {oracle_us:>12.3f} {cand_us:>14.3f} {ratio:>11.1f}x")
+ oracle_total += oracle_us
+ cand_total += cand_us
+ comparable += 1
+
+ print("-" * 78)
+ if comparable:
+ # The time columns ARE arithmetic means of per-row times.
+ # The ratio column is the ratio of those means
+ # (equivalently `sum(oracle) / sum(cand)`), which weights each
+ # row by absolute time spent — the right metric for an
+ # "overall speedup" reading. Note this is NOT the arithmetic
+ # mean of per-row ratios; on a corpus with vastly different
+ # absolute times, that mean would over-weight cheap rows.
+ overall = oracle_total / cand_total if cand_total > 0 else float("nan")
+ print(
+ f"{'mean (per-call µs)':<30} {'':>6} {oracle_total / comparable:>12.3f} "
+ f"{cand_total / comparable:>14.3f} {overall:>11.1f}x "
+ f"(ratio sum-weighted; {comparable}/{len(queries)} comparable)"
+ )
+ return comparable
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument(
+ "--oracle",
+ default=os.environ.get("ORACLE_BACKEND", "cpp-json"),
+ help="Source-of-truth backend (default: cpp-json)",
+ )
+ parser.add_argument(
+ "--candidate",
+ default=os.environ.get("CANDIDATE_BACKEND"),
+ help=(
+ "Backend under test (no default). The Python backend is an "
+ "ANTLR-generated visitor and is several orders of magnitude "
+ "slower than cpp on most queries — the bench would take tens "
+ "of minutes per row — so this script intentionally has no "
+ "default. Set CANDIDATE_BACKEND or pass --candidate to any "
+ "other backend available in your environment."
+ ),
+ )
+ parser.add_argument(
+ "--n",
+ type=int,
+ default=DEFAULT_N,
+ help=(
+ f"Iterations per row (default: {DEFAULT_N}). Lower it for a quick "
+ f"sanity check during grinding, e.g. --n 50. Per-query ceilings in "
+ f"N_PER_QUERY still apply as min(ceiling, --n)."
+ ),
+ )
+ args = parser.parse_args()
+ if args.n < 1:
+ print("ERROR: --n must be at least 1")
+ return 2
+ if not args.candidate:
+ print(
+ "ERROR: --candidate is required (no default). The Python "
+ "backend is too slow to be a useful bench target; pass any "
+ "other backend available in your environment."
+ )
+ return 2
+
+ # Sanity-probe both rules on both backends so a typo, a missing
+ # backend, or a backend with partial rule coverage (e.g. expr only,
+ # no select) fails immediately with a readable error rather than
+ # tripping the per-row `except` on every query and silently
+ # reporting zero comparable rows. We bench parse_expr AND
+ # parse_select below, so probing only one rule would miss the
+ # partial-implementation case entirely.
+ for rule in ("expr", "select"):
+ for label, backend in (("oracle", args.oracle), ("candidate", args.candidate)):
+ err = _probe_backend(rule, backend)
+ if err is not None:
+ print(f"ERROR: {label} backend {backend!r} unavailable for rule {rule!r}: {err}")
+ return 2
+
+ comparable = 0
+ comparable += bench("parse_expr", parse_expr, EXPR_QUERIES, args.n, args.oracle, args.candidate)
+ comparable += bench("parse_select", parse_select, SELECT_QUERIES, args.n, args.oracle, args.candidate)
+ if comparable == 0:
+ print(
+ f"\nERROR: zero comparable rows — candidate {args.candidate!r} "
+ f"failed every query. Backend is reachable (probe passed) but "
+ f"can't parse any of the corpus; this is a regression, not a "
+ f"config issue."
+ )
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/posthog/hogql/scripts/pbt_corpus.py b/posthog/hogql/scripts/pbt_corpus.py
new file mode 100644
index 000000000000..d1f2110bafc6
--- /dev/null
+++ b/posthog/hogql/scripts/pbt_corpus.py
@@ -0,0 +1,260 @@
+"""Regression corpus tool for parser-parity divergences.
+
+Companion to `pbt_diagnostic.py`. Two subcommands:
+
+ extract Read a divergences JSONL (produced by
+ `pbt_diagnostic.py --write-divergences`) and write a
+ deduplicated corpus — one entry per
+ (kind, oracle_root, candidate_root, terminal_diff_or_signature)
+ bucket. The first occurrence of each bucket wins; we trust
+ that the shrinker has already minimised it.
+
+ check Read a corpus and verify each entry still triggers its
+ recorded divergence shape against the configured backends.
+ Useful before/after a fix: any entry whose shape no longer
+ matches has either been FIXED (good — remove from corpus)
+ or REGRESSED into a different shape (bad — investigate).
+
+Backend-agnostic: the corpus records the (oracle, candidate) pair the
+divergence was found against. `check` re-runs against the same pair
+unless overridden via `--oracle` / `--candidate`.
+
+Typical workflow:
+
+ # 1. Grind the PBT, persist divergences, shrink them.
+ python posthog/hogql/scripts/pbt_diagnostic.py --n 5000 \\
+ --shrink-failures --write-divergences /tmp/divergences.jsonl
+
+ # 2. Extract a deduplicated regression corpus.
+ python posthog/hogql/scripts/pbt_corpus.py extract \\
+ --from /tmp/divergences.jsonl \\
+ --to /tmp/pbt_regression_corpus.jsonl
+
+ # 3. After making a fix, replay the corpus to see what changed.
+ python posthog/hogql/scripts/pbt_corpus.py check \\
+ --corpus /tmp/pbt_regression_corpus.jsonl
+"""
+
+# ruff: noqa: T201 (CLI script — print is the report channel)
+# ruff: noqa: E402 (django.setup() ordering)
+
+from __future__ import annotations
+
+import os
+import sys
+import json
+import argparse
+from collections import Counter
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+from posthog.hogql.scripts._diagnostic_common import (
+ DivergenceShape,
+ _ast_mismatch_shape,
+ _probe_backend,
+ _safe_parse,
+ _shape_for,
+)
+
+
+def _shape_from_divergence(rec: dict) -> DivergenceShape:
+ """Build the structural shape recorded in a divergences-JSONL row.
+ Same canonical shape `_shape_for` produces, so two examples of the
+ same divergence (with different leaf values) compare equal under
+ this key."""
+ if rec["kind"] == "ast_mismatch":
+ return _ast_mismatch_shape(
+ (rec.get("oracle_root", ""), rec.get("candidate_root", "")),
+ rec.get("diff_path", []),
+ )
+ return DivergenceShape(kind="candidate_reject", reject_signature=rec.get("reject_signature"))
+
+
+def _shape_from_corpus_entry(entry: dict) -> DivergenceShape:
+ """Reconstruct the expected shape from a corpus-JSONL row produced
+ by `cmd_extract`. Mirrors what `_shape_from_divergence` would
+ produce on the original raw record."""
+ if entry["kind"] == "ast_mismatch":
+ types = None
+ if "expected_terminal_oracle" in entry:
+ types = (entry["expected_terminal_oracle"], entry["expected_terminal_candidate"])
+ return DivergenceShape(
+ kind="ast_mismatch",
+ root_pair=(entry["expected_oracle_root"], entry["expected_candidate_root"]),
+ terminal_kind=entry.get("expected_terminal_kind"),
+ terminal_types=types,
+ )
+ return DivergenceShape(kind="candidate_reject", reject_signature=entry.get("expected_reject_signature"))
+
+
+def cmd_extract(args: argparse.Namespace) -> int:
+ # `DivergenceShape` is a frozen dataclass so it's hashable on its
+ # own fields — use the shape directly as the dedup key.
+ seen: dict[DivergenceShape, dict] = {}
+ skipped_no_shrunk = 0
+ with open(args.src) as f:
+ for line in f:
+ rec = json.loads(line)
+ if not args.keep_unshrunken and "query_shrunk" not in rec:
+ skipped_no_shrunk += 1
+ continue
+ shape = _shape_from_divergence(rec)
+ if shape in seen:
+ continue
+ # Prefer the shrunken query if available.
+ entry = {
+ "kind": rec["kind"],
+ "rule": rec["rule"],
+ "oracle": rec["oracle"],
+ "candidate": rec["candidate"],
+ "query": rec.get("query_shrunk", rec["query"]),
+ }
+ if shape.kind == "ast_mismatch":
+ entry["expected_oracle_root"] = shape.root_pair[0] if shape.root_pair else ""
+ entry["expected_candidate_root"] = shape.root_pair[1] if shape.root_pair else ""
+ if shape.terminal_kind:
+ entry["expected_terminal_kind"] = shape.terminal_kind
+ if shape.terminal_types:
+ entry["expected_terminal_oracle"] = shape.terminal_types[0]
+ entry["expected_terminal_candidate"] = shape.terminal_types[1]
+ else:
+ entry["expected_reject_signature"] = shape.reject_signature
+ seen[shape] = entry
+
+ with open(args.dst, "w") as f:
+ for entry in seen.values():
+ f.write(json.dumps(entry) + "\n")
+ print(f"Wrote {len(seen)} deduplicated entries to {args.dst}")
+ if skipped_no_shrunk:
+ print(
+ f" ({skipped_no_shrunk} input records skipped because they have no "
+ f"`query_shrunk` field — re-run the diagnostic with --shrink-failures, "
+ f"or pass --keep-unshrunken to extract them anyway.)"
+ )
+ return 0
+
+
+def cmd_check(args: argparse.Namespace) -> int:
+ """Replay the corpus, classifying each entry as still-diverges /
+ fixed / regressed / oracle-rejects. Exit 0 iff there are neither
+ regressions nor oracle-reject entries (an oracle that now rejects
+ a recorded query means the comparison baseline has shifted, so a
+ bare "0 regressions" verdict can no longer be trusted)."""
+ counts: Counter[str] = Counter()
+ sample: dict[str, list[str]] = {"fixed": [], "regressed": [], "still_diverges": [], "oracle_rejects": []}
+ # Sanity-probe each (oracle, candidate, rule) tuple we'll use the
+ # first time we see it. `_shape_for` -> `_safe_parse` swallows the
+ # `KeyError` raised by an invalid backend name silently, which
+ # would classify every corpus entry as "fixed" with no error.
+ # Probing lazily inside the loop catches both `--oracle` /
+ # `--candidate` typos AND corpus files referring to backends that
+ # were removed since the corpus was generated. The `rule` is part
+ # of the key because a backend with partial coverage (e.g. expr
+ # only, no select) needs to be caught for EACH rule the corpus
+ # uses — otherwise the first entry's rule probes successfully and
+ # the unprobed rule's entries all silently misclassify.
+ probed: set[tuple[str, str, str]] = set()
+ with open(args.corpus) as f:
+ for line in f:
+ entry = json.loads(line)
+ oracle = args.oracle or entry["oracle"]
+ candidate = args.candidate or entry["candidate"]
+ rule = entry["rule"]
+ if (oracle, candidate, rule) not in probed:
+ for label, backend in (("oracle", oracle), ("candidate", candidate)):
+ err = _probe_backend(rule, backend)
+ if err is not None:
+ print(f"ERROR: {label} backend {backend!r} unavailable for rule {rule!r}: {err}")
+ 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)
+ if o_status != "ok":
+ counts["oracle_rejects"] += 1
+ if len(sample["oracle_rejects"]) < args.max_samples:
+ sample["oracle_rejects"].append(entry["query"])
+ continue
+ shape = _shape_for(entry["query"], entry["rule"], oracle, candidate)
+ if shape is None:
+ counts["fixed"] += 1
+ if len(sample["fixed"]) < args.max_samples:
+ sample["fixed"].append(entry["query"])
+ continue
+ expected = _shape_from_corpus_entry(entry)
+ if shape == expected:
+ counts["still_diverges"] += 1
+ if len(sample["still_diverges"]) < args.max_samples:
+ sample["still_diverges"].append(entry["query"])
+ else:
+ counts["regressed"] += 1
+ if len(sample["regressed"]) < args.max_samples:
+ sample["regressed"].append(
+ f"{entry['query']!r}\n expected: {expected}\n got: {shape}"
+ )
+
+ print(f"=== Corpus check ({sum(counts.values())} entries) ===")
+ for k, v in counts.most_common():
+ print(f" {k:20s} {v}")
+ for label in ("fixed", "regressed", "still_diverges", "oracle_rejects"):
+ if sample[label]:
+ print()
+ print(f"--- {label} (showing up to {args.max_samples}) ---")
+ for q in sample[label]:
+ print(f" {q}")
+ if counts["oracle_rejects"]:
+ print(
+ f"\nWARNING: the oracle now rejects {counts['oracle_rejects']} corpus "
+ f"{'entry' if counts['oracle_rejects'] == 1 else 'entries'} it previously "
+ f"accepted — the comparison baseline has shifted. Regenerate the corpus "
+ f"against the current oracle before trusting the fixed/regressed counts."
+ )
+ return 0 if counts["regressed"] == 0 and counts["oracle_rejects"] == 0 else 1
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = parser.add_subparsers(dest="cmd", required=True)
+
+ p_extract = sub.add_parser("extract", help="Dedup divergences JSONL into a corpus")
+ p_extract.add_argument("--from", dest="src", required=True, metavar="JSONL")
+ p_extract.add_argument("--to", dest="dst", required=True, metavar="JSONL")
+ p_extract.add_argument(
+ "--keep-unshrunken",
+ action="store_true",
+ help="Include records that lack a `query_shrunk` field (default: skip them, since unshrunken queries make for bad regression tests)",
+ )
+ p_extract.set_defaults(func=cmd_extract)
+
+ p_check = sub.add_parser("check", help="Replay a corpus and classify outcomes")
+ p_check.add_argument("--corpus", required=True, metavar="JSONL")
+ p_check.add_argument(
+ "--oracle",
+ default=None,
+ help="Override the oracle backend (default: use what each entry recorded)",
+ )
+ p_check.add_argument(
+ "--candidate",
+ default=None,
+ help="Override the candidate backend (default: use what each entry recorded)",
+ )
+ p_check.add_argument("--max-samples", type=int, default=5)
+ p_check.set_defaults(func=cmd_check)
+
+ args = parser.parse_args()
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/posthog/hogql/scripts/pbt_diagnostic.py b/posthog/hogql/scripts/pbt_diagnostic.py
new file mode 100644
index 000000000000..c74ae94cd483
--- /dev/null
+++ b/posthog/hogql/scripts/pbt_diagnostic.py
@@ -0,0 +1,447 @@
+"""Diagnostic PBT runner: oracle backend vs candidate backend.
+
+Reuses the strategies from `test_parser_grammar_pbt.py` (the
+auto-generated grammar PBT introduced in PR #58627) but runs as an
+ad-hoc CLI rather than a pytest collection. Backend-agnostic:
+defaults to `cpp-json` vs `python` (the two backends shipped in
+master); point `--candidate` at any other backend in a feature
+branch that adds one.
+
+Distinct from the pytest PBT in five ways:
+
+1. **AST node-type pair categorization.** Each ast_mismatch is
+ bucketed by `(oracle.root_node, candidate.root_node)` so the
+ dominant divergence classes surface immediately — no manual
+ eyeballing of 200-line AST dumps.
+2. **Diff-only AST output.** When printing a sample mismatch, walk
+ both ASTs together and print only the path from root to the first
+ differing node.
+3. **Auto-shrinker (`--shrink-failures`).** For each ast_mismatch
+ and reject, run a delete-one-token reducer that keeps the smallest
+ variant which still triggers the same divergence shape. Drops
+ typical PBT failures from 200+ chars to <50.
+4. **Optional JSONL persistence (`--write-divergences PATH`).** Drop
+ one JSON line per failing example for cross-run analysis or
+ regression-corpus extraction.
+5. **Reject categorization.** Group `candidate_reject` queries by the
+ error message + leading-token signature so recurring shapes
+ surface even though there's no AST to diff against.
+6. **Crash bucketing.** A query that makes a backend raise a non-HogQL
+ exception (`RecursionError`, a half-built parser's `RuntimeError`,
+ …) is bucketed as `candidate_crash` / `oracle_crash` and the grind
+ continues — surfacing the crash rather than aborting on it.
+
+The shared parse / AST-diff / divergence-shape vocabulary lives in
+`_diagnostic_common.py` alongside this script.
+
+Typical usage:
+
+ # Default: cpp-json vs python (works in master out of the box)
+ PYTHONPATH=. python posthog/hogql/scripts/pbt_diagnostic.py --n 5000
+
+ # With auto-shrinking on every failure
+ PYTHONPATH=. python posthog/hogql/scripts/pbt_diagnostic.py \\
+ --n 5000 --shrink-failures
+
+ # Persist for later analysis / corpus extraction
+ PYTHONPATH=. python posthog/hogql/scripts/pbt_diagnostic.py \\
+ --write-divergences /tmp/divergences.jsonl --shrink-failures
+"""
+
+# ruff: noqa: T201 (this is a CLI script — print is the output channel)
+# ruff: noqa: E402 (django.setup() must run between import django and the
+# project-app imports below)
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+import json
+import argparse
+import traceback
+from collections import Counter
+from typing import Any
+
+import django
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+django.setup()
+
+from hypothesis import given, settings
+
+from posthog.hogql.scripts._diagnostic_common import (
+ DivergenceShape,
+ _ast_mismatch_shape,
+ _diff_path,
+ _format_diff_path,
+ _node_type,
+ _probe_backend,
+ _safe_parse,
+ _shape_for,
+)
+from posthog.hogql.test._generated_grammar_strategies import expr_strategy, select_strategy
+from posthog.hogql.test.test_parser_grammar_pbt import _PBT_SETTINGS, _apply_jiggle
+
+# ---------------------------------------------------------------------------
+# Auto-shrinker
+# ---------------------------------------------------------------------------
+#
+# Hypothesis has its own shrinker but we're running queries that already
+# escaped from a Hypothesis trial — by the time the diagnostic sees them,
+# Hypothesis has moved on. We re-run our own delete-one-token reducer so
+# each printed failure is a small repro the human can paste into a unit
+# test.
+
+
+_TOKEN_RE = re.compile(r"\s+|[^\s]+")
+
+
+def _tokenize_for_shrink(query: str) -> list[str]:
+ """Split into shrinker units. We use whitespace-or-non-whitespace
+ runs so paren matching is preserved (a token like `(` or `)` is a
+ single shrinker unit). The original whitespace is retained so we
+ can re-join faithfully."""
+ return [m.group(0) for m in _TOKEN_RE.finditer(query)]
+
+
+def _shrink_query(
+ query: str,
+ rule: str,
+ oracle_backend: str,
+ candidate_backend: str,
+ target_shape: DivergenceShape,
+ max_passes: int = 5,
+) -> str:
+ """Greedy delete-one-token shrinker. Each pass walks every token
+ and drops it (and its trailing whitespace) if the resulting query
+ still triggers the same divergence shape. Stops when a pass
+ removes nothing or after `max_passes`. Linear in
+ tokens × passes — fine for ~50-300-token PBT queries."""
+ current = query
+ for _ in range(max_passes):
+ tokens = _tokenize_for_shrink(current)
+ # Try delete each non-whitespace token (and any trailing
+ # whitespace token) in turn.
+ improved = False
+ i = 0
+ while i < len(tokens):
+ if tokens[i].isspace():
+ i += 1
+ continue
+ # Build a candidate with tokens[i] removed (plus any
+ # immediately-following whitespace token).
+ drop_to = i + 1
+ if drop_to < len(tokens) and tokens[drop_to].isspace():
+ drop_to += 1
+ candidate = "".join(tokens[:i] + tokens[drop_to:])
+ if not candidate.strip():
+ i += 1
+ continue
+ shape = _shape_for(candidate, rule, oracle_backend, candidate_backend)
+ if shape == target_shape:
+ current = candidate
+ tokens = _tokenize_for_shrink(current)
+ improved = True
+ # Don't advance i — the next token slid into this slot.
+ continue
+ i += 1
+ if not improved:
+ break
+ return current
+
+
+# ---------------------------------------------------------------------------
+# Output helpers
+# ---------------------------------------------------------------------------
+
+
+def _print_failure_sample(
+ query: str,
+ shrunk: str | None,
+ rule: str,
+ oracle: str,
+ candidate: str,
+ *,
+ diff_steps: list | None = None,
+) -> None:
+ """Print one sample failure. The caller pre-computes the shrunken
+ form (None if shrinking is off) — both this print path and the
+ JSONL writer pull from the same pre-shrunk string so they never
+ disagree on the minimal repro. For ast_mismatch samples, pass
+ `diff_steps` so the diff path renders against the original; when
+ a shrunk query is present, re-parse it for a fresh diff path."""
+ if shrunk is not None and shrunk != query:
+ print(f" query (shrunk {len(query)} -> {len(shrunk)}): {shrunk!r}")
+ if diff_steps is not None:
+ _, o_s, _ = _safe_parse(shrunk, rule, oracle)
+ _, c_s, _ = _safe_parse(shrunk, rule, candidate)
+ print(_format_diff_path(_diff_path(o_s, c_s)))
+ else:
+ print(f" query: {query!r}")
+ if diff_steps is not None:
+ print(_format_diff_path(diff_steps))
+
+
+# ---------------------------------------------------------------------------
+# Main runner
+# ---------------------------------------------------------------------------
+
+
+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("--jiggle", action="store_true")
+ parser.add_argument(
+ "--oracle",
+ default=os.environ.get("ORACLE_BACKEND", "cpp-json"),
+ help="Source-of-truth backend (default: cpp-json)",
+ )
+ parser.add_argument(
+ "--candidate",
+ default=os.environ.get("CANDIDATE_BACKEND", "python"),
+ help="Backend under test (default: python; override in feature branches that add a third backend)",
+ )
+ parser.add_argument(
+ "--max-mismatch-samples",
+ type=int,
+ default=3,
+ help="Per category, max sample mismatches to print (default: 3)",
+ )
+ parser.add_argument(
+ "--print-rejects",
+ action="store_true",
+ help="Also print sample candidate-rejected queries (oracle accepted)",
+ )
+ parser.add_argument(
+ "--shrink-failures",
+ action="store_true",
+ help="Run an auto-shrinker on each printed failure to produce a minimal repro",
+ )
+ parser.add_argument(
+ "--write-divergences",
+ metavar="PATH",
+ default=None,
+ help="Write JSONL with one entry per failing example (query + diff path)",
+ )
+ args = parser.parse_args()
+ oracle = args.oracle
+ candidate = args.candidate
+
+ # Sanity-probe the backends so we fail fast with a clear error
+ # rather than mid-run with cryptic Hypothesis output.
+ for label, backend in (("oracle", oracle), ("candidate", candidate)):
+ err = _probe_backend(args.rule, backend)
+ if err is not None:
+ print(f"ERROR: {label} backend {backend!r} unavailable: {err}")
+ return 1
+
+ counts: Counter[str] = Counter()
+ # Buckets store `(query, shrunk_or_none, steps_for_mismatch)`. We
+ # shrink ONCE per failure (in `run()` below) and reuse the result
+ # both for the JSONL writer and the summary print loop — otherwise
+ # the two paths would shrink independently and could land on
+ # different minima of the same divergence (greedy deletion picks
+ # the first viable reduction at each step, so order matters), and
+ # a user cross-referencing the two outputs would see two
+ # different "minimal" repros for the same bug.
+ mismatch_buckets: dict[tuple[str, str], list[tuple[str, str | None, list]]] = {}
+ reject_buckets: dict[str, list[tuple[str, str | None]]] = {}
+ # A candidate that raises a non-HogQL exception (RecursionError, a
+ # half-built backend's RuntimeError, …) is a finding in its own
+ # right — `_safe_parse` catches it so one crashing query can't
+ # 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()
+ strategy = base_strategy.flatmap(_apply_jiggle) if args.jiggle else base_strategy
+
+ # Stream JSONL during the run rather than collecting everything in
+ # memory. Opened in the try-block below so the strategy
+ # construction and decorator application above have no chance to
+ # leak the handle.
+ jsonl_file: Any = None
+ jsonl_count = 0
+
+ def write_record(rec: dict, shrunk: str | None) -> None:
+ nonlocal jsonl_count
+ if jsonl_file is None:
+ return
+ if shrunk is not None:
+ rec["query_shrunk"] = shrunk
+ if "diff_path" in rec:
+ rec["diff_path"] = [list(s) if isinstance(s, tuple) else s for s in rec["diff_path"]]
+ jsonl_file.write(json.dumps(rec) + "\n")
+ jsonl_count += 1
+
+ # Reuse the pytest PBT's shared settings (deadline=None, slow /
+ # filter-too-much suppression) and only override `max_examples`
+ # from the CLI flag. The pytest PBT deliberately leaves
+ # `data_too_large` unsuppressed — same signal here.
+ @given(query=strategy)
+ @settings(parent=_PBT_SETTINGS, max_examples=args.n)
+ def run(query: str) -> None:
+ counts["total"] += 1
+
+ o_status, o_ast, _ = _safe_parse(query, args.rule, oracle)
+ if o_status == "reject":
+ counts["oracle_reject"] += 1
+ 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
+ return
+
+ c_status, c_ast, c_detail = _safe_parse(query, args.rule, candidate)
+ if c_status == "reject":
+ counts["candidate_reject"] += 1
+ sig = c_detail or "<no message>"
+ shape = DivergenceShape(kind="candidate_reject", reject_signature=sig)
+ shrunk = _shrink_query(query, args.rule, oracle, candidate, shape) if args.shrink_failures else None
+ reject_buckets.setdefault(sig, []).append((query, shrunk))
+ write_record(
+ {
+ "kind": "candidate_reject",
+ "rule": args.rule,
+ "oracle": oracle,
+ "candidate": candidate,
+ "query": query,
+ "reject_signature": sig,
+ },
+ shrunk,
+ )
+ return
+ if c_status == "crash":
+ # Not shrunk: a crash isn't a stable `DivergenceShape`, so
+ # `_shrink_query` can't reduce toward it. Recorded full.
+ counts["candidate_crash"] += 1
+ sig = c_detail or "<no message>"
+ crash_buckets.setdefault(sig, []).append(query)
+ write_record(
+ {
+ "kind": "candidate_crash",
+ "rule": args.rule,
+ "oracle": oracle,
+ "candidate": candidate,
+ "query": query,
+ "crash_signature": sig,
+ },
+ None,
+ )
+ return
+
+ if o_ast == c_ast:
+ counts["match"] += 1
+ return
+
+ counts["ast_mismatch"] += 1
+ bucket = (_node_type(o_ast), _node_type(c_ast))
+ steps = _diff_path(o_ast, c_ast)
+ shape = _ast_mismatch_shape(bucket, steps)
+ shrunk = _shrink_query(query, args.rule, oracle, candidate, shape) if args.shrink_failures else None
+ mismatch_buckets.setdefault(bucket, []).append((query, shrunk, steps))
+ write_record(
+ {
+ "kind": "ast_mismatch",
+ "rule": args.rule,
+ "oracle": oracle,
+ "candidate": candidate,
+ "query": query,
+ "oracle_root": bucket[0],
+ "candidate_root": bucket[1],
+ "diff_path": steps,
+ },
+ shrunk,
+ )
+
+ # `run()` can fail outright — a Hypothesis `FailedHealthCheck`, a
+ # backend import error surfacing mid-run, an unopenable
+ # `--write-divergences` path. We still print whatever summary we
+ # have, but track the failure so the exit code reflects it: tooling
+ # that invokes the diagnostic non-interactively must not read a
+ # crashed run as success.
+ run_ok = True
+ try:
+ if args.write_divergences:
+ jsonl_file = open(args.write_divergences, "w") # noqa: SIM115 — see finally
+ run()
+ except Exception:
+ traceback.print_exc()
+ run_ok = False
+ finally:
+ if jsonl_file is not None:
+ jsonl_file.close()
+
+ # ---- Summary ----------------------------------------------------------
+ print()
+ print(
+ f"=== PBT run: rule={args.rule} oracle={oracle} candidate={candidate} "
+ f"jiggle={args.jiggle} max_examples={args.n} ==="
+ )
+ for k, v in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
+ print(f" {k:32s} {v}")
+
+ # ---- ast_mismatch categorization + samples ----------------------------
+ if mismatch_buckets:
+ total = sum(len(v) for v in mismatch_buckets.values())
+ print()
+ print(f"=== ast_mismatch categories ({total} total) ===")
+ sorted_mismatch_buckets = sorted(mismatch_buckets.items(), key=lambda kv: -len(kv[1]))
+ for (o_t, c_t), examples in sorted_mismatch_buckets:
+ print(f" {o_t} vs {c_t}: {len(examples)}")
+ print()
+ print(f"=== Sample mismatches (up to {args.max_mismatch_samples} per category) ===")
+ for (o_t, c_t), examples in sorted_mismatch_buckets:
+ print(f"\n--- {o_t} vs {c_t} ({len(examples)} total) ---")
+ for query, shrunk, steps in examples[: args.max_mismatch_samples]:
+ _print_failure_sample(query, shrunk, args.rule, oracle, candidate, diff_steps=steps)
+
+ # ---- candidate_reject categorization + samples ------------------------
+ # The category summary always prints (parity with the ast_mismatch
+ # category table); per-query samples stay gated behind `--print-rejects`
+ # to keep the default output short.
+ if reject_buckets:
+ total = sum(len(v) for v in reject_buckets.values())
+ print()
+ print(f"=== candidate_reject categories ({total} total) ===")
+ sorted_reject_buckets = sorted(reject_buckets.items(), key=lambda kv: -len(kv[1]))
+ for sig, queries in sorted_reject_buckets:
+ print(f" [{len(queries):3d}] {sig}")
+ if args.print_rejects:
+ print()
+ print(f"=== Sample candidate_rejects (up to {args.max_mismatch_samples} per category) ===")
+ for sig, queries in sorted_reject_buckets:
+ print(f"\n--- {sig} ({len(queries)} total) ---")
+ for query, shrunk in queries[: args.max_mismatch_samples]:
+ _print_failure_sample(query, shrunk, args.rule, oracle, candidate)
+
+ # ---- candidate_crash categorization + samples -------------------------
+ if crash_buckets:
+ total = sum(len(v) for v in crash_buckets.values())
+ print()
+ print(f"=== candidate_crash categories ({total} total — non-HogQL exceptions) ===")
+ sorted_crash_buckets = sorted(crash_buckets.items(), key=lambda kv: -len(kv[1]))
+ # Distinct loop names from the reject block above: crash buckets hold
+ # bare query strings, reject buckets hold (query, shrunk) pairs.
+ for crash_sig, crash_queries in sorted_crash_buckets:
+ print(f" [{len(crash_queries):3d}] {crash_sig}")
+ if args.print_rejects:
+ print()
+ print(f"=== Sample candidate_crashes (up to {args.max_mismatch_samples} per category) ===")
+ for crash_sig, crash_queries in sorted_crash_buckets:
+ print(f"\n--- {crash_sig} ({len(crash_queries)} total) ---")
+ for crash_query in crash_queries[: args.max_mismatch_samples]:
+ print(f" query: {crash_query!r}")
+
+ if args.write_divergences:
+ print()
+ print(f"=== Wrote {jsonl_count} divergence records to {args.write_divergences} ===")
+
+ return 0 if run_ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())