: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(llma): support cohort filters in clustering jobs (#56753)
Andrew Maguirec9fd32085175
diff --git a/posthog/temporal/llm_analytics/trace_summarization/sampling.py b/posthog/temporal/llm_analytics/trace_summarization/sampling.pyindex 637a78adc03d..f8fbffb0dc8a 100644--- a/posthog/temporal/llm_analytics/trace_summarization/sampling.py+++ b/posthog/temporal/llm_analytics/trace_summarization/sampling.py@@ -17,6 +17,7 @@ from posthog.hogql.property import property_to_exprfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.cohort import Cohortfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater@@ -29,6 +30,44 @@ from posthog.temporal.llm_analytics.trace_summarization.utils import format_datelogger = structlog.get_logger(__name__)+# Filter `type` values that resolve to cohort membership lookups in HogQL.+# Saved cohort references survive cohort deletion, so we pre-flight check+# them before sampling to avoid crashing the activity at resolver time.+_COHORT_FILTER_TYPES = ("cohort", "static-cohort", "precalculated-cohort")+++def _missing_cohort_ids(team: Team, event_filters: list[dict[str, Any]]) -> list[int]:+ """Return cohort IDs referenced in event_filters that no longer exist or are soft-deleted.++ Mirrors the lookup the HogQL cohort resolver does (`team__project_id`,+ `deleted=False`) so a clean pre-flight matches what `property_to_expr` /+ `cohort_query_node` would have rejected at query time.+ """+ referenced: list[int] = []+ for f in event_filters:+ if f.get("type") not in _COHORT_FILTER_TYPES:+ continue+ value = f.get("value")+ if not isinstance(value, (int, str)):+ continue+ try:+ referenced.append(int(value))+ except (TypeError, ValueError):+ # Non-numeric cohort values (name lookups) skip pre-flight; the resolver+ # raises a structured QueryError downstream.+ continue+ if not referenced:+ return []++ existing = set(+ Cohort.objects.filter(+ team__project_id=team.project_id,+ id__in=referenced,+ deleted=False,+ ).values_list("id", flat=True)+ )+ return [cid for cid in referenced if cid not in existing]+@temporalio.activity.defnasync def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> list[SampledItem]:@@ -68,6 +107,18 @@ async def sample_items_in_window_activity(inputs: BatchSummarizationInputs) -> l# Build optional trace filter expression from property filterstrace_filter_expr: ast.Expr | None = Noneif event_filters:+ missing = _missing_cohort_ids(team, event_filters)+ if missing:+ # A cohort referenced by a saved clustering job was deleted after+ # the job was created. Skip this run cleanly rather than crash the+ # workflow — the user can fix the filter or delete the job.+ logger.warning(+ "skipping_sampling_missing_cohort_filter",+ team_id=team_id,+ missing_cohort_ids=missing,+ analysis_level=analysis_level,+ )+ return []filter_exprs = [property_to_expr(f, team) for f in event_filters]trace_filter_expr = ast.And(exprs=filter_exprs) if len(filter_exprs) > 1 else filter_exprs[0]diff --git a/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.py b/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.pyindex cec0ece9510c..53786ca57fb9 100644--- a/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.py+++ b/posthog/temporal/llm_analytics/trace_summarization/tests/test_workflow.py@@ -150,6 +150,74 @@ class TestSampleItemsInWindowActivity:assert len(result) == 0+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.asyncio+ async def test_sample_skips_when_cohort_filter_references_missing_cohort(self, mock_team):+ # Cohort referenced by a saved job was deleted between save and run.+ # Activity should log + return [] rather than raise.+ inputs = BatchSummarizationInputs(+ team_id=mock_team.id,+ max_items=100,+ window_minutes=60,+ window_start="2025-01-15T11:00:00",+ window_end="2025-01-15T12:00:00",+ event_filters=[{"key": "id", "value": 999_999, "type": "cohort"}],+ )++ with patch("posthog.temporal.llm_analytics.trace_summarization.sampling.execute_hogql_query") as mock_execute:+ result = await sample_items_in_window_activity(inputs)++ assert result == []+ mock_execute.assert_not_called()++ @pytest.mark.django_db(transaction=True)+ @pytest.mark.asyncio+ async def test_sample_skips_when_cohort_filter_references_soft_deleted_cohort(self, mock_team):+ from asgiref.sync import sync_to_async++ from posthog.models.cohort import Cohort++ cohort = await sync_to_async(Cohort.objects.create)(team=mock_team, name="Stale", deleted=True)+ inputs = BatchSummarizationInputs(+ team_id=mock_team.id,+ max_items=100,+ window_minutes=60,+ window_start="2025-01-15T11:00:00",+ window_end="2025-01-15T12:00:00",+ event_filters=[{"key": "id", "value": cohort.id, "type": "cohort"}],+ )++ with patch("posthog.temporal.llm_analytics.trace_summarization.sampling.execute_hogql_query") as mock_execute:+ result = await sample_items_in_window_activity(inputs)++ assert result == []+ mock_execute.assert_not_called()++ @pytest.mark.django_db(transaction=True)+ @pytest.mark.asyncio+ async def test_sample_runs_when_cohort_filter_resolves(self, mock_team):+ from asgiref.sync import sync_to_async++ from posthog.models.cohort import Cohort++ cohort = await sync_to_async(Cohort.objects.create)(team=mock_team, name="VIPs")+ inputs = BatchSummarizationInputs(+ team_id=mock_team.id,+ max_items=100,+ window_minutes=60,+ window_start="2025-01-15T11:00:00",+ window_end="2025-01-15T12:00:00",+ event_filters=[{"key": "id", "value": cohort.id, "type": "cohort"}],+ )++ with patch("posthog.temporal.llm_analytics.trace_summarization.sampling.execute_hogql_query") as mock_execute:+ mock_execute.return_value.results = []++ result = await sample_items_in_window_activity(inputs)++ assert result == []+ mock_execute.assert_called_once()+class TestBatchTraceSummarizationWorkflow:def test_parse_inputs_minimal(self):diff --git a/products/llm_analytics/backend/api/clustering_job.py b/products/llm_analytics/backend/api/clustering_job.pyindex ce87878a598e..fa63373c5e03 100644--- a/products/llm_analytics/backend/api/clustering_job.py+++ b/products/llm_analytics/backend/api/clustering_job.py@@ -1,3 +1,5 @@+from typing import Any+from django.db import IntegrityError, transactionfrom rest_framework import serializers, status, viewsets@@ -8,11 +10,13 @@ from rest_framework.response import Responsefrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.event_usage import report_user_action+from posthog.models.cohort import Cohortfrom ..models.clustering_job import ClusteringJobfrom .metrics import llma_track_latencyMAX_JOBS_PER_TEAM = 10+_COHORT_FILTER_TYPES = ("cohort", "static-cohort", "precalculated-cohort")class ClusteringJobSerializer(serializers.ModelSerializer):@@ -33,6 +37,43 @@ class ClusteringJobSerializer(serializers.ModelSerializer):"updated_at",]+ def validate_event_filters(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Reject filters that reference a cohort that doesn't exist (or is deleted).++ Saved jobs run on a schedule with no human in the loop, so a dangling+ cohort id would silently break sampling. Catching it at save time gives+ the user immediate feedback. Cohorts deleted *after* save are still+ handled defensively in the sampling activity itself.+ """+ team = self.context["get_team"]()+ referenced_ids: list[int] = []+ for f in value:+ if f.get("type") not in _COHORT_FILTER_TYPES:+ continue+ cohort_value = f.get("value")+ if not isinstance(cohort_value, (int, str)):+ continue+ try:+ referenced_ids.append(int(cohort_value))+ except (TypeError, ValueError):+ # Non-numeric cohort references (e.g. name lookups) are passed+ # through untouched — the resolver validates them at query time.+ continue++ if referenced_ids:+ existing = set(+ Cohort.objects.filter(+ team__project_id=team.project_id,+ id__in=referenced_ids,+ deleted=False,+ ).values_list("id", flat=True)+ )+ missing = sorted({cid for cid in referenced_ids if cid not in existing})+ if missing:+ raise serializers.ValidationError(f"Cohort(s) not found or deleted: {missing}")++ return value+class ClusteringJobViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""CRUD for clustering job configurations (max 5 per team)."""diff --git a/products/llm_analytics/backend/api/test/test_clustering_job.py b/products/llm_analytics/backend/api/test/test_clustering_job.pyindex f45cc1ae7e66..1a055f6f5a7f 100644--- a/products/llm_analytics/backend/api/test/test_clustering_job.py+++ b/products/llm_analytics/backend/api/test/test_clustering_job.py@@ -207,6 +207,70 @@ class TestClusteringJobViewSet(APIBaseTest):custom.refresh_from_db()self.assertTrue(custom.enabled)+ def _cohort_filter(self, cohort_id: int | str) -> dict:+ return {"key": "id", "value": cohort_id, "type": "cohort"}++ def test_create_with_valid_cohort_filter(self):+ from posthog.models.cohort import Cohort++ cohort = Cohort.objects.create(team=self.team, name="VIPs")+ response = self.client.post(+ self._url(),+ {+ "name": "VIP Traffic",+ "analysis_level": "trace",+ "event_filters": [self._cohort_filter(cohort.id)],+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ @parameterized.expand(+ [+ ("missing", 999_999),+ ("string_id_missing", "999999"),+ ]+ )+ def test_create_rejects_missing_cohort_filter(self, _name, cohort_id):+ response = self.client.post(+ self._url(),+ {+ "name": "Bad Cohort",+ "analysis_level": "trace",+ "event_filters": [self._cohort_filter(cohort_id)],+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("not found or deleted", str(response.json()))++ def test_create_rejects_soft_deleted_cohort_filter(self):+ from posthog.models.cohort import Cohort++ cohort = Cohort.objects.create(team=self.team, name="Stale", deleted=True)+ response = self.client.post(+ self._url(),+ {+ "name": "Stale Cohort",+ "analysis_level": "trace",+ "event_filters": [self._cohort_filter(cohort.id)],+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("not found or deleted", str(response.json()))++ def test_partial_update_rejects_missing_cohort_filter(self):+ job = self._create_job(name="Will be broken")+ response = self.client.patch(+ self._url(f"{job.id}/"),+ {"event_filters": [self._cohort_filter(999_999)]},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ job.refresh_from_db()+ self.assertEqual(job.event_filters, [])+class TestDefaultClusteringJobsOnTeamCreate(APIBaseTest):"""Exercises the post_save signal in models/clustering_job.py that seeds the threediff --git a/products/llm_analytics/frontend/clusters/ClusteringAdminModal.tsx b/products/llm_analytics/frontend/clusters/ClusteringAdminModal.tsxindex abb6ef4a53e8..e93c4cb6771a 100644--- a/products/llm_analytics/frontend/clusters/ClusteringAdminModal.tsx+++ b/products/llm_analytics/frontend/clusters/ClusteringAdminModal.tsx@@ -111,6 +111,8 @@ export function ClusteringAdminModal(): JSX.Element {taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties,TaxonomicFilterGroupType.EventMetadata,+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.Cohorts,]}addText="Add event filter"hasRowOperator={false}diff --git a/products/llm_analytics/frontend/clusters/ClusteringJobsPanel.tsx b/products/llm_analytics/frontend/clusters/ClusteringJobsPanel.tsxindex 9c9b61274c44..6f339a849492 100644--- a/products/llm_analytics/frontend/clusters/ClusteringJobsPanel.tsx+++ b/products/llm_analytics/frontend/clusters/ClusteringJobsPanel.tsx@@ -92,6 +92,8 @@ function JobEditor({taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties,TaxonomicFilterGroupType.EventMetadata,+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.Cohorts,]}addText="Add filter"hasRowOperator={false}diff --git a/products/llm_analytics/frontend/clusters/ClusteringSettingsPanel.tsx b/products/llm_analytics/frontend/clusters/ClusteringSettingsPanel.tsxindex 6cc7bea90941..53e92e6295c4 100644--- a/products/llm_analytics/frontend/clusters/ClusteringSettingsPanel.tsx+++ b/products/llm_analytics/frontend/clusters/ClusteringSettingsPanel.tsx@@ -48,6 +48,8 @@ export function ClusteringSettingsPanel(): JSX.Element {taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties,TaxonomicFilterGroupType.EventMetadata,+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.Cohorts,]}addText="Add event filter"hasRowOperator={false}