: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(mcp-analytics): skeleton activity summary, parallelize its queries (#101274)
Mike Warrenfb95ed97d871
diff --git a/posthog/hogql_queries/utils/caller_context.py b/posthog/hogql_queries/utils/caller_context.pynew file mode 100644index 000000000000..9e2fbd3fe6c7--- /dev/null+++ b/posthog/hogql_queries/utils/caller_context.py@@ -0,0 +1,48 @@+import contextvars+from collections.abc import Callable, Sequence+from concurrent.futures import ThreadPoolExecutor+from typing import TypeVar++from django.db import connections++from posthog.settings import TEST++_T = TypeVar("_T")+_R = TypeVar("_R")++# Each worker may hold a Postgres connection while HogQL resolves team and property-definition+# rows; 8 keeps one request comfortably below the per-process pool while still collapsing wall+# time for the common few-item case. Bump only after measuring PG pressure under real concurrency.+DEFAULT_PARALLELISM_LIMIT = 8+++def map_in_caller_context(+ fn: Callable[[_T], _R],+ items: Sequence[_T],+ *,+ max_workers: int = DEFAULT_PARALLELISM_LIMIT,+ thread_name_prefix: str = "caller_context",+) -> list[_R]:+ """`pool.map` each item in a thread pool, with the caller's contextvars carried into the workers.++ `ThreadPoolExecutor` workers don't inherit the submitting thread's contextvars, so the query tags+ (team_id, feature, trigger) set on the read path would be lost inside the pool, silently un-tagging+ every ClickHouse query the workers emit. A Context can't be entered concurrently, so each worker+ gets its own copy. Workers release their Postgres connection on the way out, since pool threads+ end with the call and Django connections are per thread.++ Runs serially under TEST: a worker's own Django connection can't see the test transaction's+ uncommitted rows, so it would resolve against an empty team.+ """+ if TEST or len(items) <= 1:+ return [fn(item) for item in items]++ def run(ctx: contextvars.Context, item: _T) -> _R:+ try:+ return ctx.run(fn, item)+ finally:+ connections.close_all()++ contexts = [contextvars.copy_context() for _ in items]+ with ThreadPoolExecutor(max_workers=min(len(items), max_workers), thread_name_prefix=thread_name_prefix) as pool:+ return list(pool.map(run, contexts, items))diff --git a/posthog/hogql_queries/utils/test/test_caller_context.py b/posthog/hogql_queries/utils/test/test_caller_context.pynew file mode 100644index 000000000000..3a2a99ae9790--- /dev/null+++ b/posthog/hogql_queries/utils/test/test_caller_context.py@@ -0,0 +1,26 @@+from unittest.mock import patch++from django.test import SimpleTestCase++from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset_query_tags, tag_queries+from posthog.hogql_queries.utils.caller_context import map_in_caller_context+++class TestMapInCallerContext(SimpleTestCase):+ def tearDown(self):+ reset_query_tags()+ super().tearDown()++ @patch("posthog.hogql_queries.utils.caller_context.TEST", False)+ def test_query_tags_survive_into_the_worker_threads(self):+ tag_queries(feature=Feature.CACHE_WARMUP, trigger="staleRevalidation")+ seen: dict[int, tuple] = {}++ def build(item: int) -> int:+ seen[item] = (get_query_tag_value("feature"), get_query_tag_value("trigger"))+ return item * 10++ result = map_in_caller_context(build, [1, 2, 3])++ assert result == [10, 20, 30]+ assert all(tags == (Feature.CACHE_WARMUP, "staleRevalidation") for tags in seen.values()), seendiff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.pyindex 25770949b093..a91557d72c2a 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goals_aggregator.py@@ -1,14 +1,9 @@-import contextvars-from collections.abc import Callable-from concurrent.futures import ThreadPoolExecutor-from typing import TypeVar-from posthog.schema import MarketingAnalyticsBaseColumns, MarketingAnalyticsDrillDownLevelfrom posthog.hogql import ast+from posthog.hogql_queries.utils.caller_context import map_in_caller_contextfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.settings import TESTfrom products.marketing_analytics.backend.hogql_queries.constants import (CAC_COLUMN_SUFFIX,@@ -21,33 +16,6 @@ from .adapters.factory import MarketingSourceFactoryfrom .conversion_goal_processor import ConversionGoalProcessor, SharedTouchpointsPrecomputefrom .marketing_analytics_config import MarketingAnalyticsConfig-# Cap on parallel per-goal ensure_precomputed workers.-# Each worker holds a Postgres connection during the round-trip; 8 keeps us comfortably-# below the per-process pool while still collapsing wall time for the common 1–4 goal-# case. Bump only after measuring PG/Redis pressure under realistic concurrency.-_GOAL_PARALLELISM_LIMIT = 8--_T = TypeVar("_T")-_R = TypeVar("_R")---def _map_in_caller_context(build: Callable[[_T], _R], items: list[_T]) -> list[_R]:- """`pool.map` each item, but with the caller's contextvars carried into the worker threads.-- `ThreadPoolExecutor` workers don't inherit the submitting thread's contextvars, so the query tags- (team_id, feature, trigger) set on the read path would be lost inside the pool — silently un-tagging- every ClickHouse query these goals emit, and breaking serve-stale: a background revalidation tags its- own ensures CACHE_WARMUP so they skip the grace and actually recompute, and dropping that tag makes- the revalidation serve itself stale and never refresh. A Context can't be entered concurrently, so- each worker gets its own copy.- """- contexts = [contextvars.copy_context() for _ in items]- with ThreadPoolExecutor(- max_workers=min(len(items), _GOAL_PARALLELISM_LIMIT),- thread_name_prefix="ma_cte",- ) as pool:- return list(pool.map(lambda ctx, item: ctx.run(build, item), contexts, items))-class ConversionGoalsAggregator:"""@@ -94,12 +62,10 @@ class ConversionGoalsAggregator:touchpoints=touchpoints,)- # Skip the pool in TEST: Django's per-thread DB connections don't see- # fixtures created in the main test thread.- if not TEST and len(self.processors) > 1:- base_queries = _map_in_caller_context(_build_base_query, self.processors)- else:- base_queries = [_build_base_query(p) for p in self.processors]+ # The caller's query tags must reach the workers: a background revalidation tags its own+ # ensures CACHE_WARMUP so they skip the grace and actually recompute, and dropping that tag+ # would make the revalidation serve itself stale and never refresh.+ base_queries = map_in_caller_context(_build_base_query, self.processors, thread_name_prefix="ma_cte")count_processors = self._count_processors()diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.pyindex 6283c86481d8..341c5e68ed2a 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goals_aggregator.py@@ -7,8 +7,6 @@ import pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import patch-from django.test import SimpleTestCase-from posthog.schema import (BaseMathType,ConversionGoalFilter1,@@ -24,7 +22,6 @@ from posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.clickhouse.client.execute import sync_executefrom posthog.clickhouse.preaggregation.marketing_touchpoints_sql import TRUNCATE_MARKETING_TOUCHPOINTS_TABLE_SQL-from posthog.clickhouse.query_tagging import Feature, get_query_tag_value, reset_query_tags, tag_queriesfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.actions.backend.models.action import Action@@ -36,7 +33,7 @@ from products.analytics_platform.backend.models.preaggregation_job import Preaggfrom .constants import CAC_COLUMN_SUFFIX, ROAS_COLUMNfrom .conversion_goal_processor import ConversionGoalProcessor, SharedTouchpointsPrecompute-from .conversion_goals_aggregator import ConversionGoalsAggregator, _map_in_caller_context+from .conversion_goals_aggregator import ConversionGoalsAggregatorfrom .marketing_analytics_config import MarketingAnalyticsConfig@@ -822,29 +819,3 @@ class TestConversionGoalsAggregator(ClickhouseTestMixin, BaseTest):shared.get(date_from, date_to + timedelta(days=1))assert ensure.call_count == 1---class TestGoalParallelismContextPropagation(SimpleTestCase):- def tearDown(self):- reset_query_tags()- super().tearDown()-- def test_query_tags_survive_into_the_goal_worker_threads(self):- # Multi-goal reads build each goal's precompute in a thread pool. ThreadPoolExecutor workers do- # not inherit the caller's contextvars, so a bare pool.map drops the query tags — and with them- # the CACHE_WARMUP tag a background revalidation sets on itself, which is the only thing stopping- # that revalidation from serving itself stale and never refreshing. Guards that regression.- tag_queries(feature=Feature.CACHE_WARMUP, trigger="marketingAnalyticsStaleRevalidation")- seen: dict[int, tuple] = {}-- def build(item: int) -> int:- seen[item] = (get_query_tag_value("feature"), get_query_tag_value("trigger"))- return item * 10-- # 3 items > 1 forces the real pool rather than the serial path.- result = _map_in_caller_context(build, [1, 2, 3])-- assert result == [10, 20, 30]- assert all(tags == (Feature.CACHE_WARMUP, "marketingAnalyticsStaleRevalidation") for tags in seen.values()), (- seen- )diff --git a/products/mcp_analytics/backend/logic.py b/products/mcp_analytics/backend/logic.pyindex 02a17165bf52..5bb843953ebc 100644--- a/products/mcp_analytics/backend/logic.py+++ b/products/mcp_analytics/backend/logic.py@@ -15,6 +15,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.hogql_queries.utils.caller_context import map_in_caller_contextfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.person import Personfrom posthog.models.person.util import get_persons_mapped_by_distinct_id@@ -559,20 +560,58 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:Always computed fresh: the view's whole point is watching data arrive, so callerspoll this endpoint rather than a stale cache.++ The four queries are independent, so they run concurrently. Served serially their+ latency summed, which left the summary sentence landing long after the live feed+ below it had rendered — the feed's own total is an index-only ``count()``, while+ every query here reads properties across the whole window."""date_from = ast.Constant(value=timezone.now() - ACTIVITY_WINDOW)tool_call_event = ast.Constant(value=MCP_TOOL_CALL_EVENT)- stats_rows = _run_activity_query(- team,- _ACTIVITY_STATS_SQL,- "mcp_analytics_activity_stats",- {- "tool_call_event": tool_call_event,- "missing_capability_event": ast.Constant(value=MCP_MISSING_CAPABILITY_EVENT),- "date_from": date_from,- },+ stats_rows, top_tools_rows, clients_rows, recent_calls_rows = map_in_caller_context(+ lambda spec: _run_activity_query(team, *spec),+ [+ (+ _ACTIVITY_STATS_SQL,+ "mcp_analytics_activity_stats",+ {+ "tool_call_event": tool_call_event,+ "missing_capability_event": ast.Constant(value=MCP_MISSING_CAPABILITY_EVENT),+ "date_from": date_from,+ },+ ),+ (+ _ACTIVITY_TOP_TOOLS_SQL,+ "mcp_analytics_activity_top_tools",+ {+ "tool_call_event": tool_call_event,+ "date_from": date_from,+ "limit": ast.Constant(value=ACTIVITY_TOP_TOOLS_LIMIT),+ },+ ),+ (+ _ACTIVITY_CLIENTS_SQL,+ "mcp_analytics_activity_clients",+ {+ "tool_call_event": tool_call_event,+ "date_from": date_from,+ "limit": ast.Constant(value=ACTIVITY_CLIENTS_LIMIT),+ },+ ),+ (+ _ACTIVITY_RECENT_CALLS_SQL,+ "mcp_analytics_activity_recent_calls",+ {+ "tool_call_event": tool_call_event,+ "date_from": date_from,+ "limit": ast.Constant(value=ACTIVITY_RECENT_CALLS_LIMIT),+ },+ ),+ ],+ thread_name_prefix="mcp_activity",)+stats_row = stats_rows[0] if stats_rows else [0] * 7stats = contracts.ActivityStats(total_calls=_parse_int(stats_row[0]) or 0,@@ -586,30 +625,12 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:top_tools = [contracts.ActivityToolRow(tool=str(row[0] or ""), calls=_parse_int(row[1]) or 0, errors=_parse_int(row[2]) or 0)- for row in _run_activity_query(- team,- _ACTIVITY_TOP_TOOLS_SQL,- "mcp_analytics_activity_top_tools",- {- "tool_call_event": tool_call_event,- "date_from": date_from,- "limit": ast.Constant(value=ACTIVITY_TOP_TOOLS_LIMIT),- },- )+ for row in top_tools_rows]clients = [contracts.ActivityClientRow(client=str(row[0]) if row[0] else "", calls=_parse_int(row[1]) or 0)- for row in _run_activity_query(- team,- _ACTIVITY_CLIENTS_SQL,- "mcp_analytics_activity_clients",- {- "tool_call_event": tool_call_event,- "date_from": date_from,- "limit": ast.Constant(value=ACTIVITY_CLIENTS_LIMIT),- },- )+ for row in clients_rows]recent_calls = [@@ -622,16 +643,7 @@ def get_activity_overview(team: Team) -> contracts.ActivityOverview:duration_ms=float(row[5]) if row[5] is not None else None,client_name=str(row[6]) if row[6] else None,)- for row in _run_activity_query(- team,- _ACTIVITY_RECENT_CALLS_SQL,- "mcp_analytics_activity_recent_calls",- {- "tool_call_event": tool_call_event,- "date_from": date_from,- "limit": ast.Constant(value=ACTIVITY_RECENT_CALLS_LIMIT),- },- )+ for row in recent_calls_rows]return contracts.ActivityOverview(stats=stats, top_tools=top_tools, clients=clients, recent_calls=recent_calls)diff --git a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsxindex 6e3193d6fd5e..ddb2d67f94f9 100644--- a/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx+++ b/products/mcp_analytics/frontend/earlyData/MCPAnalyticsEarlyData.tsx@@ -54,14 +54,23 @@ export function MCPAnalyticsActivityDashboard(): JSX.Element {function SummaryCard(): JSX.Element {const { dashboardStage } = useValues(mcpAnalyticsOnboardingLogic)- const { summary } = useValues(mcpEarlyDataLogic)+ const { summary, overview, overviewLoading } = useValues(mcpEarlyDataLogic)+ // The sentence is derived from the overview, and an absent overview reads as zero calls —+ // so the first load would claim "No tool calls in the last 30 days" until the numbers+ // arrive. Only the first load skeletons: the 60s refresh keeps the sentence it already has+ // rather than flashing back to a placeholder every minute.+ const awaitingFirstOverview = overviewLoading && !overviewreturn (<LemonBanner type="info" dismissKey="mcp-analytics-activity-summary" hideIcon><div className="flex items-center gap-3 py-1"><HedgehogExplorer className="h-14 w-14 shrink-0 hidden sm:block" /><div className="min-w-0">- <h3 className="text-lg font-semibold m-0">{summary}</h3>+ {awaitingFirstOverview ? (+ <LemonSkeleton className="h-6 w-80 max-w-full my-1" />+ ) : (+ <h3 className="text-lg font-semibold m-0">{summary}</h3>+ )}<p className="text-muted text-base m-0 mt-1">This view fills in live as agents use your server.{dashboardStage === 'activity' ? (