Skip to content

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

feat(hogql): tag every query with a structural plan fingerprint (#97762)

George Munyoro9b739f7c1ed2
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index c3443b1f7ed9..4d8392e6f3f2 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -541,6 +541,14 @@ class QueryTags(BaseModel):
hogql_features: Optional[HogQLFeatures] = None
+ # Structural hash of the HogQL AST with literals stripped (posthog/hogql/cost/fingerprint.py), so
+ # query_log can group actual cost by plan shape and join it to the estimate recorded below.
+ plan_fingerprint: Optional[str] = None
+ # Set by the HogQL cost planner before execution and compared against read_rows / read_bytes in
+ # query_log to calibrate it. None until the estimator runs.
+ estimated_rows: Optional[int] = None
+ estimated_bytes: Optional[int] = None
+
modifiers: Optional[object] = None
number_of_entities: Optional[int] = None
person_on_events_mode: Optional[str] = None # PersonsOnEventsMode
diff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.py
index 30ef312dc1c8..37e7c939a8d5 100644
--- a/posthog/clickhouse/test/test_query_tagging.py
+++ b/posthog/clickhouse/test/test_query_tagging.py
@@ -9,6 +9,8 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin
from parameterized import parameterized
from pydantic import ValidationError
+from posthog.hogql.cost.fingerprint import fingerprint_query
+from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client import sync_execute
@@ -426,6 +428,18 @@ class TestQueryTaggingSourceInQueryLog(BaseTest, ClickhouseTestMixin):
assert comment["source_file"] == "posthog/clickhouse/test/test_query_tagging.py"
assert comment["source_line"] > 0
+ def test_execute_hogql_query_populates_plan_fingerprint(self):
+ marker = str(uuid.uuid4())
+ # An explicit LIMIT keeps the executor from adding its default one, so both sides hash the same shape.
+ sql = f"SELECT count() FROM events WHERE event = '{marker}' LIMIT 100" # noqa: S608
+ reset_query_tags()
+ tag_queries(kind="request", id="test")
+ execute_hogql_query(sql, team=self.team, query_type="HogQLQuery")
+
+ comment = self._get_log_comment(marker)
+
+ assert comment["plan_fingerprint"] == fingerprint_query(parse_select(sql))
+
@parameterized.expand([("approved", True), ("not_approved", False)])
def test_sync_execute_preserves_ai_data_processing_approved_tag(self, _name, approved):
marker = str(uuid.uuid4())
diff --git a/posthog/hogql/cost/accuracy.py b/posthog/hogql/cost/accuracy.py
new file mode 100644
index 000000000000..d070c7324e92
--- /dev/null
+++ b/posthog/hogql/cost/accuracy.py
@@ -0,0 +1,33 @@
+"""The query that judges the cost planner's estimates.
+
+q-error is ``greatest(estimate / actual, actual / estimate)``: 1 is a perfect estimate and 10 is an order of
+magnitude off in either direction. The planner's exit bar is a median below 3 and a p90 below 10 for events
+scans. Rows without an estimate are excluded so the metric only judges queries the planner saw. Failed queries
+are excluded because their ``read_rows`` reflect where they stopped, not what they would have read. Only the
+initial query counts: ClickHouse logs one row per shard subquery too, each repeating the parent's tags, and
+they would otherwise multiply ``queries`` by the shard count.
+"""
+
+
+def cost_estimate_accuracy_hogql(days: int = 7) -> str:
+ """HogQL over ``query_log`` grouping q-error by plan fingerprint for the last ``days`` days."""
+ return f"""
+SELECT
+ plan_fingerprint,
+ count() AS queries,
+ quantile(0.5)(greatest(estimated_rows / read_rows, read_rows / estimated_rows)) AS median_rows_q_error,
+ quantile(0.9)(greatest(estimated_rows / read_rows, read_rows / estimated_rows)) AS p90_rows_q_error,
+ quantile(0.5)(greatest(estimated_bytes / read_bytes, read_bytes / estimated_bytes)) AS median_bytes_q_error,
+ quantile(0.9)(greatest(estimated_bytes / read_bytes, read_bytes / estimated_bytes)) AS p90_bytes_q_error
+FROM query_log
+WHERE event_date >= today() - {int(days)}
+ AND status = 'QueryFinish'
+ AND is_initial_query
+ AND plan_fingerprint != ''
+ AND estimated_rows > 0
+ AND read_rows > 0
+ AND estimated_bytes > 0
+ AND read_bytes > 0
+GROUP BY plan_fingerprint
+ORDER BY queries DESC
+"""
diff --git a/posthog/hogql/cost/fingerprint.py b/posthog/hogql/cost/fingerprint.py
new file mode 100644
index 000000000000..3dfddea19e1d
--- /dev/null
+++ b/posthog/hogql/cost/fingerprint.py
@@ -0,0 +1,82 @@
+"""Stable structural fingerprint of a HogQL query.
+
+The fingerprint hashes the shape of an AST: node kinds, table and column references, function names,
+operators, join kinds and aliases. It skips constant values, source positions and resolved types. Two
+queries that differ only in literals (a date range, an event name, a LIMIT) share a fingerprint. Two
+queries that differ in structure never do.
+
+The HogQL executor emits it as the ``plan_fingerprint`` query tag, and ``query_log_archive`` exposes it
+as ``lc_plan_fingerprint``. That lets the cost planner group the actual cost ClickHouse reports by plan
+shape, and join it to the estimate it recorded for the same query.
+"""
+
+import hashlib
+from collections.abc import Iterator
+from dataclasses import fields
+from enum import Enum
+
+from pydantic import BaseModel
+
+from posthog.hogql import ast
+from posthog.hogql.base import AST, Type
+
+# Source positions and the types the resolver attaches carry no structure.
+_SKIPPED_FIELDS = frozenset({"start", "end", "type"})
+
+_field_names_cache: dict[type, tuple[str, ...]] = {}
+
+
+def _field_names(cls: type) -> tuple[str, ...]:
+ names = _field_names_cache.get(cls)
+ if names is None:
+ names = tuple(f.name for f in fields(cls) if f.name not in _SKIPPED_FIELDS)
+ _field_names_cache[cls] = names
+ return names
+
+
+def _tokens(value: object) -> Iterator[str]:
+ if isinstance(value, ast.Constant):
+ # The literal's type shapes the plan (a string vs a number comparison); its value does not.
+ yield f"Constant:{type(value.value).__name__}"
+ elif isinstance(value, ast.Alias) and value.hidden:
+ # The resolver adds hidden aliases to name columns. They are not part of the query's shape.
+ yield from _tokens(value.expr)
+ elif isinstance(value, Type):
+ return
+ elif isinstance(value, AST):
+ yield type(value).__name__
+ for name in _field_names(type(value)):
+ yield name
+ yield from _tokens(getattr(value, name))
+ yield "/"
+ elif isinstance(value, list | tuple):
+ yield "["
+ for item in value:
+ yield from _tokens(item)
+ yield "]"
+ elif isinstance(value, dict):
+ yield "{"
+ for key, item in value.items():
+ yield str(key)
+ yield from _tokens(item)
+ yield "}"
+ elif isinstance(value, BaseModel):
+ # Query settings such as join_algorithm change the physical plan, so every set value is part of
+ # the shape. Unset fields are skipped so adding a new setting does not move existing fingerprints.
+ yield type(value).__name__
+ for name, item in sorted(value.model_dump(exclude_none=True).items()):
+ yield name
+ yield from _tokens(item)
+ yield "/"
+ elif isinstance(value, Enum):
+ yield str(value.value)
+ elif value is None or isinstance(value, str | int | float | bool):
+ yield repr(value)
+ else:
+ yield type(value).__name__
+
+
+def fingerprint_query(node: ast.SelectQuery | ast.SelectSetQuery) -> str:
+ """Return a 16-hex-character digest of the query's structure."""
+ digest = hashlib.sha256("\x1f".join(_tokens(node)).encode())
+ return digest.hexdigest()[:16]
diff --git a/posthog/hogql/cost/test/test_fingerprint.py b/posthog/hogql/cost/test/test_fingerprint.py
new file mode 100644
index 000000000000..0a5c24f1a5ce
--- /dev/null
+++ b/posthog/hogql/cost/test/test_fingerprint.py
@@ -0,0 +1,110 @@
+from typing import cast
+
+from posthog.test.base import BaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLQuerySettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.cost.fingerprint import fingerprint_query
+from posthog.hogql.database.database import Database
+from posthog.hogql.parser import parse_select
+from posthog.hogql.resolver import resolve_types
+
+
+class TestFingerprintQueryShape(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "date_range",
+ "SELECT count() FROM events WHERE timestamp > '2024-01-01' AND timestamp < '2024-02-01'",
+ "SELECT count() FROM events WHERE timestamp > '2025-06-01' AND timestamp < '2025-09-01'",
+ ),
+ (
+ "event_name",
+ "SELECT count() FROM events WHERE event = '$pageview'",
+ "SELECT count() FROM events WHERE event = 'signup'",
+ ),
+ (
+ "limit",
+ "SELECT event FROM events LIMIT 10",
+ "SELECT event FROM events LIMIT 100000",
+ ),
+ (
+ "in_list_values",
+ "SELECT count() FROM events WHERE event IN ('a', 'b')",
+ "SELECT count() FROM events WHERE event IN ('c', 'd')",
+ ),
+ ]
+ )
+ def test_queries_differing_only_in_literals_share_a_fingerprint(self, _name, sql_a, sql_b):
+ assert fingerprint_query(parse_select(sql_a)) == fingerprint_query(parse_select(sql_b))
+
+ @parameterized.expand(
+ [
+ (
+ "extra_predicate",
+ "SELECT count() FROM events WHERE event = 'x'",
+ "SELECT count() FROM events WHERE event = 'x' AND properties.$browser = 'y'",
+ ),
+ (
+ "table",
+ "SELECT count() FROM events",
+ "SELECT count() FROM persons",
+ ),
+ (
+ "join",
+ "SELECT count() FROM events",
+ "SELECT count() FROM events JOIN persons ON persons.id = events.person_id",
+ ),
+ (
+ "aggregate_function",
+ "SELECT count() FROM events",
+ "SELECT uniq(distinct_id) FROM events",
+ ),
+ (
+ "literal_type",
+ "SELECT count() FROM events WHERE properties.n = 1",
+ "SELECT count() FROM events WHERE properties.n = '1'",
+ ),
+ (
+ "operator",
+ "SELECT count() FROM events WHERE timestamp > '2024-01-01'",
+ "SELECT count() FROM events WHERE timestamp < '2024-01-01'",
+ ),
+ (
+ "group_by",
+ "SELECT count() FROM events",
+ "SELECT count() FROM events GROUP BY event",
+ ),
+ ]
+ )
+ def test_structural_differences_produce_distinct_fingerprints(self, _name, sql_a, sql_b):
+ assert fingerprint_query(parse_select(sql_a)) != fingerprint_query(parse_select(sql_b))
+
+ def test_plan_affecting_query_settings_change_the_fingerprint(self):
+ # Runners attach settings such as join_algorithm programmatically; they change the physical plan.
+ plain = parse_select("SELECT count() FROM events")
+ hash_join = cast(ast.SelectQuery, parse_select("SELECT count() FROM events"))
+ hash_join.settings = HogQLQuerySettings(join_algorithm="hash")
+ parallel_hash_join = cast(ast.SelectQuery, parse_select("SELECT count() FROM events"))
+ parallel_hash_join.settings = HogQLQuerySettings(join_algorithm="parallel_hash")
+
+ fingerprints = {fingerprint_query(node) for node in (plain, hash_join, parallel_hash_join)}
+
+ assert len(fingerprints) == 3
+
+
+class TestFingerprintQueryResolution(BaseTest):
+ def test_resolved_types_do_not_change_the_fingerprint(self):
+ node = parse_select("SELECT count() AS c FROM events WHERE event = '$pageview' AND timestamp > '2024-01-01'")
+ raw = fingerprint_query(node)
+
+ database = Database.create_for(team=self.team)
+ context = HogQLContext(database=database, team_id=self.team.pk, enable_select_queries=True)
+ resolved = cast(ast.SelectQuery, resolve_types(node, context, dialect="clickhouse"))
+
+ assert fingerprint_query(resolved) == raw
diff --git a/posthog/hogql/database/schema/query_log_archive.py b/posthog/hogql/database/schema/query_log_archive.py
index ab4c57eca1e2..34f1a9c72d8d 100644
--- a/posthog/hogql/database/schema/query_log_archive.py
+++ b/posthog/hogql/database/schema/query_log_archive.py
@@ -63,6 +63,11 @@ QUERY_LOG_ARCHIVE_FIELDS: dict[str, FieldOrTable] = {
nullable=False,
description="Query outcome type, e.g. 'QueryFinish' or 'ExceptionWhileProcessing'.",
),
+ "is_initial_query": BooleanDatabaseField(
+ name="is_initial_query",
+ nullable=False,
+ description="True for the query a client sent. False for the per-shard subqueries ClickHouse ran on its behalf, which repeat the parent's tags.",
+ ),
"exception_code": IntegerDatabaseField(
name="exception_code", nullable=False, description="ClickHouse exception code if the query failed, else 0."
),
@@ -107,6 +112,21 @@ QUERY_LOG_ARCHIVE_FIELDS: dict[str, FieldOrTable] = {
"ReadBufferFromS3Bytes": IntegerDatabaseField(
name="ProfileEvents_ReadBufferFromS3Bytes", nullable=False, description="Bytes read from S3 by the query."
),
+ "plan_fingerprint": StringDatabaseField(
+ name="lc_plan_fingerprint",
+ nullable=False,
+ description="Hash of the query's structure with literal values removed. Queries that differ only in literals share it.",
+ ),
+ "estimated_rows": IntegerDatabaseField(
+ name="lc_estimated_rows",
+ nullable=False,
+ description="Rows the cost planner estimated the query would read before it ran. 0 when no estimate was recorded.",
+ ),
+ "estimated_bytes": IntegerDatabaseField(
+ name="lc_estimated_bytes",
+ nullable=False,
+ description="Bytes the cost planner estimated the query would read before it ran. 0 when no estimate was recorded.",
+ ),
# "cost_usd": FloatDatabaseField(name="cost_usd", nullable=False),
}
@@ -191,6 +211,11 @@ class RawQueryLogArchiveTable(Table):
"query_id": StringDatabaseField(
name="query_id", nullable=False, description="ClickHouse-assigned query identifier."
),
+ "is_initial_query": BooleanDatabaseField(
+ name="is_initial_query",
+ nullable=False,
+ description="True for the query a client sent, false for its per-shard subqueries.",
+ ),
"lc_client_query_id": StringDatabaseField(
name="lc_client_query_id", nullable=False, description="Client-supplied query identifier."
),
@@ -250,6 +275,21 @@ class RawQueryLogArchiveTable(Table):
"ProfileEvents_ReadBufferFromS3Bytes": IntegerDatabaseField(
name="ProfileEvents_ReadBufferFromS3Bytes", nullable=False
),
+ "lc_plan_fingerprint": StringDatabaseField(
+ name="lc_plan_fingerprint",
+ nullable=False,
+ description="Hash of the query's structure with literal values removed.",
+ ),
+ "lc_estimated_rows": IntegerDatabaseField(
+ name="lc_estimated_rows",
+ nullable=False,
+ description="Rows the cost planner estimated the query would read. 0 when no estimate was recorded.",
+ ),
+ "lc_estimated_bytes": IntegerDatabaseField(
+ name="lc_estimated_bytes",
+ nullable=False,
+ description="Bytes the cost planner estimated the query would read. 0 when no estimate was recorded.",
+ ),
}
def to_printed_clickhouse(self, context) -> str:
diff --git a/posthog/hogql/database/schema/test/test_table_query_log.py b/posthog/hogql/database/schema/test/test_table_query_log.py
index 1f26a4376f95..f0694c49fdd4 100644
--- a/posthog/hogql/database/schema/test/test_table_query_log.py
+++ b/posthog/hogql/database/schema/test/test_table_query_log.py
@@ -2,6 +2,7 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
from posthog.hogql.context import HogQLContext
+from posthog.hogql.cost.accuracy import cost_estimate_accuracy_hogql
from posthog.hogql.database.database import Database
from posthog.hogql.query import execute_hogql_query
@@ -49,3 +50,16 @@ LIMIT 10 SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_t
external_tables=None,
)
assert response.results is not None
+
+ def test_cost_estimate_accuracy_query_runs_against_the_archive(self):
+ response = execute_hogql_query(cost_estimate_accuracy_hogql(days=7), self.team)
+
+ assert response.results is not None
+ assert response.columns == [
+ "plan_fingerprint",
+ "queries",
+ "median_rows_q_error",
+ "p90_rows_q_error",
+ "median_bytes_q_error",
+ "p90_bytes_q_error",
+ ]
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 2047fa1dbdeb..c9c15af2f43b 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -2168,6 +2168,16 @@
"table": null,
"type": "string"
},
+ "is_initial_query": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "is_initial_query",
+ "id": null,
+ "name": "is_initial_query",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
"exception_code": {
"chain": null,
"fields": null,
@@ -2287,6 +2297,36 @@
"schema_valid": true,
"table": null,
"type": "integer"
+ },
+ "plan_fingerprint": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "plan_fingerprint",
+ "id": null,
+ "name": "plan_fingerprint",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "estimated_rows": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "estimated_rows",
+ "id": null,
+ "name": "estimated_rows",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "estimated_bytes": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "estimated_bytes",
+ "id": null,
+ "name": "estimated_bytes",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
}
},
"id": "query_log",
@@ -14294,6 +14334,16 @@
"table": null,
"type": "string"
},
+ "is_initial_query": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "is_initial_query",
+ "id": null,
+ "name": "is_initial_query",
+ "schema_valid": true,
+ "table": null,
+ "type": "boolean"
+ },
"exception_code": {
"chain": null,
"fields": null,
@@ -14413,6 +14463,36 @@
"schema_valid": true,
"table": null,
"type": "integer"
+ },
+ "plan_fingerprint": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "plan_fingerprint",
+ "id": null,
+ "name": "plan_fingerprint",
+ "schema_valid": true,
+ "table": null,
+ "type": "string"
+ },
+ "estimated_rows": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "estimated_rows",
+ "id": null,
+ "name": "estimated_rows",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
+ },
+ "estimated_bytes": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "estimated_bytes",
+ "id": null,
+ "name": "estimated_bytes",
+ "schema_valid": true,
+ "table": null,
+ "type": "integer"
}
},
"id": "query_log",
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index 873c70f537cb..1a3b96846621 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -23,6 +23,7 @@ from posthog.hogql.constants import (
get_default_hogql_global_settings,
get_default_limit_for_context,
)
+from posthog.hogql.cost.fingerprint import fingerprint_query
from posthog.hogql.database.database import Database
from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.database.schema.duckdb_table_functions import (
@@ -576,6 +577,13 @@ class HogQLQueryExecutor:
self.used_data_warehouse_sources = sources
return sources
+ def _plan_fingerprint(self) -> str | None:
+ # The tag is advisory. A query that compiles must never fail because fingerprinting it did.
+ try:
+ return fingerprint_query(self.select_query)
+ except Exception:
+ return None
+
@tracer.start_as_current_span("HogQLQueryExecutor._execute_direct_sql_query")
def _execute_direct_sql_query(self, adapter: DirectSQLAdapter | None = None) -> None:
assert self.direct_sql is not None
@@ -783,6 +791,8 @@ class HogQLQueryExecutor:
with self.timings.measure("clickhouse_execute"):
with self.timings.measure("extract_hogql_features"):
hogql_features = extract_hogql_features(self.select_query)
+ with self.timings.measure("plan_fingerprint"):
+ plan_fingerprint = self._plan_fingerprint()
self._detect_warehouse_sources()
tag_queries(
team_id=self.team.pk,
@@ -791,6 +801,7 @@ class HogQLQueryExecutor:
has_json_operations="JSONExtract" in self.clickhouse_sql or "JSONHas" in self.clickhouse_sql,
hogql_features=hogql_features,
saved_query_ids=sorted(self.context.referenced_saved_query_ids) or None,
+ plan_fingerprint=plan_fingerprint,
timings=timings_dict,
modifiers=(
{k: v for k, v in self.modifiers.model_dump().items() if v is not None} if self.modifiers else {}