: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
chore(mcp-analytics): time-window the intent corpus query (PR1/9) (#59684)
Daniel Visca6184df973db3
diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.pyindex a3e6981387dc..999017573c26 100644--- a/products/mcp_analytics/backend/intent_clustering.py+++ b/products/mcp_analytics/backend/intent_clustering.py@@ -18,8 +18,11 @@ import mathimport asynciofrom collections import Counter, defaultdictfrom dataclasses import dataclass, field+from datetime import timedeltafrom typing import Any+from django.utils import timezone+import numpy as npfrom sklearn.cluster import AgglomerativeClustering@@ -119,8 +122,15 @@ def fetch_intent_corpus(``intent_by_session`` is exposed so callers can later join session-leveldata (e.g. journey aggregation) back to the cluster a session belongs to.++ ``lookback_days`` bounds both stores to the same window: sessions are+ filtered by ``session_end`` (the index on ``(team, -session_end)`` makes+ this cheap), and the joined ClickHouse query filters by event timestamp."""- session_rows = list(MCPSession.objects.filter(team=team).values_list("session_id", "intent"))+ window_start = timezone.now() - timedelta(days=lookback_days)+ session_rows = list(+ MCPSession.objects.filter(team=team, session_end__gte=window_start).values_list("session_id", "intent")+ )if not session_rows:return [], {}diff --git a/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py b/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.pyindex 1968b6a0fa75..030bf2b1d23f 100644--- a/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py+++ b/products/mcp_analytics/backend/management/commands/cluster_mcp_intents.py@@ -21,6 +21,12 @@ class Command(BaseCommand):def add_arguments(self, parser: CommandParser) -> None:parser.add_argument("--team-id", type=int, required=True, help="Team ID to cluster intents for.")+ parser.add_argument(+ "--lookback-days",+ type=int,+ default=None,+ help="Window for both the session and ClickHouse queries. Default uses the task default (7 days).",+ )parser.add_argument("--raw",action="store_true",@@ -29,6 +35,7 @@ class Command(BaseCommand):def handle(self, *args: Any, **options: Any) -> None:team_id: int = options["team_id"]+ lookback_days: int | None = options["lookback_days"]raw: bool = options["raw"]try:@@ -37,8 +44,9 @@ class Command(BaseCommand):self.stderr.write(self.style.ERROR(f"Team {team_id} does not exist."))return- self.stdout.write(f"Running intent clustering for team {team_id}...")- compute_intent_clusters.apply(args=[team_id, None]).get()+ window_label = f"{lookback_days} day(s)" if lookback_days is not None else "default window"+ self.stdout.write(f"Running intent clustering for team {team_id} ({window_label})...")+ compute_intent_clusters.apply(args=[team_id, None, lookback_days]).get()with team_scope(team_id):snapshot = MCPIntentClusterSnapshot.objects.filter(team_id=team_id).first()diff --git a/products/mcp_analytics/backend/tasks/tasks.py b/products/mcp_analytics/backend/tasks/tasks.pyindex 69a8de3135ac..68fa2f9e3b2b 100644--- a/products/mcp_analytics/backend/tasks/tasks.py+++ b/products/mcp_analytics/backend/tasks/tasks.py@@ -27,7 +27,9 @@ logger = structlog.get_logger(__name__)max_retries=2,)@with_team_scope()-def compute_intent_clusters(self: Any, team_id: int, user_id: int | None = None) -> None:+def compute_intent_clusters(+ self: Any, team_id: int, user_id: int | None = None, lookback_days: int | None = None+) -> None:"""Recompute the intent cluster snapshot for a team.Flow:@@ -35,6 +37,9 @@ def compute_intent_clusters(self: Any, team_id: int, user_id: int | None = None)2. Fetch the intent corpus, embed it, cluster it, build the snapshot.3. Persist the snapshot atomically and mark ``idle``.4. On failure, mark ``error`` with the message; rely on Celery retry.++ ``lookback_days`` overrides the default window used by both the Postgres+ session query and the joined ClickHouse query. ``None`` keeps the default."""# Imports inside the task so Celery autoimport doesn't pull heavy deps# (numpy/sklearn/httpx) at worker startup.@@ -64,8 +69,12 @@ def compute_intent_clusters(self: Any, team_id: int, user_id: int | None = None)},)+ corpus_kwargs: dict[str, int] = {}+ if lookback_days is not None:+ corpus_kwargs["lookback_days"] = lookback_days+try:- records, intent_by_session = intent_clustering.fetch_intent_corpus(team)+ records, intent_by_session = intent_clustering.fetch_intent_corpus(team, **corpus_kwargs)if not records:_save_empty_snapshot(snapshot)logger.info("mcp_analytics.intent_clusters.no_intents_found", team_id=team_id)@@ -82,7 +91,9 @@ def compute_intent_clusters(self: Any, team_id: int, user_id: int | None = None)# Fetch ordered tool-call sequences for every session and aggregate# them per cluster so the UI can render a Sankey of agent journeys.- session_journeys = intent_clustering.fetch_session_journeys(team, list(intent_by_session.keys()))+ session_journeys = intent_clustering.fetch_session_journeys(+ team, list(intent_by_session.keys()), **corpus_kwargs+ )intent_to_sessions: dict[str, list[str]] = {}for sid, intent_text in intent_by_session.items():intent_to_sessions.setdefault(intent_text, []).append(sid)diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.pyindex 60d494057f85..0d783046b956 100644--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py@@ -13,6 +13,7 @@ import pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsimport numpy as np+from parameterized import parameterizedfrom products.mcp_analytics.backend.intent_clustering import (DEFAULT_DISTANCE_THRESHOLD,@@ -229,13 +230,20 @@ class TestBuildSnapshot:class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, BaseTest):"""End-to-end: posthog_mcp_session in Postgres + mcp_tool_call in ClickHouse."""- def _seed_session(self, session_id: str, intent: str) -> None:- start = datetime.now(tz=UTC) - timedelta(hours=1)+ def _seed_session(+ self,+ session_id: str,+ intent: str,+ *,+ session_end_offset: timedelta = timedelta(minutes=-55),+ ) -> None:+ end = datetime.now(tz=UTC) + session_end_offset+ start = end - timedelta(minutes=5)MCPSession.objects.create(team=self.team,session_id=session_id,session_start=start,- session_end=start + timedelta(minutes=5),+ session_end=end,duration_seconds=300,intent=intent,)@@ -291,3 +299,30 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixiassert records[0].intent_text == "quiet intent with no events"assert records[0].tool_counts == {}assert records[0].frequency == 1++ def test_lookback_days_excludes_sessions_outside_the_window(self) -> None:+ # In-window session (ends ~55 min ago).+ self._seed_session("recent", "recent intent")+ # Out-of-window session (ends 10 days ago, beyond the 7-day default).+ self._seed_session("old", "old intent", session_end_offset=timedelta(days=-10))++ records, intent_by_session = fetch_intent_corpus(self.team)++ assert {r.intent_text for r in records} == {"recent intent"}+ assert intent_by_session == {"recent": "recent intent"}++ @parameterized.expand(+ [+ ("default_7_excludes_old", 7, []),+ ("override_30_includes_old", 30, ["old intent"]),+ ]+ )+ def test_lookback_days_argument_is_respected(+ self, _name: str, lookback_days: int, expected_intents: list[str]+ ) -> None:+ # Session ends 10 days ago: excluded at 7 days, included at 30.+ self._seed_session("old", "old intent", session_end_offset=timedelta(days=-10))++ records, _ = fetch_intent_corpus(self.team, lookback_days=lookback_days)++ assert [r.intent_text for r in records] == expected_intents