: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
feat(mcp-analytics): cache intent embeddings by content hash (PR3/9) (#59686)
Daniel Visca66ae263f13f1
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 31532a438f74..ddc8435e6dd1 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -167,6 +167,7 @@ rules:|MessageTemplate|MCPAnalyticsSubmission|MCPIntentClusterSnapshot+ |MCPIntentEmbeddingCache|MCPSession|OptOutSyncConfig|Node@@ -395,6 +396,7 @@ rules:|MessageRecipientPreference|MessageTemplate|MCPIntentClusterSnapshot+ |MCPIntentEmbeddingCache|MCPSession|OptOutSyncConfig|Nodediff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.pyindex 00848719b9d0..31d1ef1129a1 100644--- a/products/mcp_analytics/backend/intent_clustering.py+++ b/products/mcp_analytics/backend/intent_clustering.py@@ -16,6 +16,7 @@ to change when that table lands — swap its body to read from the new source.import mathimport asyncio+import hashlibfrom collections import Counter, defaultdictfrom dataclasses import dataclass, fieldfrom datetime import timedelta@@ -33,8 +34,9 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.api.embedding_worker import EmbeddingResponse, async_generate_embeddingfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team.team import Team+from posthog.sync import database_sync_to_async-from products.mcp_analytics.backend.models import MCPSession+from products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSession# ConstantsEMBEDDING_MODEL = "text-embedding-3-small-1536"@@ -49,6 +51,14 @@ MAX_SAMPLE_INTENTS_PER_CLUSTER = 3# meaningless pseudo-cluster of "empty" sessions.NO_INTENT_RECORDED_FALLBACK = "No agent intent was recorded for this session."+# Embedding cache + concurrency+# 1536-d float32 embedding = 6144 bytes. 500-intent corpus × 6144 ≈ 3 MB/team.+# Cap concurrent embedding worker requests so we don't dogpile when a team's+# corpus has hundreds of misses on first run. 20 matches the trace_clustering+# precedent (SENTIMENT_MAX_CONCURRENT) and stays well under any per-team+# rate limit on the embedding provider.+EMBED_CONCURRENCY = 20+# How many tool-call steps to show in the per-cluster Sankey before the# outcome column. Sessions with fewer steps pad with None so the column# count stays fixed; the UI renders those as an "Ended" node.@@ -295,38 +305,122 @@ def aggregate_journeys_per_cluster(# Embeddings ---------------------------------------------------------------async def _embed_one(team: Team, text: str) -> EmbeddingResponse | None:+def _content_hash(text: str) -> str:+ """SHA-256 of the prefixed text — what we actually embed."""+ return hashlib.sha256((EMBEDDING_PREFIX + text).encode("utf-8")).hexdigest()+++def _encode_embedding(vector: list[float]) -> bytes:+ """Encode an embedding to compact bytes for cache storage."""+ return np.asarray(vector, dtype=np.float32).tobytes()+++def _decode_embedding(blob: bytes) -> np.ndarray:+ """Decode cached bytes back into a 1-D float32 vector."""+ return np.frombuffer(blob, dtype=np.float32)+++@database_sync_to_async+def _load_cached_embeddings(team: Team, hashes: list[str], model: str) -> dict[str, np.ndarray]:+ """Return ``{content_hash: embedding}`` for cache hits."""+ if not hashes:+ return {}+ rows = MCPIntentEmbeddingCache.objects.filter(+ team=team,+ content_hash__in=hashes,+ model=model,+ ).values_list("content_hash", "embedding")+ return {content_hash: _decode_embedding(bytes(blob)) for content_hash, blob in rows}+++@database_sync_to_async+def _persist_embedding(team: Team, content_hash: str, model: str, vector: list[float]) -> None:+ """Insert (or no-op) a single cache row. Concurrent identical inserts are tolerated.++ Uses ``get_or_create`` rather than ``update_or_create`` because the content hash+ deterministically maps to the embedding bytes — there is nothing to update if the+ row already exists. ``get_or_create`` avoids the spurious UPDATE that+ ``update_or_create`` would issue on a creation race.+ """+ MCPIntentEmbeddingCache.objects.get_or_create(+ team=team,+ content_hash=content_hash,+ model=model,+ defaults={"embedding": _encode_embedding(vector)},+ )+++async def _embed_one_with_cache(+ team: Team,+ text: str,+ content_hash: str,+ semaphore: asyncio.Semaphore,+ cached: dict[str, np.ndarray],+) -> np.ndarray | None:+ """Return the embedding for ``text``, hitting the cache when possible.++ Concurrency is bounded by ``semaphore``; cache reads come pre-loaded in+ ``cached`` so the hot path is a dict lookup. Misses go through+ ``async_generate_embedding`` and write back on success.+ """+ hit = cached.get(content_hash)+ if hit is not None:+ return hit+ async with semaphore:+ try:+ response: EmbeddingResponse = await async_generate_embedding(+ team, EMBEDDING_PREFIX + text, model=EMBEDDING_MODEL+ )+ except Exception:+ return Nonetry:- return await async_generate_embedding(team, EMBEDDING_PREFIX + text, model=EMBEDDING_MODEL)+ await _persist_embedding(team, content_hash, EMBEDDING_MODEL, response.embedding)except Exception:- return None+ # A concurrent insert for the same (team, hash, model) is fine —+ # the unique constraint guarantees the row exists. Don't fail the+ # whole batch over a race.+ pass+ return np.asarray(response.embedding, dtype=np.float32)async def embed_intents_async(team: Team, texts: list[str]) -> tuple[np.ndarray, list[int]]:- """Embed a list of intent texts concurrently.+ """Embed a list of intent texts concurrently, with a per-team cache.Returns (embeddings, valid_indices) where ``valid_indices`` are the indicesinto ``texts`` for which embedding succeeded. Skipped indices have no rowin the returned matrix. Callers must align downstream data structures with``valid_indices``.++ Cache key is ``(team, sha256(prefix + text), model)``. Hits return the+ stored bytes; misses call the embedding worker and write back. Worker+ concurrency is capped at ``EMBED_CONCURRENCY``."""if not texts:return np.zeros((0, 0), dtype=np.float32), []- responses = await asyncio.gather(*[_embed_one(team, t) for t in texts])+ hashes = [_content_hash(t) for t in texts]+ cached = await _load_cached_embeddings(team, hashes, EMBEDDING_MODEL)+ semaphore = asyncio.Semaphore(EMBED_CONCURRENCY)++ results = await asyncio.gather(+ *[+ _embed_one_with_cache(team, text, content_hash, semaphore, cached)+ for text, content_hash in zip(texts, hashes)+ ]+ )- vectors: list[list[float]] = []+ vectors: list[np.ndarray] = []valid_indices: list[int] = []- for i, response in enumerate(responses):- if response is None:+ for i, vector in enumerate(results):+ if vector is None:continue- vectors.append(response.embedding)+ vectors.append(vector)valid_indices.append(i)if not vectors:return np.zeros((0, 0), dtype=np.float32), []- return np.asarray(vectors, dtype=np.float32), valid_indices+ return np.stack(vectors).astype(np.float32, copy=False), valid_indices# Clustering --------------------------------------------------------------diff --git a/products/mcp_analytics/backend/migrations/0009_mcpintentembeddingcache.py b/products/mcp_analytics/backend/migrations/0009_mcpintentembeddingcache.pynew file mode 100644index 000000000000..1078f33c4eed--- /dev/null+++ b/products/mcp_analytics/backend/migrations/0009_mcpintentembeddingcache.py@@ -0,0 +1,48 @@+# Generated by Django 5.2.14 on 2026-05-21 23:01++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("mcp_analytics", "0008_drop_mcpsession_backfill_columns"),+ ("posthog", "1171_backfill_credentials_reviewed_at"),+ ]++ operations = [+ migrations.CreateModel(+ name="MCPIntentEmbeddingCache",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("content_hash", models.CharField(max_length=64)),+ ("model", models.CharField(max_length=64)),+ ("embedding", models.BinaryField()),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_mcp_analytics_intent_embedding_cache",+ "indexes": [models.Index(fields=["team", "created_at"], name="posthog_mcp_team_id_31d8c1_idx")],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "content_hash", "model"),+ name="unique_mcp_intent_embedding_cache",+ )+ ],+ },+ ),+ ]diff --git a/products/mcp_analytics/backend/migrations/max_migration.txt b/products/mcp_analytics/backend/migrations/max_migration.txtindex 09ecb97d2440..a46117201e53 100644--- a/products/mcp_analytics/backend/migrations/max_migration.txt+++ b/products/mcp_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_drop_mcpsession_backfill_columns+0009_mcpintentembeddingcachediff --git a/products/mcp_analytics/backend/models.py b/products/mcp_analytics/backend/models.pyindex 5fc03bd25d49..533560ca173a 100644--- a/products/mcp_analytics/backend/models.py+++ b/products/mcp_analytics/backend/models.py@@ -76,6 +76,38 @@ class MCPAnalyticsSubmission(UUIDModel):]+class MCPIntentEmbeddingCache(UUIDModel, TeamScopedRootMixin):+ """Content-addressable embedding cache for intent clustering.++ Keyed on ``(team, content_hash, model)``: same text re-embedded with the+ same model returns the cached bytes. Embeddings are stored as raw+ little-endian float32 bytes — vector arithmetic happens in numpy, never+ in Postgres, so a typed Postgres array buys us nothing.+ """++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ content_hash = models.CharField(max_length=64)+ model = models.CharField(max_length=64)+ embedding = models.BinaryField()++ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ db_table = "posthog_mcp_analytics_intent_embedding_cache"+ constraints = [+ models.UniqueConstraint(+ fields=["team", "content_hash", "model"],+ name="unique_mcp_intent_embedding_cache",+ ),+ ]+ indexes = [+ # Drives the (per-team) TTL sweep activity. Composite (team, created_at)+ # so Postgres can skip directly to a team's rows instead of a global+ # index scan-then-filter.+ models.Index(fields=["team", "created_at"]),+ ]++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); thediff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.pyindex 0e324b61e616..ee2dfd121527 100644--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py@@ -7,25 +7,36 @@ shape we promise the frontend.import mathimport uuid+import asynciofrom datetime import UTC, datetime, timedelta+from typing import Anyimport pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events+from unittest.mock import patchimport numpy as npfrom parameterized import parameterized+from posthog.api.embedding_worker import EmbeddingResponse++from products.mcp_analytics.backend import intent_clusteringfrom products.mcp_analytics.backend.intent_clustering import (DEFAULT_DISTANCE_THRESHOLD,+ EMBEDDING_MODEL,NO_INTENT_RECORDED_FALLBACK,IntentRecord,+ _content_hash,+ _decode_embedding,+ _encode_embedding,_medoid_index,_routing_entropy,build_snapshot,cluster_embeddings,+ embed_intents_async,fetch_intent_corpus,)-from products.mcp_analytics.backend.models import MCPSession+from products.mcp_analytics.backend.models import MCPIntentEmbeddingCache, MCPSessionfrom products.mcp_analytics.backend.tests import _MCPAnalyticsTeamScopedTestMixin# Helpers@@ -338,3 +349,171 @@ class TestFetchIntentCorpus(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixiassert [r.intent_text for r in records] == ["look up feature flag rollout"]assert intent_by_session == {"real": "look up feature flag rollout"}+++# Embedding helpers -----------------------------------------------------+++class TestEmbeddingHelpers:+ def test_content_hash_includes_prefix(self) -> None:+ # The prefix is what we actually embed, so the hash must include it.+ assert _content_hash("hello") != _content_hash("ello")+ assert _content_hash("hello") == _content_hash("hello") # stable++ def test_encode_decode_round_trips_to_float32(self) -> None:+ vec = [0.1, -0.2, 0.5, 1.5e-3]+ blob = _encode_embedding(vec)+ decoded = _decode_embedding(blob)+ assert decoded.dtype == np.float32+ assert np.allclose(decoded, np.asarray(vec, dtype=np.float32))+++# embed_intents_async (cache integration, mocked ORM) ------------------------+++def _fake_embedding(text: str) -> EmbeddingResponse:+ seed = int.from_bytes(text.encode("utf-8")[:4].ljust(4, b"\x00"), "little")+ rng = np.random.default_rng(seed)+ vec = rng.standard_normal(1536).astype(np.float32)+ vec /= np.linalg.norm(vec)+ return EmbeddingResponse(embedding=vec.tolist(), tokens_used=0, did_truncate=False)+++class TestEmbedIntentsAsyncCacheLogic:+ """Cache hit/miss logic with the Postgres helpers mocked.++ The ORM round-trip is covered separately by ``TestEmbeddingCacheModel``+ so the async logic can be exercised without TransactionTestCase setup —+ mirrors the pattern in ``test_tasks.py`` (mock the IO, assert the call+ shape).+ """++ @staticmethod+ def _call(texts: list[str], cached: dict[str, np.ndarray], worker: Any) -> tuple[np.ndarray, list[int]]:+ async def _load(team, hashes, model): # noqa: ARG001+ return cached++ async def _persist(team, content_hash, model, vector): # noqa: ARG001+ cached[content_hash] = np.asarray(vector, dtype=np.float32)++ with (+ patch.object(intent_clustering, "_load_cached_embeddings", side_effect=_load),+ patch.object(intent_clustering, "_persist_embedding", side_effect=_persist),+ patch.object(intent_clustering, "async_generate_embedding", side_effect=worker),+ ):+ return asyncio.run(embed_intents_async(object(), texts)) # type: ignore[arg-type]++ def test_first_run_populates_cache(self) -> None:+ cached: dict[str, np.ndarray] = {}++ async def _fake_call(_team, text, model): # noqa: ARG001+ return _fake_embedding(text)++ embeddings, valid_indices = self._call(["intent A", "intent B"], cached, _fake_call)++ assert embeddings.shape == (2, 1536)+ assert valid_indices == [0, 1]+ # Both intents persisted into the cache.+ assert set(cached.keys()) == {_content_hash("intent A"), _content_hash("intent B")}++ def test_full_cache_hit_skips_worker(self) -> None:+ # Pre-populate the cache with both intents.+ cached = {_content_hash(t): np.asarray(_fake_embedding(t).embedding, dtype=np.float32) for t in ("a", "b")}++ async def _explode(_team, _text, model): # noqa: ARG001+ raise AssertionError("worker must not be called on cache hit")++ embeddings, valid_indices = self._call(["a", "b"], cached, _explode)++ assert valid_indices == [0, 1]+ assert embeddings.shape == (2, 1536)++ def test_partial_cache_only_embeds_missing(self) -> None:+ cached = {_content_hash("a"): np.asarray(_fake_embedding("a").embedding, dtype=np.float32)}+ worker_calls: list[str] = []++ async def _fake_call(_team, text, model): # noqa: ARG001+ worker_calls.append(text)+ return _fake_embedding(text)++ embeddings, valid_indices = self._call(["a", "b"], cached, _fake_call)++ assert len(worker_calls) == 1+ assert worker_calls[0].endswith("b")+ assert embeddings.shape == (2, 1536)+ assert valid_indices == [0, 1]++ def test_worker_failure_skips_intent(self) -> None:+ cached: dict[str, np.ndarray] = {}++ async def _fail(_team, _text, model): # noqa: ARG001+ raise RuntimeError("worker down")++ embeddings, valid_indices = self._call(["a", "b"], cached, _fail)++ assert valid_indices == []+ assert embeddings.shape == (0, 0)+ assert cached == {}++ def test_duplicate_texts_each_call_the_worker(self) -> None:+ # Documents intentional production behaviour: dedup happens upstream+ # (fetch_intent_corpus aggregates by distinct intent_text), so+ # embed_intents_async itself does not dedup. If the caller passes the+ # same text twice, each call independently misses the in-memory cache+ # and hits the worker. The unique constraint on the cache row makes+ # the persist-side race harmless.+ cached: dict[str, np.ndarray] = {}+ worker_calls: list[str] = []++ async def _fake_call(_team, text, model): # noqa: ARG001+ worker_calls.append(text)+ # Real httpx suspends here on the HTTP round-trip; the mock must+ # yield too, otherwise Task A runs to completion (including its+ # persist writeback into `cached`) before Task B's cache check+ # ever runs, and the test would observe spurious dedup that+ # doesn't happen in production.+ await asyncio.sleep(0)+ return _fake_embedding(text)++ embeddings, valid_indices = self._call(["dup", "dup"], cached, _fake_call)++ assert len(worker_calls) == 2+ assert valid_indices == [0, 1]+ assert embeddings.shape == (2, 1536)+++# Cache model round-trip ----------------------------------------------------+++class TestEmbeddingCacheModel(_MCPAnalyticsTeamScopedTestMixin, BaseTest):+ """Pure ORM coverage — proves the model and unique constraint work as expected."""++ def test_round_trip_via_encode_decode(self) -> None:+ vec = _fake_embedding("alpha").embedding+ MCPIntentEmbeddingCache.objects.create(+ team=self.team,+ content_hash=_content_hash("alpha"),+ model=EMBEDDING_MODEL,+ embedding=_encode_embedding(vec),+ )+ row = MCPIntentEmbeddingCache.objects.get(team=self.team, content_hash=_content_hash("alpha"))+ decoded = _decode_embedding(bytes(row.embedding))+ assert decoded.shape == (1536,)+ assert np.allclose(decoded, np.asarray(vec, dtype=np.float32))++ def test_unique_constraint_blocks_duplicate(self) -> None:+ from django.db.utils import IntegrityError++ MCPIntentEmbeddingCache.objects.create(+ team=self.team,+ content_hash="abc",+ model=EMBEDDING_MODEL,+ embedding=_encode_embedding([0.0]),+ )+ with pytest.raises(IntegrityError):+ MCPIntentEmbeddingCache.objects.create(+ team=self.team,+ content_hash="abc",+ model=EMBEDDING_MODEL,+ embedding=_encode_embedding([1.0]),+ )