:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogql): PBT example DB + AST-shape target() + event() (#64005)
Robbiec074d27ecaaa
diff --git a/posthog/hogql/printer/test/test_printer_pbt.py b/posthog/hogql/printer/test/test_printer_pbt.pyindex c748dc3968b3..1fc68724a2ac 100644--- a/posthog/hogql/printer/test/test_printer_pbt.py+++ b/posthog/hogql/printer/test/test_printer_pbt.py@@ -22,6 +22,7 @@ from posthog.hogql.escape_sql import (escape_postgres_identifier,)from posthog.hogql.parse_string import parse_string_literal_text+from posthog.hogql.test._pbt_corpus_db import shared_corpus_database# These tests are too slow for CI. Run manually with:# RUN_PBT=1 pytest posthog/hogql/printer/test/test_printer_pbt.py@@ -30,6 +31,13 @@ pytestmark = pytest.mark.skipif(reason="PBT tests are slow; set RUN_PBT=1 to run",)+# Replay the per-developer local seed read-only + write new examples to the+# default `.hypothesis/examples` (see _pbt_corpus_db). Applied to the+# substantive roundtrip properties below via `parent=_BASE`; the trivial+# single-shape property checks are left on the default Hypothesis cache — a+# shared seed adds nothing there.+_BASE = settings(database=shared_corpus_database())+# ---------------------------------------------------------------------------# Reusable strategies# ---------------------------------------------------------------------------@@ -104,7 +112,7 @@ class TestStringEscapingRoundTrip:@pytest.mark.parametrize("label,escape_fn", _STRING_ESCAPE_FUNCTIONS)@given(data=st.data())- @settings(max_examples=1000)+ @settings(parent=_BASE, max_examples=1000)def test_string_roundtrip(self, label: str, escape_fn: Callable, data: st.DataObject) -> None:s = data.draw(_roundtrip_safe_text)escaped = escape_fn(s)@@ -149,7 +157,7 @@ class TestBacktickIdentifierRoundTrip:@pytest.mark.parametrize("label,escape_fn", _BACKTICK_IDENTIFIER_FUNCTIONS)@given(data=st.data())- @settings(max_examples=1000)+ @settings(parent=_BASE, max_examples=1000)def test_roundtrip_through_parse_string_literal(self, label: str, escape_fn: Callable, data: st.DataObject) -> None:s = data.draw(_roundtrip_safe_identifier_text)escaped = escape_fn(s)@@ -184,7 +192,7 @@ class TestPostgresIdentifier:"""@given(s=st.text(min_size=1, max_size=63))- @settings(max_examples=1000)+ @settings(parent=_BASE, max_examples=1000)def test_roundtrip(self, s: str) -> None:escaped = escape_postgres_identifier(s)if escaped.startswith('"'):diff --git a/posthog/hogql/scripts/_diagnostic_common.py b/posthog/hogql/scripts/_diagnostic_common.pyindex 647a108e66a6..78ab3bb64385 100644--- a/posthog/hogql/scripts/_diagnostic_common.py+++ b/posthog/hogql/scripts/_diagnostic_common.py@@ -35,7 +35,7 @@ import tracebackimport subprocessimport dataclassesfrom collections import Counter-from collections.abc import Callable+from collections.abc import Callable, Iteratorfrom pathlib import Pathfrom typing import Any, NoReturn@@ -132,6 +132,73 @@ def _format_diff_path(steps: list) -> str:return f" {label}{field}\n oracle: {o_repr[:200]}\n candidate: {c_repr[:200]}"+# ---------------------------------------------------------------------------+# AST shape walkers (k-paths and depth)+# ---------------------------------------------------------------------------+#+# Cheap, in-process traversals that fold an AST into a coverage-flavoured signal+# without any native instrumentation. Used as `target()` observations and+# `event()` labels in the PBT layer; safe to call on every example because both+# walkers are depth-bounded and run in O(nodes).+++def _iter_child_nodes(value: Any) -> Iterator[Any]:+ """Yield the AST dataclass nodes one level below `value`, descending+ through intervening lists / tuples / dicts (which hold child nodes in the+ HogQL AST) but stopping at scalars. A dataclass *type* (as opposed to an+ instance) is a scalar for our purposes."""+ if dataclasses.is_dataclass(value) and not isinstance(value, type):+ yield value+ return+ if isinstance(value, list | tuple):+ for item in value:+ yield from _iter_child_nodes(item)+ elif isinstance(value, dict):+ for item in value.values():+ yield from _iter_child_nodes(item)+++def ast_kpaths(root: Any, k: int = 2, *, max_depth: int = 64) -> set[tuple[str, ...]]:+ """All node-type k-paths in `root`: the set of length-`k` windows of AST+ node-type names along each root->descendant path. `k=1` is the set of node+ types present, `k=2` every parent->child edge, `k=3` every+ grandparent->parent->child triple. Depth-bounded so a pathological tree+ can't blow the stack."""+ out: set[tuple[str, ...]] = set()++ def walk(node: Any, chain: tuple[str, ...]) -> None:+ chain = (*chain, _node_type(node))+ if len(chain) >= k:+ out.add(chain[-k:])+ if len(chain) >= max_depth:+ return+ for _, value in _node_fields(node):+ for child in _iter_child_nodes(value):+ walk(child, chain)++ walk(root, ())+ return out+++def ast_depth(root: Any, *, max_depth: int = 256) -> int:+ """Maximum AST node nesting depth (root = depth 1). Capped so a pathological+ tree returns the cap rather than recursing without bound."""+ best = 0++ def walk(node: Any, d: int) -> None:+ nonlocal best+ if d > best:+ best = d+ if d >= max_depth:+ return+ for _, value in _node_fields(node):+ for child in _iter_child_nodes(value):+ walk(child, d + 1)++ walk(root, 1)+ return best++# ---------------------------------------------------------------------------# Divergence shape (a stable bucket key — used for shrinking + corpus dedup)# ---------------------------------------------------------------------------diff --git a/posthog/hogql/test/_pbt_corpus_db.py b/posthog/hogql/test/_pbt_corpus_db.pynew file mode 100644index 000000000000..cd43544ac4b6--- /dev/null+++ b/posthog/hogql/test/_pbt_corpus_db.py@@ -0,0 +1,116 @@+"""Shared Hypothesis example-database wiring for the HogQL parser/printer PBTs.++``parser_pbt_corpus/<hypothesis-version>/`` is a per-machine, per-Hypothesis+``DirectoryBasedExampleDatabase`` — the parent directory is tracked but every+subdirectory under it is ``.gitignore``\\ d. Each dev can populate their own+seed locally (e.g. with the future diagnostic CLI's ``--update-corpus`` mode,+or directly via :func:`committed_corpus_db`) and benefit from warm-starts and+replays on their own machine without pushing opaque binary blobs to the repo.++The storage path always resolves to the **main worktree's** copy of the+directory, so every git worktree of the same checkout shares one seed (see+:func:`_resolve_corpus_dir`). Without that, devs juggling worktrees would end up+with a different seed per branch — defeating the "persists between runs on this+machine" goal.++The Hypothesis-version segment keeps each version's blobs in its own+subdirectory: Hypothesis's blob format is only stable within a pinned version,+and without segmentation a bump would silently mis-replay stale blobs against a+newer codec.++Per Hypothesis's own recommendation (see ``MultiplexedDatabase`` /+``ReadOnlyDatabase`` docstrings), the default the tooling uses is+``MultiplexedDatabase(local, ReadOnlyDatabase(committed))``:++ - whatever the dev has put under ``parser_pbt_corpus/<version>/`` is replayed+ first on every run, but **read-only**, so a normal test run or grind never+ rewrites it — no churn from accumulated PBT failures piling up there;+ - newly-discovered failing / Pareto-front examples are written only to the+ developer's local ``.hypothesis/examples`` database (Hypothesis's default+ location).+"""++from __future__ import annotations++import subprocess+from pathlib import Path++import hypothesis+from hypothesis.configuration import storage_directory+from hypothesis.database import DirectoryBasedExampleDatabase, ExampleDatabase, MultiplexedDatabase, ReadOnlyDatabase+++def _resolve_corpus_dir() -> Path:+ """Resolve the corpus dir to a ``parser_pbt_corpus/<hypothesis-version>/``+ subdirectory of the **main worktree's** source tree, so every git worktree+ of the same checkout shares one seed.++ Two things:++ 1. ``git rev-parse --git-common-dir`` resolves to the shared ``.git`` for+ all worktrees of this repo; its parent is the main worktree's top-level.+ Without this, ``Path(__file__).parent / "parser_pbt_corpus"`` resolves to+ *this* worktree's source tree, and devs juggling worktrees end up with a+ different seed per branch.+ 2. Hypothesis's blob format is only stable within a pinned version (see+ ``DirectoryBasedExampleDatabase``). The version segment keeps each+ Hypothesis version's blobs in its own subdirectory so a bump never+ silently mis-replays stale entries against a newer codec.++ Falls back to ``Path(__file__).parent / "parser_pbt_corpus" / <version>`` if+ git isn't available or this isn't a checkout — still per-machine and+ version-segmented, just per-checkout instead of shared across worktrees.+ """+ here = Path(__file__).resolve().parent+ try:+ result = subprocess.run(+ ["git", "rev-parse", "--git-common-dir"],+ cwd=here,+ capture_output=True,+ text=True,+ check=True,+ timeout=2,+ )+ except (FileNotFoundError, subprocess.SubprocessError):+ return here / "parser_pbt_corpus" / hypothesis.__version__+ common_dir = Path(result.stdout.strip())+ if not common_dir.is_absolute():+ common_dir = (here / common_dir).resolve()+ main_worktree_root = common_dir.parent+ return main_worktree_root / "posthog" / "hogql" / "test" / "parser_pbt_corpus" / hypothesis.__version__+++# Per-machine corpus seed shared across every git worktree of this checkout,+# segmented by Hypothesis version (e.g. `parser_pbt_corpus/6.151.9/`). The+# parent dir is tracked in-tree (so the README + `.gitignore` are discoverable+# on whichever branch you're on), but every subdir under it is `.gitignore`d —+# populated and used only locally. Outside `.hypothesis/` on purpose: that path+# is gitignored repo-wide, which would sweep this dir up under it.+PARSER_PBT_CORPUS_DIR: Path = _resolve_corpus_dir()+++def committed_corpus_db() -> ExampleDatabase:+ """Read-write handle straight to the local corpus seed. Use only when+ deliberately populating the seed — everything else reads through+ :func:`shared_corpus_database` (read-only).++ Annotated ``ExampleDatabase`` (the base) rather than the concrete subclass:+ Hypothesis's ``_EDMeta`` metaclass types ``DirectoryBasedExampleDatabase(...)``+ construction as returning the base ``ExampleDatabase``."""+ return DirectoryBasedExampleDatabase(PARSER_PBT_CORPUS_DIR)+++def shared_corpus_database(local: ExampleDatabase | None = None) -> ExampleDatabase:+ """Default database for the PBT tooling: replay the local seed read-only,+ write new examples to a local read-write database. So running the PBTs+ warm-starts from the local seed and persists new failures, but never churns+ the seed blobs from the test path.++ ``local`` defaults to Hypothesis's standard ``.hypothesis/examples`` directory+ (so locally-found failures land where Hypothesis normally caches them); pass+ an explicit database to override (e.g. an ``InMemoryExampleDatabase`` for a+ hermetic run)."""+ if local is None:+ local = DirectoryBasedExampleDatabase(storage_directory("examples"))+ committed = ReadOnlyDatabase(DirectoryBasedExampleDatabase(PARSER_PBT_CORPUS_DIR))+ return MultiplexedDatabase(local, committed)diff --git a/posthog/hogql/test/parser_pbt_corpus/.gitignore b/posthog/hogql/test/parser_pbt_corpus/.gitignorenew file mode 100644index 000000000000..7c9d611b5924--- /dev/null+++ b/posthog/hogql/test/parser_pbt_corpus/.gitignore@@ -0,0 +1,3 @@+*+!.gitignore+!README.mddiff --git a/posthog/hogql/test/parser_pbt_corpus/README.md b/posthog/hogql/test/parser_pbt_corpus/README.mdnew file mode 100644index 000000000000..5120a74e2dbb--- /dev/null+++ b/posthog/hogql/test/parser_pbt_corpus/README.md@@ -0,0 +1,42 @@+# Parser PBT corpus (per-machine Hypothesis example database)++This directory is a [Hypothesis example database](https://hypothesis.readthedocs.io/en/latest/database.html)+(`DirectoryBasedExampleDatabase`) for the HogQL parser-parity property tests.++**Contents are `.gitignore`d.** Only this README and the `.gitignore` are tracked. Each developer+populates their own seed locally; nothing ever gets pushed to the remote.++The actual storage lives at `parser_pbt_corpus/<hypothesis-version>/` in the+**main worktree's** copy of this directory, even when the PBT runs from another+worktree (see `_resolve_corpus_dir` in [`_pbt_corpus_db.py`](../_pbt_corpus_db.py)).+One seed per machine + per Hypothesis version, not one per worktree.++The version segmentation matters because Hypothesis's blob format is only+stable within a pinned version — without it, a `hypothesis` bump would silently+mis-replay stale blobs against the newer codec. Old version dirs are inert+after a bump; they're harmless and can be deleted if you care about the disk.++## Why local-only?++A committed seed would ship megabytes of opaque binary blobs to the repo and churn+on every PBT run that finds a new interesting example. The PBT tooling already runs+**offline only** (never in CI), so a shared seed adds noise without solving a real+problem. Persistence between runs _on the same machine_ is what matters — and+Hypothesis's local cache combined with this dir handles that without any commits.++## How runs use this dir++The tooling wires this as `MultiplexedDatabase(local, ReadOnlyDatabase(committed))`+(see [`_pbt_corpus_db.py`](../_pbt_corpus_db.py)):++- whatever's in this dir is replayed first on every PBT run, but **read-only**,+- new examples / Pareto-front entries land in `.hypothesis/examples`+ (Hypothesis's default per-machine cache).++An empty dir is fine — it just means no warm-start. Everything else works+normally.++## Populating the seed locally++Use the read-write handle returned by `committed_corpus_db()` in+[`_pbt_corpus_db.py`](../_pbt_corpus_db.py).diff --git a/posthog/hogql/test/test_parser_grammar_pbt.py b/posthog/hogql/test/test_parser_grammar_pbt.pyindex 939e9639f2e2..dc96e8e522f4 100644--- a/posthog/hogql/test/test_parser_grammar_pbt.py+++ b/posthog/hogql/test/test_parser_grammar_pbt.py@@ -32,6 +32,7 @@ audit runs rather than every CI build.from __future__ import annotationsimport os+from collections import defaultdictfrom typing import Anyimport pytest@@ -39,20 +40,24 @@ import pytestfrom hypothesis import (HealthCheck,assume,+ event,given,settings,strategies as st,+ target,)from posthog.hogql import astfrom posthog.hogql.errors import BaseHogQLErrorfrom posthog.hogql.parser import parse_expr, parse_select, parse_string_template+from posthog.hogql.scripts._diagnostic_common import ast_depth, ast_kpathsfrom posthog.hogql.test._generated_grammar_strategies import (expr_strategy,fullTemplateString_strategy as full_template_string_strategy,select_strategy,)from posthog.hogql.test._grammar_token_strategies import _RESERVED_KEYWORDS+from posthog.hogql.test._pbt_corpus_db import shared_corpus_databasefrom posthog.hogql.visitor import clear_locationspytestmark = pytest.mark.skipif(@@ -565,23 +570,43 @@ def _assert_backends_agree(query: str, rule: str) -> None:# Both rejected — uninteresting; the grammar generator can# over-produce strings that neither visitor accepts. ``assume(False)``# raises ``UnsatisfiedAssumption`` to skip the example.+ event("outcome", "both_reject")assume(False)if a_ok != b_ok:+ event("outcome", "accept/reject divergence")accepted, rejected = (_BACKEND_A, _BACKEND_B) if a_ok else (_BACKEND_B, _BACKEND_A)raise AssertionError(f"{accepted!r} accepted but {rejected!r} rejected ({rule!r}): {query!r}")if a_ast != b_ast:+ event("outcome", "ast mismatch")raise AssertionError(f"AST mismatch for {rule!r}: {query!r}\n {_BACKEND_A}: {a_ast!r}\n {_BACKEND_B}: {b_ast!r}")+ # Both backends accepted and agree. Surface a coverage-flavoured signal+ # to Hypothesis so the shrinker preserves interesting shapes (deep ASTs,+ # novel k-paths) when it minimises failing examples — and so the optional+ # `Phase.target` hill-climbing phase can hunt for them at generation time+ # if turned on. Both targets are cheap in-process AST walks; no native+ # instrumentation needed.+ event("outcome", "match")+ kpaths = ast_kpaths(a_ast, _KPATH_K)+ target(float(len(kpaths - _SEEN_KPATHS[rule])), label="novel_kpaths")+ _SEEN_KPATHS[rule].update(kpaths)+ target(float(ast_depth(a_ast)), label="ast_depth")+# Shared Hypothesis settings. Strategies overgenerate (semantic-visitor# rejection drops a sizable fraction); ``filter_too_much`` is silenced._PBT_SETTINGS = settings(max_examples=int(os.environ.get("GRAMMAR_PBT_EXAMPLES", "1000")),deadline=None,+ # Replay the per-developer local seed read-only + write new examples to the+ # default `.hypothesis/examples` (see _pbt_corpus_db). The seed dir is+ # `.gitignore`d — devs populate it locally if they want, nothing churns the+ # repo.+ database=shared_corpus_database(),# ``too_slow`` and ``filter_too_much`` are characteristics of the# grind itself (deep ASTs, semantic-visitor rejections drop a# sizable fraction). ``data_too_large`` is deliberately *not*@@ -596,6 +621,13 @@ _PBT_SETTINGS = settings(],)+# Per-rule AST k-path coverage seen so far this session — feeds the `target()`+# steering in `_assert_backends_agree`. Keyed by rule so expr / select / full+# template don't pollute each other's novelty signal. Process-local, so the+# steering only counts within a single pytest run.+_SEEN_KPATHS: dict[str, set[tuple[str, ...]]] = defaultdict(set)+_KPATH_K: int = int(os.environ.get("GRAMMAR_PBT_KPATH_K", "2"))+# Wall-clock timeout per test (via pytest-timeout, which is already a# project dependency). Hypothesis shrinking on a deep AST tree can run# for many minutes; cap each test so a stuck shrink loop doesn't blockdiff --git a/posthog/hogql/test/test_parser_pbt.py b/posthog/hogql/test/test_parser_pbt.pyindex 4259b1647e18..1d1c6fb96109 100644--- a/posthog/hogql/test/test_parser_pbt.py+++ b/posthog/hogql/test/test_parser_pbt.py@@ -19,14 +19,18 @@ import pytestfrom hypothesis import (HealthCheck,assume,+ event,given,settings,strategies as st,+ target,)from posthog.hogql import astfrom posthog.hogql.errors import BaseHogQLErrorfrom posthog.hogql.parser import parse_expr+from posthog.hogql.scripts._diagnostic_common import ast_depth+from posthog.hogql.test._pbt_corpus_db import shared_corpus_database# These tests are too slow for CI (~8 min). Run manually with:# RUN_PBT=1 pytest posthog/hogql/test/test_parser_pbt.py@@ -349,12 +353,29 @@ def _roundtrip_check(expr: ast.Expr) -> None:# ---------------------------------------------------------------------------+# Shared settings base: replay the per-developer local seed read-only + write+# new examples to the default `.hypothesis/examples` (see _pbt_corpus_db). The+# seed dir is `.gitignore`d — devs populate it locally if they want, nothing+# churns the repo. Per-test decorators set `parent=_BASE` to inherit the+# database + slow-test allowances without re-wiring them on every class.+_BASE = settings(+ database=shared_corpus_database(),+ deadline=None,+ suppress_health_check=[HealthCheck.too_slow],+)++class TestExprRoundTrip:"""Print → parse → print yields the same HogQL string."""@given(expr=_expr_strategy())- @settings(max_examples=2000, deadline=None, suppress_health_check=[HealthCheck.too_slow])+ @settings(parent=_BASE, max_examples=2000)def test_print_parse_print_idempotent(self, expr: ast.Expr) -> None:+ # Steer toward deeper generated expression trees — the long tail+ # where printer/parser round-tripping is most likely to drift. Mainly+ # useful at shrink time: when a failure does pop, prefer to minimise+ # to a small-but-still-deep repro rather than the trivial leaf.+ target(float(ast_depth(expr)), label="ast_depth")_roundtrip_check(expr)@@ -362,8 +383,9 @@ class TestParserBackendEquivalence:"""Both parser backends produce equivalent ASTs for generated HogQL strings."""@given(expr=_expr_strategy())- @settings(max_examples=2000, deadline=None, suppress_health_check=[HealthCheck.too_slow])+ @settings(parent=_BASE, max_examples=2000)def test_rust_py_and_cpp_backends_agree(self, expr: ast.Expr) -> None:+ target(float(ast_depth(expr)), label="ast_depth")try:hogql_string = _print_hogql(expr)except BaseHogQLError:@@ -373,15 +395,20 @@ class TestParserBackendEquivalence:rust_ast, cpp_ast = _parse_both_backends(hogql_string)if rust_ast is None and cpp_ast is None:+ event("outcome", "both_reject")assume(False)return # type: ignore[unreachable]- # If one succeeds and the other fails, that's a bug- assert (rust_ast is None) == (cpp_ast is None), (- f"Backend disagreement on parsability of: {hogql_string!r}\n"- f" Rust: {'failed' if rust_ast is None else 'ok'}\n"- f" C++: {'failed' if cpp_ast is None else 'ok'}"- )+ # If one succeeds and the other fails, that's a bug. Same label as the+ # grammar PBT so `--hypothesis-show-statistics` aggregates cleanly across+ # both files.+ if (rust_ast is None) != (cpp_ast is None):+ event("outcome", "accept/reject divergence")+ raise AssertionError(+ f"Backend disagreement on parsability of: {hogql_string!r}\n"+ f" Rust: {'failed' if rust_ast is None else 'ok'}\n"+ f" C++: {'failed' if cpp_ast is None else 'ok'}"+ )assert rust_ast is not None and cpp_ast is not None@@ -390,28 +417,32 @@ class TestParserBackendEquivalence:rust_printed = _print_hogql(rust_ast)cpp_printed = _print_hogql(cpp_ast)- assert rust_printed == cpp_printed, (- f"Backend outputs differ for: {hogql_string!r}\n"- f" Rust backend: {rust_printed!r}\n"- f" C++ backend: {cpp_printed!r}"- )+ if rust_printed != cpp_printed:+ event("outcome", "ast mismatch")+ raise AssertionError(+ f"Backend outputs differ for: {hogql_string!r}\n"+ f" Rust backend: {rust_printed!r}\n"+ f" C++ backend: {cpp_printed!r}"+ )++ event("outcome", "match")class TestConstantRoundTrip:"""Focused round-trip tests for constant values (strings, numbers, booleans, null)."""@given(s=_SAFE_STRING)- @settings(max_examples=1000)+ @settings(parent=_BASE, max_examples=1000)def test_string_constant_roundtrip(self, s: str) -> None:_roundtrip_check(ast.Constant(value=s))@given(n=_SAFE_INTEGER)- @settings(max_examples=1000)+ @settings(parent=_BASE, max_examples=1000)def test_integer_constant_roundtrip(self, n: int) -> None:_roundtrip_check(ast.Constant(value=n))@given(f=_SAFE_FLOAT)- @settings(max_examples=1000)+ @settings(parent=_BASE, max_examples=1000)def test_float_constant_roundtrip(self, f: float) -> None:node = ast.Constant(value=f)printed = _print_hogql(node)