: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(devenv): make hogli start work end-to-end for clustering features (#59705)
Daniel Visca17203f0225b4
diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yamlindex 796156938cd2..7287158b3a9d 100644--- a/devenv/intent-map.yaml+++ b/devenv/intent-map.yaml@@ -269,12 +269,18 @@ intents:event_ingestion,ai_capture,llm_gateway,+ embedding_service,property_definitions,property_values,temporal_workflows,llm_analytics_sentiment,]+ mcp_analytics:+ description: 'MCP analytics intent clustering and session summarisation'+ capabilities:+ [event_ingestion, llm_gateway, embedding_service, property_definitions, property_values, temporal_workflows]+web_analytics:description: 'Web analytics, traffic analysis, and heatmaps'capabilities: [event_ingestion, replay_storage, property_definitions, property_values, livestream]diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 34020e757c3f..0c4ebf9a4a47 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -439,6 +439,42 @@ services:depends_on:- zookeeper+ kafka-init:+ image: docker.redpanda.com/redpandadata/redpanda:v25.1.9+ entrypoint: /bin/sh+ restart: 'no'+ command:+ - -c+ - |+ set -x+ # Redpanda auto_create_topics_enabled=true only fires on producer-first+ # writes. Consumer-only services (e.g. embedding-worker) error on missing+ # topics, so we pre-create them here. Idempotent — re-running is safe.+ TIMEOUT=60+ ELAPSED=0+ until rpk topic list --brokers kafka:9092 2>/dev/null; do+ echo "Waiting for Kafka broker... (elapsed: ${ELAPSED}s)"+ sleep 2+ ELAPSED=$((ELAPSED + 2))+ if [ $ELAPSED -ge $TIMEOUT ]; then+ echo "Timeout waiting for Kafka broker after ${TIMEOUT}s"+ exit 1+ fi+ done+ for topic in document_embeddings_input; do+ if rpk topic create "$$topic" --brokers kafka:9092 -p 1 -r 1 2>&1; then+ echo "Topic $$topic created"+ elif rpk topic list --brokers kafka:9092 | grep -q "$$topic"; then+ echo "Topic $$topic already exists"+ else+ echo "Failed to create topic $$topic"+ exit 1+ fi+ done+ depends_on:+ kafka:+ condition: service_healthy+kafka_ui:extends:file: docker-compose.base.ymldiff --git a/posthog/api/embedding_worker.py b/posthog/api/embedding_worker.pyindex 6a63af1a1836..d1b6363ad890 100644--- a/posthog/api/embedding_worker.py+++ b/posthog/api/embedding_worker.py@@ -4,6 +4,7 @@ from typing import Optionalfrom django.utils.timezone import now+import httpximport structlogfrom posthog.kafka_client.client import ProduceResult@@ -49,6 +50,23 @@ def _build_embedding_payload(team: Team, content: str, model: str | None, no_tru}+def _raise_for_embedding_response(response) -> None:+ """raise_for_status() with a clearer hint when the worker rejects ad-hoc requests+ because the organization has not opted into AI data processing — a common dev+ foot-gun where the underlying 403 body is hidden behind a generic HTTPStatusError.+ """+ if response.status_code == 403 and "ai" in response.text.lower():+ raise httpx.HTTPStatusError(+ f"Embedding worker returned 403: {response.text}. "+ "Likely the organization has not opted into AI data processing — "+ "set Organization.is_ai_data_processing_approved=True (Settings > AI, "+ "or via SQL in local dev) and retry.",+ request=response.request,+ response=response,+ )+ response.raise_for_status()++def _parse_embedding_response(data: dict) -> EmbeddingResponse:return EmbeddingResponse(embedding=data["embedding"],@@ -63,7 +81,7 @@ def generate_embedding(logger.info(f"Generating ad-hoc embedding for team {team.pk}")payload = _build_embedding_payload(team, content, model, no_truncate)response = internal_requests.post(_EMBEDDING_URL, json=payload)- response.raise_for_status()+ _raise_for_embedding_response(response)return _parse_embedding_response(response.json())@@ -75,7 +93,7 @@ async def async_generate_embedding(payload = _build_embedding_payload(team, content, model, no_truncate)async with internal_httpx_async_client(timeout=30.0) as client:response = await client.post(_EMBEDDING_URL, json=payload)- response.raise_for_status()+ _raise_for_embedding_response(response)return _parse_embedding_response(response.json())diff --git a/scripts/inject_mcp_intents.py b/scripts/inject_mcp_intents.pynew file mode 100644index 000000000000..f8c47e8bad3a--- /dev/null+++ b/scripts/inject_mcp_intents.py@@ -0,0 +1,133 @@+"""Inject synthetic intents on MCPSession rows for local clustering tests.++Bypasses OpenAI by picking from a curated pool of phrasings grouped into+themes. Use this when you want to validate the clustering pipeline at scale+without burning LLM credits.++Themes are intentionally redundant — multiple phrasings of "investigate a+checkout-failure spike", multiple phrasings of "confirm a flag rollout", etc.+— so clustering has clear signal to detect.++Usage:+ flox activate -- python scripts/inject_mcp_intents.py [--team-id N] [--seed N]+"""++import os+import sys+import random+import argparse+from pathlib import Path++# Allow `python scripts/inject_mcp_intents.py` from the repo root without+# requiring PYTHONPATH — django.setup() needs the posthog package on sys.path.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import django++os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+django.setup()++# Each list is a cluster theme. Variants share semantic meaning so the embedding+# space groups them together, but lexical phrasing differs so the cluster has+# non-trivial intra-cluster variance — closer to real LLM output.+INTENT_THEMES: list[list[str]] = [+ [+ "Investigate yesterday's spike in checkout failures using revenue and error events.",+ "Drill into the unusual jump in failed checkouts that started last night.",+ "Diagnose the checkout-error surge by correlating revenue and exception events.",+ "Triage the increase in checkout failures by pulling related error tracking issues.",+ "Look into the overnight checkout-error spike and identify the affected segments.",+ ],+ [+ "Pull funnel conversion numbers for the new pricing page for the weekly product review.",+ "Compare pricing-page funnel performance week over week ahead of the product review.",+ "Summarise the pricing-page conversion funnel for the leadership update.",+ "Build a funnel from pricing-page view to checkout to assess the new layout.",+ ],+ [+ "Check whether the new pricing feature flag is fully rolled out to the affected cohort.",+ "Confirm the rollout percentage of the pricing flag for a support escalation.",+ "Verify the new pricing flag is enabled for the customer who reported the issue.",+ "Audit the pricing feature flag's targeting rules after a complaint.",+ ],+ [+ "Review the active pricing experiment and decide whether we have the power to call a winner.",+ "Check the statistical significance of the current pricing experiment results.",+ "Decide whether to ship the winning variant of the pricing A/B test this week.",+ ],+ [+ "Pull active users metrics to share growth trends in the leadership Slack channel.",+ "Compile weekly active user counts for the growth update.",+ "Generate a DAU/WAU/MAU summary to post in the leadership channel.",+ ],+ [+ "Compare last cohort's retention curve to the previous one for the product review.",+ "Pull the 7-day retention chart for the latest signup cohort.",+ "Analyse retention drop-off for the most recent product launch.",+ ],+ [+ "Triage user-reported latency complaints from this morning using the platform health dashboard.",+ "Open the platform health dashboard to investigate API latency reports.",+ "Diagnose this morning's slowness complaints by reviewing the health dashboard.",+ ],+ [+ "Look up the reporter of a paid plan billing complaint before processing a refund.",+ "Find the customer profile tied to the billing escalation for the refund decision.",+ "Resolve the billing-complaint identity by querying recent paid-plan events.",+ ],+ [+ "Replay the signup session where the user got stuck so we can file a precise bug report.",+ "Watch the session recording of the stuck-signup user to identify the friction point.",+ "Investigate the stuck-signup complaint via session replay.",+ ],+ [+ "Pull the latest exception issue tied to the deploy so on-call can triage the regression.",+ "Identify the new error-tracking issue linked to today's deploy.",+ "Investigate the deploy-related regression by inspecting the freshest exception.",+ ],+]+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--team-id",+ type=int,+ default=None,+ help="Only inject for this team (default: all teams).",+ )+ parser.add_argument("--seed", type=int, default=None, help="Random seed for reproducible output.")+ args = parser.parse_args()++ from products.mcp_analytics.backend.models import MCPSession++ qs = MCPSession.objects.unscoped().filter(intent__isnull=True)+ if args.team_id is not None:+ qs = qs.filter(team_id=args.team_id)++ pending = qs.count()+ if pending == 0:+ sys.stdout.write("No NULL-intent sessions to inject.\n")+ return++ rng = random.Random(args.seed)+ pool = [phrase for theme in INTENT_THEMES for phrase in theme]+ sys.stdout.write(+ f"Injecting intents into {pending} sessions from {len(pool)} phrasings across {len(INTENT_THEMES)} themes...\n"+ )++ # Iterate ids only so we don't hold the full queryset in memory; use update()+ # per row to skip ORM signals and stay fast on large batches.+ updated = 0+ for session_id in qs.values_list("id", flat=True):+ intent = rng.choice(pool)+ MCPSession.objects.unscoped().filter(id=session_id).update(intent=intent)+ updated += 1+ if updated % 100 == 0:+ sys.stdout.write(f" {updated}/{pending}\n")++ sys.stdout.write(f"\nDone. injected={updated}\n")+++if __name__ == "__main__":+ main()