: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
fix(aio): return 400 for malformed clustering job event_filters (#93084)
posthog[bot]fb709a58620e
diff --git a/products/ai_observability/backend/api/clustering_job.py b/products/ai_observability/backend/api/clustering_job.pyindex c33b02738680..9c241a79e593 100644--- a/products/ai_observability/backend/api/clustering_job.py+++ b/products/ai_observability/backend/api/clustering_job.py@@ -22,7 +22,29 @@ MAX_JOBS_PER_TEAM = 10_COHORT_FILTER_TYPES = ("cohort", "static-cohort", "precalculated-cohort")+class EventFiltersField(serializers.ListField):+ """Validate the filter shape on write, and pass the stored value through on read.++ The column is an unvalidated JSONField, and the team-level config writer only+ checks that the value is a list, so a row can already hold any shape. Running+ the strict read path over such a row raises and turns a job list into a 500,+ so reads keep the pass-through behavior the plain model field had.+ """++ def to_representation(self, data: Any) -> Any:+ return data++class ClusteringJobSerializer(serializers.ModelSerializer):+ event_filters = EventFiltersField(+ # A property filter can carry a null value or label, for example before the+ # user picks a value or when switching operators. A JSONField child rejects+ # null, so keep the child an untyped DictField to avoid 400ing valid filters.+ child=serializers.DictField(),+ required=False,+ help_text="PostHog property filters that scope this clustering job. Empty array means no filters.",+ )+class Meta:model = ClusteringJobfields = [diff --git a/products/ai_observability/backend/api/test/test_clustering_job.py b/products/ai_observability/backend/api/test/test_clustering_job.pyindex 246ab637d104..95a6187b9230 100644--- a/products/ai_observability/backend/api/test/test_clustering_job.py+++ b/products/ai_observability/backend/api/test/test_clustering_job.py@@ -3,9 +3,12 @@ import uuidfrom posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import status+from products.ai_observability.backend.api.clustering_job import ClusteringJobSerializerfrom products.ai_observability.backend.models.clustering_job import ClusteringJob@@ -295,6 +298,32 @@ class TestClusteringJobViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("not found or deleted", str(response.json()))+ def test_create_rejects_malformed_event_filters(self):+ response = self.client.post(+ self._url(),+ {"name": "Malformed", "analysis_level": "trace", "event_filters": {"key": "$ai_model"}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json().get("attr"), "event_filters")+ self.assertEqual(ClusteringJob.objects.filter(team=self.team).count(), 0)++ @parameterized.expand(+ [+ ("bare_string", "$ai_model"),+ ("list_holding_a_string", ["$ai_model"]),+ ]+ )+ def test_list_still_serializes_a_row_holding_a_malformed_shape(self, name, stored_filters):+ # The column is an unvalidated JSONField and the config writer only checks for a+ # list, so an existing row can hold a shape the write path now rejects. The+ # config-to-job migration copied those values across, which is how a stored list+ # can hold a non-dict element.+ self._create_job(name=f"Legacy {name}", event_filters=stored_filters)+ response = self.client.get(self._url())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"][0]["event_filters"], stored_filters)+def test_partial_update_rejects_missing_cohort_filter(self):job = self._create_job(name="Will be broken")response = self.client.patch(@@ -307,6 +336,32 @@ class TestClusteringJobViewSet(APIBaseTest):self.assertEqual(job.event_filters, [])+class TestClusteringJobSerializerValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("mapping", {"key": "$ai_model"}),+ ("list_of_strings", ["$ai_model"]),+ ("bare_string", "$ai_model"),+ ("number", 1),+ ("boolean", True),+ ]+ )+ def test_rejects_event_filters_that_are_not_a_list_of_objects(self, _name, value) -> None:+ serializer = ClusteringJobSerializer(data={"event_filters": value}, partial=True)+ assert not serializer.is_valid()+ assert "event_filters" in serializer.errors++ def test_accepts_event_filter_with_null_value_and_label(self) -> None:+ # A non-cohort filter never dereferences the team, so a stub get_team keeps+ # this DB-free while still reaching field validation of the null values.+ filters = [{"key": "$ai_model", "operator": "exact", "type": "event", "value": None, "label": None}]+ serializer = ClusteringJobSerializer(+ data={"event_filters": filters}, partial=True, context={"get_team": lambda: None}+ )+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data["event_filters"] == filters++class TestDefaultClusteringJobsOnTeamCreate(APIBaseTest):"""Exercises the post_save signal in models/clustering_job.py that seeds the threeDefault - <level> rows when a new Team is created."""diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 0ab11a9f7068..fafec91827ab 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -1264,12 +1264,15 @@ export const AnalysisLevelEnumApi = {Evaluation: 'evaluation',} as const+export type ClusteringJobApiEventFiltersItem = { [key: string]: unknown }+export interface ClusteringJobApi {readonly id: string/** @maxLength 100 */name: stringanalysis_level: AnalysisLevelEnumApi- event_filters?: unknown+ /** PostHog property filters that scope this clustering job. Empty array means no filters. */+ event_filters?: ClusteringJobApiEventFiltersItem[]enabled?: booleanreadonly created_at: stringreadonly updated_at: string@@ -1284,12 +1287,15 @@ export interface PaginatedClusteringJobListApi {results: ClusteringJobApi[]}+export type PatchedClusteringJobApiEventFiltersItem = { [key: string]: unknown }+export interface PatchedClusteringJobApi {readonly id?: string/** @maxLength 100 */name?: stringanalysis_level?: AnalysisLevelEnumApi- event_filters?: unknown+ /** PostHog property filters that scope this clustering job. Empty array means no filters. */+ event_filters?: PatchedClusteringJobApiEventFiltersItem[]enabled?: booleanreadonly created_at?: stringreadonly updated_at?: stringdiff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex fa15cd0fd67b..666320791114 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -934,7 +934,10 @@ export const LlmAnalyticsClusteringJobsCreateBody = /* @__PURE__ */ zod.object({analysis_level: zod.enum(['trace', 'generation', 'evaluation']).describe('\* `trace` - trace\n\* `generation` - generation\n\* `evaluation` - evaluation'),- event_filters: zod.unknown().optional(),+ event_filters: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe('PostHog property filters that scope this clustering job. Empty array means no filters.'),enabled: zod.boolean().optional(),})@@ -948,7 +951,10 @@ export const LlmAnalyticsClusteringJobsUpdateBody = /* @__PURE__ */ zod.object({analysis_level: zod.enum(['trace', 'generation', 'evaluation']).describe('\* `trace` - trace\n\* `generation` - generation\n\* `evaluation` - evaluation'),- event_filters: zod.unknown().optional(),+ event_filters: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe('PostHog property filters that scope this clustering job. Empty array means no filters.'),enabled: zod.boolean().optional(),})@@ -963,7 +969,10 @@ export const LlmAnalyticsClusteringJobsPartialUpdateBody = /* @__PURE__ */ zod.o.enum(['trace', 'generation', 'evaluation']).optional().describe('\* `trace` - trace\n\* `generation` - generation\n\* `evaluation` - evaluation'),- event_filters: zod.unknown().optional(),+ event_filters: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe('PostHog property filters that scope this clustering job. Empty array means no filters.'),enabled: zod.boolean().optional(),})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5af2d0b4e195..bd14df537a5c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17682,12 +17682,15 @@ export namespace Schemas {event_filters: ClusteringConfigSetEventFiltersEventFiltersItem[];}+ export type ClusteringJobEventFiltersItem = { [key: string]: unknown };+export interface ClusteringJob {readonly id: string;/** @maxLength 100 */name: string;analysis_level: AnalysisLevelEnum;- event_filters?: unknown;+ /** PostHog property filters that scope this clustering job. Empty array means no filters. */+ event_filters?: ClusteringJobEventFiltersItem[];enabled?: boolean;readonly created_at: string;readonly updated_at: string;@@ -60634,12 +60637,15 @@ export namespace Schemas {auto_archive_after_days?: number | null;}+ export type PatchedClusteringJobEventFiltersItem = { [key: string]: unknown };+export interface PatchedClusteringJob {readonly id?: string;/** @maxLength 100 */name?: string;analysis_level?: AnalysisLevelEnum;- event_filters?: unknown;+ /** PostHog property filters that scope this clustering job. Empty array means no filters. */+ event_filters?: PatchedClusteringJobEventFiltersItem[];enabled?: boolean;readonly created_at?: string;readonly updated_at?: string;diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex d2efdc61f936..5b75d73b0928 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -1119,7 +1119,10 @@ export const LlmAnalyticsClusteringJobsCreateBody = () => zod.object({analysis_level: zod.enum(['trace', 'generation', 'evaluation']).describe('\* `trace` - trace\n\* `generation` - generation\n\* `evaluation` - evaluation'),- event_filters: zod.unknown().optional(),+ event_filters: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe('PostHog property filters that scope this clustering job. Empty array means no filters.'),enabled: zod.boolean().optional(),})@@ -1155,7 +1158,10 @@ export const LlmAnalyticsClusteringJobsPartialUpdateBody = () => zod.object({.enum(['trace', 'generation', 'evaluation']).optional().describe('\* `trace` - trace\n\* `generation` - generation\n\* `evaluation` - evaluation'),- event_filters: zod.unknown().optional(),+ event_filters: zod+ .array(zod.record(zod.string(), zod.unknown()))+ .optional()+ .describe('PostHog property filters that scope this clustering job. Empty array means no filters.'),enabled: zod.boolean().optional(),})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-create.jsonindex b72841666895..15e0dbf0a93a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-create.json@@ -9,7 +9,17 @@"enabled": {"type": "boolean"},- "event_filters": {},+ "event_filters": {+ "description": "PostHog property filters that scope this clustering job. Empty array means no filters.",+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },"name": {"maxLength": 100,"type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-update.jsonindex 3da2a9a6f617..aad356f49c09 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-clustering-job-update.json@@ -9,7 +9,17 @@"enabled": {"type": "boolean"},- "event_filters": {},+ "event_filters": {+ "description": "PostHog property filters that scope this clustering job. Empty array means no filters.",+ "items": {+ "additionalProperties": {},+ "propertyNames": {+ "type": "string"+ },+ "type": "object"+ },+ "type": "array"+ },"id": {"description": "A UUID string identifying this clustering job.","type": "string"