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.

fix(insights): bound taxonomy suggestion lookups in the SQL editor (#91986)

Thomas Obermüller39b36afbcfed
diff --git a/posthog/hogql/taxonomy_validation.py b/posthog/hogql/taxonomy_validation.py
index 3c8fae2422aa..87ced356e6d0 100644
--- a/posthog/hogql/taxonomy_validation.py
+++ b/posthog/hogql/taxonomy_validation.py
@@ -3,8 +3,10 @@ from difflib import get_close_matches
from logging import getLogger
from typing import Literal
+from django.contrib.postgres.search import TrigramSimilarity
from django.db import DatabaseError
-from django.db.models import QuerySet
+from django.db.models import Case, IntegerField, Q, QuerySet, Value, When
+from django.db.models.functions import Greatest
from posthog.schema import HogQLNotice
@@ -23,6 +25,18 @@ logger = getLogger(__name__)
# `property` → a `properties.<identifier>` field. Both escape the suggestion (see `_build_fix`).
FixContext = Literal["string", "property"]
+# How many similar names the suggestion lookup reads per typed name. Postgres ranks candidates by
+# trigram similarity, so the best match is in the first rows and difflib does not need every name.
+SUGGESTION_CANDIDATE_LIMIT = 20
+
+# The `name` column of both definition models is `CharField(max_length=400)`.
+MAX_SUGGESTION_INPUT_LENGTH = 400
+
+# How many unknown names in one query get a suggestion. One lookup covers the whole batch, but
+# pg_trgm compares every name in it, and a caller controls how many unknown names one query carries.
+# Names past this cap still warn, only without "Did you mean".
+MAX_SUGGESTED_NAMES = 5
+
# Property names that are legitimately dynamic — they encode an id/key after the prefix, so they will
# never appear in PropertyDefinition and must not be flagged as unknown.
DYNAMIC_PROPERTY_PREFIXES = (
@@ -183,24 +197,24 @@ def _warnings_for_unknown_references(
references_by_name.setdefault(reference.name, reference)
referenced_names = list(references_by_name.keys())
- # Hot path: an indexed `name__in` existence check over only the referenced names (usually 1–5),
- # not a materialization of the whole team taxonomy. When every name is valid we never load more.
+ # Hot path: an indexed `name__in` existence check over only the referenced names (usually 1–5).
+ # When every name is valid we never load more.
found_names = set(taxonomy.filter(name__in=referenced_names).values_list("name", flat=True))
unknown_names = [name for name in referenced_names if name not in found_names]
if not unknown_names:
return []
- # Rare path (a name is unknown): load the full name set for fuzzy suggestions. This also doubles as
- # the empty-taxonomy guard — a project with no definitions yet should not warn on anything.
- known_names = _known_names(taxonomy)
- if not known_names:
+ # A project with no definitions yet must not warn on every name. Only ask when nothing was
+ # found, because a hit above already proves the taxonomy has rows.
+ if not found_names and not taxonomy.exists():
return []
- sorted_known_names = sorted(known_names)
+
+ suggestions = _suggestions_for(taxonomy, unknown_names[:MAX_SUGGESTED_NAMES])
warnings: list[HogQLNotice] = []
for name in unknown_names:
reference = references_by_name[name]
- suggestion = _suggest_name(name, known_names, sorted_known_names)
+ suggestion = suggestions.get(name)
message = f"{kind} '{name}' was not found in this project taxonomy."
if suggestion:
message += f" Did you mean '{suggestion}'?"
@@ -228,14 +242,80 @@ def _build_fix(fix_context: FixContext | None, suggestion: str) -> str | None:
return None
-def _known_names(taxonomy: QuerySet) -> set[str]:
- return set(taxonomy.values_list("name", flat=True))
+def _suggestions_for(taxonomy: QuerySet, names: list[str]) -> dict[str, str]:
+ """Map the names that earn a suggestion to the name suggested for each.
+
+ One candidate read covers the whole batch. A read per name would cost a round trip per name, and
+ a typical project holds a few hundred definitions, where those round trips cost more than the
+ comparison they save.
+ """
+ candidates = _similar_names(taxonomy, names)
+ if not candidates:
+ return {}
+
+ candidate_set = set(candidates)
+ suggestions: dict[str, str] = {}
+ for name in names:
+ dollar_prefixed = f"${name}"
+ if not name.startswith("$") and dollar_prefixed in candidate_set:
+ suggestions[name] = dollar_prefixed
+ continue
+
+ closest = _closest_name(name, candidates)
+ if closest:
+ suggestions[name] = closest
+
+ return suggestions
+
+
+def _similar_names(taxonomy: QuerySet, names: list[str]) -> list[str]:
+ """Read the names most similar to any of `names`, ranked and capped by Postgres.
+
+ `name__trigram_similar` is the pg_trgm `%` operator, which the GIN trigram indexes
+ `index_event_definition_name` and `index_property_definition_name` answer directly. Postgres
+ still intersects that match with the project scope, so this call is bounded by what it returns,
+ not by what it reads.
+
+ The `$`-prefixed form of each name is matched exactly as well, and sorts ahead of the ranked
+ candidates. A caller who typed a name without its `$` therefore keeps that suggestion however
+ many other candidates the batch pulls in.
+
+ A name longer than the `name` column can never equal a definition, and pg_trgm cost grows with
+ the input, so an oversized literal is dropped rather than compared.
+ """
+ comparable = [name for name in names if len(name) <= MAX_SUGGESTION_INPUT_LENGTH]
+ if not comparable:
+ return []
+
+ dollar_prefixed = [f"${name}" for name in comparable if not name.startswith("$")]
+
+ matches = Q(name__in=dollar_prefixed) if dollar_prefixed else Q()
+ for name in comparable:
+ matches |= Q(name__trigram_similar=name)
+
+ similarities = [TrigramSimilarity("name", name) for name in comparable]
+ ranked = taxonomy.filter(matches).annotate(
+ # `Greatest` needs two expressions, and one unknown name is the common case.
+ name_similarity=Greatest(*similarities) if len(similarities) > 1 else similarities[0]
+ )
+
+ ordering = ["-name_similarity", "name"]
+ if dollar_prefixed:
+ ranked = ranked.annotate(
+ name_is_dollar_prefixed=Case(
+ When(name__in=dollar_prefixed, then=Value(1)), default=Value(0), output_field=IntegerField()
+ )
+ )
+ ordering.insert(0, "-name_is_dollar_prefixed")
+ return list(
+ ranked.order_by(*ordering).values_list("name", flat=True)[: SUGGESTION_CANDIDATE_LIMIT * len(comparable)]
+ )
-def _suggest_name(name: str, known_names: set[str], sorted_known_names: list[str]) -> str | None:
- dollar_prefixed = f"${name}"
- if not name.startswith("$") and dollar_prefixed in known_names:
- return dollar_prefixed
- matches = get_close_matches(name, sorted_known_names, n=1, cutoff=0.6)
+def _closest_name(name: str, candidates: list[str]) -> str | None:
+ # pg_trgm selects candidates at the server's `pg_trgm.similarity_threshold` (0.3 by default),
+ # which is loose enough to return names a reader would not accept as a typo. difflib makes the
+ # final call at a stricter cutoff, so a suggestion needs both measures to agree.
+ matches = get_close_matches(name, candidates, n=1, cutoff=0.6)
return matches[0] if matches else None
diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.py
index 5f3fe0d294b9..036779446b23 100644
--- a/posthog/hogql/test/test_metadata.py
+++ b/posthog/hogql/test/test_metadata.py
@@ -4,8 +4,9 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
from django.conf import settings
-from django.db import DatabaseError
+from django.db import DatabaseError, connection
from django.test import override_settings
+from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
@@ -21,8 +22,9 @@ from posthog.schema import (
from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR
from posthog.hogql.metadata import get_hogql_metadata
from posthog.hogql.parser import parse_select
+from posthog.hogql.taxonomy_validation import MAX_SUGGESTED_NAMES
-from posthog.models import EventDefinition, PropertyDefinition
+from posthog.models import EventDefinition, PropertyDefinition, Team
from products.cohorts.backend.models.cohort import Cohort
from products.product_analytics.backend.facade.models import InsightVariable
@@ -291,6 +293,64 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(metadata.isValid)
self.assertEqual(metadata.warnings, [])
+ @parameterized.expand([("event",), ("property",)])
+ def test_metadata_scopes_taxonomy_to_the_project(self, kind: str) -> None:
+ # Definitions are project-scoped, and so is the taxonomic filter that lists them. A
+ # team-scoped lookup here reports a name as unknown that the filter offers, for every
+ # definition ingested through a sibling environment of the same project.
+ sibling = Team.objects.create(
+ organization=self.organization, project_id=self.team.project_id, name="sibling environment"
+ )
+ other_project = Team.objects.create(organization=self.organization, name="unrelated project")
+ model = EventDefinition if kind == "event" else PropertyDefinition
+ # Without a definition owned by this team the taxonomy reads as empty under a team-scoped
+ # lookup, and the empty-taxonomy early return would satisfy the first assertion for free.
+ model.objects.create(team=self.team, name="owned_by_this_team")
+ model.objects.create(team=sibling, project_id=self.team.project_id, name="in_this_project")
+ model.objects.create(team=other_project, project_id=other_project.project_id, name="in_another_project")
+
+ def taxonomy_warnings(name: str) -> list[str]:
+ query = (
+ f"SELECT count() FROM events WHERE event = '{name}'"
+ if kind == "event"
+ else f"SELECT properties.{name} FROM events"
+ )
+ return [w.message for w in self._select(query).warnings if "project taxonomy" in w.message]
+
+ self.assertEqual(taxonomy_warnings("in_this_project"), [])
+ self.assertEqual(len(taxonomy_warnings("in_another_project")), 1)
+
+ def _select_with_unknown_properties(self, count: int) -> HogQLMetadataResponse:
+ for index in range(count):
+ PropertyDefinition.objects.create(team=self.team, name=f"suggestable_{index}")
+
+ conditions = " OR ".join(f"properties.sugestable_{index} = '1'" for index in range(count))
+ return self._select(f"SELECT count() FROM events WHERE {conditions}")
+
+ def test_metadata_caps_how_many_unknown_names_get_a_suggestion(self) -> None:
+ # One query can carry any number of unknown names. Every unknown name still warns, so only
+ # the "Did you mean" half is capped.
+ unknown_count = MAX_SUGGESTED_NAMES + 3
+
+ metadata = self._select_with_unknown_properties(unknown_count)
+
+ taxonomy_warnings = [w.message for w in metadata.warnings if "project taxonomy" in w.message]
+ self.assertEqual(len(taxonomy_warnings), unknown_count)
+ self.assertEqual(
+ len([message for message in taxonomy_warnings if "Did you mean" in message]),
+ MAX_SUGGESTED_NAMES,
+ )
+
+ def test_metadata_reads_suggestion_candidates_in_one_query(self) -> None:
+ # A candidate read per unknown name costs a round trip per name. A typical project holds a
+ # few hundred definitions, where those round trips cost more than the comparison they save.
+ with CaptureQueriesContext(connection) as captured:
+ metadata = self._select_with_unknown_properties(MAX_SUGGESTED_NAMES)
+
+ self.assertTrue(metadata.isValid)
+ candidate_reads = [q["sql"] for q in captured.captured_queries if "SIMILARITY" in q["sql"].upper()]
+ self.assertEqual(len(candidate_reads), 1, candidate_reads)
+
def test_metadata_does_not_warn_for_dynamic_event_expression(self):
EventDefinition.objects.create(team=self.team, name="paid_bill")
@@ -313,14 +373,14 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):
taxonomy_warnings = [warning for warning in metadata.warnings if "project taxonomy" in warning.message]
self.assertEqual(taxonomy_warnings, [])
- def test_metadata_skips_full_taxonomy_fetch_for_known_event(self):
+ def test_metadata_skips_suggestion_lookup_for_known_event(self):
EventDefinition.objects.create(team=self.team, name="paid_bill")
- with patch("posthog.hogql.taxonomy_validation._known_names") as known_names:
+ with patch("posthog.hogql.taxonomy_validation._similar_names") as similar_names:
metadata = self._select("SELECT count() FROM events WHERE event = 'paid_bill'")
self.assertTrue(metadata.isValid)
- known_names.assert_not_called()
+ similar_names.assert_not_called()
def test_metadata_event_literal_fix_preserves_quotes(self):
EventDefinition.objects.create(team=self.team, name="$pageview")