: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(settings): tag the gateway spend query with a known product key (#118776)
Brandon5711c71a4190
diff --git a/frontend/src/scenes/settings/project/gatewayKeySpendQuery.ts b/frontend/src/scenes/settings/project/gatewayKeySpendQuery.tsindex 48c62f87d10e..6f09ef75b4e2 100644--- a/frontend/src/scenes/settings/project/gatewayKeySpendQuery.ts+++ b/frontend/src/scenes/settings/project/gatewayKeySpendQuery.ts@@ -1,5 +1,6 @@import api from 'lib/api'+import { ProductKey } from '~/queries/schema/schema-general'import { hogql } from '~/queries/utils'export const GATEWAY_SPEND_WINDOW_DAYS = 30@@ -27,7 +28,7 @@ export async function fetchGatewaySpendByCredential(): Promise<GatewayCredentialORDER BY cost_usd DESCLIMIT 200`,- { scene: 'Settings', productKey: 'ai_gateway', name: 'gateway_spend_by_key' }+ { scene: 'Settings', productKey: ProductKey.AI_OBSERVABILITY, name: 'gateway_spend_by_key' })return (response.results ?? []).map((row: unknown[]) => ({credential: row[0] ? String(row[0]) : null,diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex f9621f2872f1..994a663ae748 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -1720,6 +1720,19 @@ class TestQueryLLMFormatting(ClickhouseTestMixin, APIBaseTest):self.assertEqual(bool(executed_query.dateRange.explicitDate), expected_explicit)+def _latest_log_comment_for_team(team_id: int) -> dict:+ sync_execute("SYSTEM FLUSH LOGS")+ rows = sync_execute(+ "SELECT log_comment FROM system.query_log "+ "WHERE JSONExtractInt(log_comment, 'team_id') = %(team_id)s "+ "AND type = 'QueryFinish' "+ "ORDER BY event_time DESC LIMIT 1",+ {"team_id": team_id},+ )+ assert rows, f"No query_log entry found for team {team_id}"+ return json.loads(rows[0][0])++class TestMcpProductTaggingEndToEnd(ClickhouseTestMixin, APIBaseTest):"""End-to-end tests that an MCP request to the /query endpoint ends up tagged asproduct=mcp in `system.query_log` — *unless* a more specific product was set somewhere@@ -1728,17 +1741,7 @@ class TestMcpProductTaggingEndToEnd(ClickhouseTestMixin, APIBaseTest):ENDPOINT = "query"def _get_log_comment_for_team(self) -> dict:- """Return the log_comment of the most recent QueryFinish entry for this team."""- sync_execute("SYSTEM FLUSH LOGS")- rows = sync_execute(- "SELECT log_comment FROM system.query_log "- "WHERE JSONExtractInt(log_comment, 'team_id') = %(team_id)s "- "AND type = 'QueryFinish' "- "ORDER BY event_time DESC LIMIT 1",- {"team_id": self.team.pk},- )- assert rows, f"No query_log entry found for team {self.team.pk}"- return json.loads(rows[0][0])+ return _latest_log_comment_for_team(self.team.pk)def test_mcp_request_falls_back_to_mcp_when_kind_and_scene_unmapped(self):# Raw HogQLQuery has query_type="hogql_query" (not a NodeKind value) and no scene,@@ -1799,6 +1802,35 @@ class TestMcpProductTaggingEndToEnd(ClickhouseTestMixin, APIBaseTest):self.assertNotEqual(comment.get("product"), Product.MCP.value)+class TestQueryProductTag(ClickhouseTestMixin, APIBaseTest):+ def _post_with_product_key(self, product_key: str):+ return self.client.post(+ f"/api/environments/{self.team.id}/query/",+ {+ "query": {+ "kind": "HogQLQuery",+ "query": "SELECT 1",+ "tags": {"scene": "Settings", "productKey": product_key, "name": "product_tag_test"},+ }+ },+ )++ def test_unknown_product_key_runs_the_query_untagged(self):+ response = self._post_with_product_key("not_a_product")++ self.assertEqual(response.status_code, 200, response.content)+ comment = _latest_log_comment_for_team(self.team.pk)+ self.assertEqual(comment.get("name"), "product_tag_test")+ self.assertNotEqual(comment.get("product"), "not_a_product")++ def test_known_product_key_is_tagged(self):+ response = self._post_with_product_key(Product.LLM_ANALYTICS.value)++ self.assertEqual(response.status_code, 200, response.content)+ comment = _latest_log_comment_for_team(self.team.pk)+ self.assertEqual(comment["product"], Product.LLM_ANALYTICS.value)++class TestQueryCostHeaders(ClickhouseTestMixin, APIBaseTest):def _personal_key_headers(self) -> dict[str, str]:value = generate_random_token_personal()diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 42c74bc82f9d..3bdb116daff6 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -395,6 +395,13 @@ class DagsterTags(BaseModel):asset_key: Optional[str] = None+_PRODUCT_TAG_VALUES = frozenset(member.value for member in Product) | frozenset(member.value for member in ProductKey)+++def is_known_product_tag(value: str) -> bool:+ return value in _PRODUCT_TAG_VALUES++class QueryTags(BaseModel):team_id: Optional[int] = Noneuser_id: Optional[int] = Nonediff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.pyindex 09109769ada4..17b935504a1f 100644--- a/posthog/clickhouse/test/test_query_tagging.py+++ b/posthog/clickhouse/test/test_query_tagging.py@@ -33,6 +33,7 @@ from posthog.clickhouse.query_tagging import (get_query_tag_value,get_query_tags,is_api_key_access_method,+ is_known_product_tag,reset_query_tags,tag_contains_user_hogql,tag_queries,@@ -835,3 +836,15 @@ class TestAddFallbackQueryTags(SimpleTestCase):)def test_is_api_key_access_method(access_method, expected):assert is_api_key_access_method(access_method) is expected+++ [+ ("product_enum", Product.LLM_ANALYTICS.value, True),+ ("product_key_enum", "session_replay", True),+ ("unknown", "ai_gateway", False),+ ("empty", "", False),+ ]+)+def test_is_known_product_tag(_name, value, expected):+ assert is_known_product_tag(value) is expecteddiff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 14453e9f8a3a..752176afb098 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -157,7 +157,12 @@ from posthog.clickhouse.client.limit import (get_app_dashboard_queries_rate_limiter,get_materialized_endpoints_rate_limiter,)-from posthog.clickhouse.query_tagging import get_query_tag_value, is_api_key_access_method, tag_queries+from posthog.clickhouse.query_tagging import (+ get_query_tag_value,+ is_api_key_access_method,+ is_known_product_tag,+ tag_queries,+)from posthog.constants import AvailableFeaturefrom posthog.dataclasses import frozenfrom posthog.errors import QueryErrorCategory, classify_query_error, clickhouse_error_type@@ -2405,7 +2410,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):if tags.productKey:product_key = tags.productKeyposthoganalytics.tag("product_key", product_key)- tag_queries(product=tags.productKey)+ # Client-supplied: an unknown product must not fail the query.+ if is_known_product_tag(product_key):+ tag_queries(product=product_key)if tags.scene:posthoganalytics.tag("scene", tags.scene)tag_queries(scene=tags.scene)