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.

chore(mcp-analytics): retire MCPSession backfill columns from ORM state (#60394)

Georgis Andonis2cfe7047cac1
diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.py
index 9650c058dc48..00848719b9d0 100644
--- a/products/mcp_analytics/backend/intent_clustering.py
+++ b/products/mcp_analytics/backend/intent_clustering.py
@@ -128,13 +128,14 @@ def fetch_intent_corpus(
``intent_by_session`` is exposed so callers can later join session-level
data (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.
+ ``lookback_days`` bounds both stores to the same window: session intent
+ rows are filtered by ``created_at`` (when the intent was generated, since
+ intents are produced on demand), and the joined ClickHouse query filters by
+ event timestamp.
"""
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")
+ MCPSession.objects.filter(team=team, created_at__gte=window_start).values_list("session_id", "intent")
)
if not session_rows:
return [], {}
diff --git a/products/mcp_analytics/backend/migrations/0007_alter_mcpsession_options_and_more.py b/products/mcp_analytics/backend/migrations/0007_alter_mcpsession_options_and_more.py
new file mode 100644
index 000000000000..8a2274538d73
--- /dev/null
+++ b/products/mcp_analytics/backend/migrations/0007_alter_mcpsession_options_and_more.py
@@ -0,0 +1,60 @@
+# Generated by Django 5.2.14 on 2026-05-28 08:40
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ # Phase 1 of a two-phase column drop (see safe-django-migrations.md "Dropping Columns").
+ # These backfill columns are no longer written or read by any code, but dropping them
+ # from the database while old app servers still reference them would break a rolling
+ # deploy and is irreversible. So this migration removes them from Django's model *state*
+ # only — the DB columns and the (team, -session_end) index are retained. A follow-up
+ # migration issues the real DROP COLUMN after this has been deployed for a full cycle.
+
+ dependencies = [
+ ("mcp_analytics", "0006_alter_mcpsession_distinct_id_and_more"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterModelOptions(
+ name="mcpsession",
+ options={"ordering": ["-created_at"]},
+ ),
+ migrations.RemoveIndex(
+ model_name="mcpsession",
+ name="posthog_mcp_team_id_b561f4_idx",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="distinct_id",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="duration_seconds",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="mcp_client_name",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="session_end",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="session_start",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="tool_call_count",
+ ),
+ migrations.RemoveField(
+ model_name="mcpsession",
+ name="tools_used",
+ ),
+ ],
+ database_operations=[],
+ ),
+ ]
diff --git a/products/mcp_analytics/backend/migrations/max_migration.txt b/products/mcp_analytics/backend/migrations/max_migration.txt
index 34e4770f40dd..0cce200ea386 100644
--- a/products/mcp_analytics/backend/migrations/max_migration.txt
+++ b/products/mcp_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0006_alter_mcpsession_distinct_id_and_more
+0007_alter_mcpsession_options_and_more
diff --git a/products/mcp_analytics/backend/models.py b/products/mcp_analytics/backend/models.py
index a6744fb901c4..5fc03bd25d49 100644
--- a/products/mcp_analytics/backend/models.py
+++ b/products/mcp_analytics/backend/models.py
@@ -1,6 +1,5 @@
"""Django models for mcp_analytics."""
-from django.contrib.postgres.fields import ArrayField
from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
@@ -78,17 +77,11 @@ class MCPAnalyticsSubmission(UUIDModel):
class MCPSession(UUIDModel, TeamScopedRootMixin):
+ # On-demand intent store keyed by (team, session_id). The session list itself
+ # is aggregated on the fly from mcp_tool_call events (see logic.py); the
+ # backfill that once populated session_start/_end/duration/etc. is gone.
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
session_id = models.CharField(max_length=64)
-
- session_start = models.DateTimeField(null=True, blank=True)
- session_end = models.DateTimeField(null=True, blank=True)
- duration_seconds = models.IntegerField(null=True, blank=True)
-
- tools_used = ArrayField(models.CharField(max_length=200), default=list, blank=True, null=True)
- tool_call_count = models.IntegerField(default=0, null=True, blank=True)
- distinct_id = models.CharField(max_length=400, blank=True, default="", null=True)
- mcp_client_name = models.CharField(max_length=200, blank=True, default="", null=True)
intent = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
@@ -96,10 +89,7 @@ class MCPSession(UUIDModel, TeamScopedRootMixin):
class Meta:
db_table = "posthog_mcp_session"
- ordering = ["-session_end"]
+ ordering = ["-created_at"]
constraints = [
models.UniqueConstraint(fields=["team", "session_id"], name="unique_mcp_session"),
]
- indexes = [
- models.Index(fields=["team", "-session_end"]),
- ]
diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.py
index 473774ec2620..0e324b61e616 100644
--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py
+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py
@@ -236,18 +236,11 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixi
session_id: str,
intent: str,
*,
- session_end_offset: timedelta = timedelta(minutes=-55),
+ created_at_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=end,
- duration_seconds=300,
- intent=intent,
- )
+ session = MCPSession.objects.create(team=self.team, session_id=session_id, intent=intent)
+ # created_at is auto_now_add, so override it directly to position the row in the lookback window.
+ MCPSession.objects.filter(pk=session.pk).update(created_at=datetime.now(tz=UTC) + created_at_offset)
def _seed_tool_call(self, session_id: str, tool_name: str, is_error: bool = False) -> None:
_create_event(
@@ -302,10 +295,10 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixi
assert records[0].frequency == 1
def test_lookback_days_excludes_sessions_outside_the_window(self) -> None:
- # In-window session (ends ~55 min ago).
+ # In-window session (intent generated ~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))
+ # Out-of-window session (intent generated 10 days ago, beyond the 7-day default).
+ self._seed_session("old", "old intent", created_at_offset=timedelta(days=-10))
records, intent_by_session = fetch_intent_corpus(self.team)
@@ -321,8 +314,8 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixi
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))
+ # Intent generated 10 days ago: excluded at 7 days, included at 30.
+ self._seed_session("old", "old intent", created_at_offset=timedelta(days=-10))
records, _ = fetch_intent_corpus(self.team, lookback_days=lookback_days)