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(query-tagging): resolve product for wrapped and drill-down queries (#63938)

Thomas Obermüllerdd1d8ff01428
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 667d75ec7253..4a0adae5479f 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -638,8 +638,39 @@ _TABLE_TO_TAGS: tuple[tuple[frozenset[str], FallbackTags], ...] = (
)
+def _query_structure_fallback_tags(query: object, max_depth: int = 16) -> FallbackTags | None:
+ """Walk a query's `source` chain to the first node whose kind maps to a product.
+
+ Wrapper / drill-down nodes (DataTableNode, ActorsQuery, InsightActorsQuery, …) map to None in
+ `kind_fallback_tags` — "caller's product is what matters". When one of them runs as the
+ top-level request (e.g. "open as new insight" from an actors modal) there is no caller, so we
+ descend into `source` to find the wrapped insight (e.g. RetentionQuery → product_analytics).
+
+ Reads the canonical `kind` from `tags.query`, so it also resolves runners that pass a non-NodeKind
+ `query_type` label (e.g. marketing analytics' "marketing_analytics_table_query"). Accepts the raw
+ query dict stored on `tags.query` or a pydantic node.
+ """
+ current = query
+ for _ in range(max_depth):
+ if isinstance(current, dict):
+ kind_value, source = current.get("kind"), current.get("source")
+ else:
+ kind_value, source = getattr(current, "kind", None), getattr(current, "source", None)
+ if isinstance(kind_value, str):
+ try:
+ kind = NodeKind(kind_value)
+ except ValueError:
+ kind = None
+ if kind is not None and (mapped := kind_fallback_tags(kind)) is not None:
+ return mapped
+ if source is None:
+ return None
+ current = source
+ return None
+
+
def add_fallback_query_tags(tags: QueryTags) -> None:
- """Order: scene → kind → hogql features (HogQLQuery only) → mcp source. Never overrides set values."""
+ """Order: scene → kind → query structure → hogql features (HogQLQuery only) → mcp source. Never overrides set values."""
if tags.scene and (scene_mapped := SCENE_TO_TAGS.get(tags.scene)) is not None:
_apply_fallback_tags(tags, scene_mapped)
@@ -651,6 +682,10 @@ def add_fallback_query_tags(tags: QueryTags) -> None:
if kind is not None and (kind_mapped := kind_fallback_tags(kind)) is not None:
_apply_fallback_tags(tags, kind_mapped)
+ if tags.product is None and tags.query is not None:
+ if (query_mapped := _query_structure_fallback_tags(tags.query)) is not None:
+ _apply_fallback_tags(tags, query_mapped)
+
if (
tags.product is None
and tags.query_type == NodeKind.HOG_QL_QUERY.value
diff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.py
index c4cab4eb767b..642c56dd7ce5 100644
--- a/posthog/clickhouse/test/test_query_tagging.py
+++ b/posthog/clickhouse/test/test_query_tagging.py
@@ -1,6 +1,7 @@
import json
import uuid
import asyncio
+from types import SimpleNamespace
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin
@@ -696,6 +697,63 @@ class TestAddFallbackQueryTags(BaseTest):
add_fallback_query_tags(tags)
assert tags.product == Product.MCP
+ # --- query-structure fallback: wrapper / drill-down queries inherit the wrapped product ---
+
+ @parameterized.expand(
+ [("RetentionQuery",), ("TrendsQuery",), ("FunnelsQuery",), ("StickinessQuery",), ("LifecycleQuery",)]
+ )
+ def test_query_structure_resolves_actors_drilldowns(self, inner_kind):
+ # "Open as new insight" from an actors modal posts a DataTableNode wrapping an
+ # ActorsQuery → InsightActorsQuery → <insight>. Every outer kind maps to None, so the
+ # product is inherited from the wrapped insight via the query-structure walk.
+ query = {
+ "kind": "DataTableNode",
+ "source": {"kind": "ActorsQuery", "source": {"kind": "InsightActorsQuery", "source": {"kind": inner_kind}}},
+ }
+ tags = QueryTags(query_type="ActorsQuery", query=query)
+ add_fallback_query_tags(tags)
+ assert tags.product == Product.PRODUCT_ANALYTICS
+
+ def test_query_structure_resolves_marketing_analytics_snakecase_query_type(self):
+ # Marketing analytics runners pass a non-NodeKind query_type label ("marketing_analytics_table_query"),
+ # so the query_type fallback can't map it — but tags.query carries the canonical kind.
+ tags = QueryTags(
+ query_type="marketing_analytics_table_query",
+ query={"kind": "MarketingAnalyticsTableQuery"},
+ )
+ add_fallback_query_tags(tags)
+ assert tags.product == Product.MARKETING_ANALYTICS
+
+ def test_query_structure_does_not_override_set_product(self):
+ query = {"kind": "ActorsQuery", "source": {"kind": "InsightActorsQuery", "source": {"kind": "RetentionQuery"}}}
+ tags = QueryTags(product=Product.MCP, query_type="ActorsQuery", query=query)
+ add_fallback_query_tags(tags)
+ assert tags.product == Product.MCP
+
+ def test_query_type_kind_takes_precedence_over_query_structure(self):
+ # query_type maps directly (LogsQuery → logs); the structure walk must not override it.
+ tags = QueryTags(query_type="LogsQuery", query={"kind": "TrendsQuery"})
+ add_fallback_query_tags(tags)
+ assert tags.product == Product.LOGS
+
+ def test_query_structure_leaves_product_none_when_no_inner_kind_maps(self):
+ # A bare ActorsQuery (raw persons drill-down) has no wrapped insight to inherit from.
+ tags = QueryTags(query_type="ActorsQuery", query={"kind": "ActorsQuery", "source": None})
+ add_fallback_query_tags(tags)
+ assert tags.product is None
+
+ def test_query_structure_accepts_pydantic_like_objects(self):
+ # tags.query is usually the raw posted dict, but the walk also reads `.kind` / `.source` attributes.
+ query = SimpleNamespace(
+ kind="ActorsQuery",
+ source=SimpleNamespace(
+ kind="InsightActorsQuery", source=SimpleNamespace(kind="RetentionQuery", source=None)
+ ),
+ )
+ tags = QueryTags(query_type="ActorsQuery", query=query)
+ add_fallback_query_tags(tags)
+ assert tags.product == Product.PRODUCT_ANALYTICS
+
@pytest.mark.parametrize(
"access_method,expected",