: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
fix(hogql): stop flagging virtual traffic properties as unknown taxonomy (#92104)
posthog[bot]4e5497edffab
diff --git a/ee/hogai/chat_agent/taxonomy/virtual_properties.py b/ee/hogai/chat_agent/taxonomy/virtual_properties.pyindex e21b22ff2dd7..55dfd20acb02 100644--- a/ee/hogai/chat_agent/taxonomy/virtual_properties.py+++ b/ee/hogai/chat_agent/taxonomy/virtual_properties.py@@ -1,7 +1,7 @@from collections.abc import Container, Iterablefrom typing import Literal-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinition+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP, CoreFilterDefinition, is_virtual_propertyfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType@@ -19,10 +19,9 @@ def virtual_group_for_entity(entity: str) -> VirtualPropertyGroup:def get_virtual_property_definition(group: VirtualPropertyGroup, property_name: str) -> CoreFilterDefinition | None:- definition = CORE_FILTER_DEFINITIONS_BY_GROUP[group].get(property_name)- if definition is None or definition.get("virtual") is not True:+ if not is_virtual_property(group, property_name):return None- return definition+ return CORE_FILTER_DEFINITIONS_BY_GROUP[group][property_name]def list_virtual_properties(group: VirtualPropertyGroup, exclude: Container[str] = ()) -> list[tuple[str, str | None]]:@@ -30,7 +29,7 @@ def list_virtual_properties(group: VirtualPropertyGroup, exclude: Container[str]return [(name, definition.get("type"))for name, definition in CORE_FILTER_DEFINITIONS_BY_GROUP[group].items()- if definition.get("virtual") is True and name not in exclude+ if is_virtual_property(group, name) and name not in exclude]diff --git a/posthog/hogql/taxonomy_validation.py b/posthog/hogql/taxonomy_validation.pyindex b5dfe43acffe..962e30511c4b 100644--- a/posthog/hogql/taxonomy_validation.py+++ b/posthog/hogql/taxonomy_validation.py@@ -15,11 +15,17 @@ from posthog.hogql.escape_sql import escape_hogql_identifier, escape_hogql_strinfrom posthog.hogql.visitor import TraversingVisitorfrom posthog.models import EventDefinition, PropertyDefinition, Team+from posthog.taxonomy.taxonomy import virtual_property_namesfrom products.event_definitions.backend.models.property_definition import effective_project_id_exprlogger = getLogger(__name__)+# Virtual event properties (e.g. `$virt_traffic_type`, `$virt_is_bot`) are computed at query time from+# event data and never persisted as PropertyDefinition rows, so a lookup against the table would flag+# them as unknown. `read_taxonomy` reads the same source, so the two tools stay in agreement.+VIRTUAL_EVENT_PROPERTY_NAMES = virtual_property_names("event_properties")+# How a suggested name is rendered back into the marked range for a one-click fix:# `string` → a quoted, escaped string literal (event `=`/`IN` values, `properties['key']` keys);# `property` → a `properties.<identifier>` field. Both escape the suggestion (see `_build_fix`).@@ -62,6 +68,10 @@ class TaxonomyReference:# it strips the quotes/prefix. `fix_context` says how to render the suggested name back into that slot.# `None` means "warn, but offer no one-click fix" (e.g. nested `properties.a.b`).fix_context: FixContext | None = "string"+ # `properties['name']` bracket access reads the raw JSON blob directly; `properties.name` dot access is+ # the form the resolver remaps onto a virtual top-level field for `$virt` names. Recording the form lets+ # the validator exempt a virtual name only for the dot access that actually reaches the computed value.+ bracket_access: bool = Falseclass TaxonomyReferenceVisitor(TraversingVisitor):@@ -107,7 +117,13 @@ class TaxonomyReferenceVisitor(TraversingVisitor):and isinstance(node.property.value, str)):self.property_names.append(- TaxonomyReference(node.property.value, node.property.start, node.property.end, fix_context="string")+ TaxonomyReference(+ node.property.value,+ node.property.start,+ node.property.end,+ fix_context="string",+ bracket_access=True,+ ))@@ -141,7 +157,7 @@ def validate_taxonomy_references(if visitor.property_names:property_references = [- reference for reference in visitor.property_names if not _is_dynamic_property(reference.name)+ reference for reference in visitor.property_names if not _is_known_computed_property(reference)]if property_references:warnings.extend(@@ -168,8 +184,18 @@ def _is_properties_field(node: ast.Expr) -> bool:return isinstance(node, ast.Field) and len(node.chain) == 1 and node.chain[0] == "properties"-def _is_dynamic_property(name: str) -> bool:- return any(name.startswith(prefix) for prefix in DYNAMIC_PROPERTY_PREFIXES)+def _is_known_computed_property(reference: TaxonomyReference) -> bool:+ # Properties that legitimately never appear in PropertyDefinition and so must not be flagged as unknown.+ # Dynamic id-encoding prefixes (feature flags, survey ids) are real JSON keys read the same way through+ # dot or bracket access, so they are always exempt. A virtual property is computed at query time, and the+ # resolver only remaps the `properties.<name>` dot form onto the computed top-level field; bracket access+ # (`properties['<name>']`) reads the raw JSON blob, where the virtual value is never stored, so it returns+ # an empty value and must still warn. A typo'd virtual name (e.g. `$virt_trafic_type`) is not in the set,+ # so it also still warns.+ name = reference.name+ if any(name.startswith(prefix) for prefix in DYNAMIC_PROPERTY_PREFIXES):+ return True+ return name in VIRTUAL_EVENT_PROPERTY_NAMES and not reference.bracket_accessdef _event_literal_from_equality(field_node: ast.Expr, value_node: ast.Expr) -> TaxonomyReference | None:diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.pyindex 8438f81c06bf..61e1dd9acfa5 100644--- a/posthog/hogql/test/test_metadata.py+++ b/posthog/hogql/test/test_metadata.py@@ -427,6 +427,54 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):taxonomy_warnings = [warning for warning in metadata.warnings if "project taxonomy" in warning.message]self.assertEqual(taxonomy_warnings, [])+ @parameterized.expand(+ [+ "$virt_traffic_type",+ "$virt_traffic_category",+ "$virt_is_bot",+ "$virt_bot_name",+ "$virt_bot_operator",+ ]+ )+ def test_metadata_does_not_warn_for_virtual_property(self, prop: str):+ # Virtual traffic properties are computed at query time and never stored as PropertyDefinition+ # rows, so the validator must treat them as known — read_taxonomy lists the same set.+ # The unrelated definition is what makes this assertion mean anything: a project with no+ # definitions at all never warns, so without a row here the case passes however the validator behaves.+ PropertyDefinition.objects.create(team=self.team, name="$geoip_country_code")++ metadata = self._select(f"SELECT properties.{prop} FROM events WHERE properties.{prop} = 'x'")++ taxonomy_warnings = [warning for warning in metadata.warnings if "project taxonomy" in warning.message]+ self.assertEqual(taxonomy_warnings, [])++ def test_metadata_warns_for_virtual_property_bracket_access(self):+ # Dot access (`properties.$virt_is_bot`) is remapped by the resolver onto the computed field, but+ # bracket access reads the raw JSON blob, where the virtual value is never stored. So a bracket+ # reference to a virtual property returns an empty value and must still warn, unlike the dot form.+ PropertyDefinition.objects.create(team=self.team, name="$geoip_country_code")++ metadata = self._select("SELECT properties['$virt_is_bot'] FROM events")++ taxonomy_warnings = [warning for warning in metadata.warnings if "project taxonomy" in warning.message]+ self.assertEqual(+ [warning.message for warning in taxonomy_warnings],+ ["Property '$virt_is_bot' was not found in this project taxonomy."],+ )++ def test_metadata_warns_for_unknown_virtual_property(self):+ # A `$virt_`-prefixed name that is not a real virtual property (e.g. a typo) is still unknown,+ # so the warning must state it, rather than the prefix silently passing validation.+ PropertyDefinition.objects.create(team=self.team, name="$geoip_country_code")++ metadata = self._select("SELECT properties.$virt_trafic_type FROM events")++ taxonomy_warnings = [warning for warning in metadata.warnings if "project taxonomy" in warning.message]+ self.assertEqual(+ [warning.message for warning in taxonomy_warnings],+ ["Property '$virt_trafic_type' was not found in this project taxonomy."],+ )+def test_metadata_skips_suggestion_lookup_for_known_event(self):EventDefinition.objects.create(team=self.team, name="paid_bill")diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 085635bb905c..4f0cd7936321 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -4110,3 +4110,20 @@ WELL_KNOWN_EVENT_NAMES: list[str] = sorted(for name, defn in CORE_FILTER_DEFINITIONS_BY_GROUP.get("events", {}).items()if name not in IGNORED_EVENT_NAMES and name != "All events")+++def is_virtual_property(group: str, name: str) -> bool:+ """Whether a property is virtual — computed at query time, never stored as a PropertyDefinition row.++ Single source of truth for both taxonomy listings (read_taxonomy) and HogQL taxonomy validation+ (execute_sql), so the two agree on which `$virt_*` names are known.+ """+ definition = CORE_FILTER_DEFINITIONS_BY_GROUP.get(group, {}).get(name)+ return definition is not None and definition.get("virtual") is True+++def virtual_property_names(group: str) -> frozenset[str]:+ """Names of the group's virtual properties. See `is_virtual_property`."""+ return frozenset(+ name for name in CORE_FILTER_DEFINITIONS_BY_GROUP.get(group, {}) if is_virtual_property(group, name)+ )