: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): reject evaluation conditions that fail to compile (#109475)
posthog[bot]cfa14ad4508a
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 78427d812072..fe9cac71d2bc 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -1468,6 +1468,53 @@ class TestEvaluationConfigsApi(APIBaseTest):self.assertEqual(len(response.data["conditions"][0]["properties"]), 1)self.assertEqual(response.data["conditions"][0]["properties"][0]["key"], "$ai_model_name")+ @parameterized.expand(+ [+ ("select_query", "(select 1)"),+ ("global_the_runtime_does_not_have", "$virt_is_bot"),+ ]+ )+ def test_condition_that_fails_to_compile_is_rejected(self, _name, hogql_key):+ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/",+ {+ "name": "Broken filter",+ "evaluation_type": "llm_judge",+ "model_configuration": _DEFAULT_MODEL_CONFIGURATION,+ "evaluation_config": {"prompt": "Evaluate this"},+ "output_type": "boolean",+ "output_config": {},+ "conditions": [+ {"id": "cond-1", "rollout_percentage": 100, "properties": []},+ {"id": "cond-2", "rollout_percentage": 100, "properties": [{"type": "hogql", "key": hogql_key}]},+ ],+ },+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertIn("Condition set 2", str(response.data))+ self.assertFalse(Evaluation.objects.filter(team=self.team, name="Broken filter").exists())++ def test_patch_that_adds_a_condition_that_fails_to_compile_is_rejected(self):+ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Working filter",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ conditions=[{"id": "cond-1", "rollout_percentage": 100, "properties": []}],+ )++ response = self.client.patch(+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",+ {"conditions": [{"id": "cond-1", "properties": [{"type": "hogql", "key": "(select 1)"}]}]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ evaluation.refresh_from_db()+ self.assertEqual(evaluation.conditions[0]["properties"], [])+def test_unknown_condition_keys_are_dropped_and_rollout_percentage_defaults_to_100(self):# Regression: callers (notably MCP) previously sent `sampling_rate` instead of# `rollout_percentage` and the unstructured JSONField silently persisted it. Thediff --git a/products/ai_observability/backend/models/evaluations.py b/products/ai_observability/backend/models/evaluations.pyindex 0baab02b4f5e..e73eb064b728 100644--- a/products/ai_observability/backend/models/evaluations.py+++ b/products/ai_observability/backend/models/evaluations.py@@ -220,6 +220,17 @@ class Evaluation(ModelActivityMixin, UUIDTModel):self.status_reason_detail = reason_detailself.save(update_fields=["status", "status_reason", "status_reason_detail", "enabled", "updated_at"])+ def _condition_filters_changed(self) -> bool:+ # Compare against the stored row, not an in-memory snapshot, so in-place edits count as changes.+ if self._state.adding:+ return True+ stored = (+ Evaluation.objects.filter(pk=self.pk, team_id=self.team_id).values_list("conditions", flat=True).first()+ )+ if stored is None:+ return True+ return [c.get("properties", []) for c in self.conditions] != [c.get("properties", []) for c in stored]+def save(self, *args, **kwargs):from posthog.cdp.filters import compile_filters_bytecode@@ -264,14 +275,25 @@ class Evaluation(ModelActivityMixin, UUIDTModel):# Compile bytecode for each conditioncompiled_conditions = []- for condition in self.conditions:+ compile_error: str | None = None+ for index, condition in enumerate(self.conditions):compiled_condition = {**condition}filters = {"properties": condition.get("properties", [])}compiled = compile_filters_bytecode(filters, self.team)+ bytecode_error = compiled.get("bytecode_error")+ if bytecode_error and compile_error is None:+ compile_error = f"Condition set {index + 1} has a filter that evaluations cannot run. {bytecode_error}"compiled_condition["bytecode"] = compiled.get("bytecode")- compiled_condition["bytecode_error"] = compiled.get("bytecode_error")+ compiled_condition["bytecode_error"] = bytecode_errorcompiled_conditions.append(compiled_condition)+ # The scheduler never matches a condition that has no bytecode. Reject the save when the caller+ # changes the filters. Other saves skip this check, so pause, delete and status changes work.+ update_fields = kwargs.get("update_fields")+ writes_conditions = update_fields is None or "conditions" in update_fields+ if compile_error and writes_conditions and self._condition_filters_changed():+ raise ValidationError({"conditions": compile_error})+self.conditions = compiled_conditionsresult = super().save(*args, **kwargs)# Refresh the baseline so the next save cycle compares against the post-save state.diff --git a/products/ai_observability/backend/models/test/test_evaluations.py b/products/ai_observability/backend/models/test/test_evaluations.pyindex 0b7e3bd1ccba..7e926413e9b7 100644--- a/products/ai_observability/backend/models/test/test_evaluations.py+++ b/products/ai_observability/backend/models/test/test_evaluations.py@@ -39,36 +39,52 @@ class TestEvaluationModel(BaseTest):self.assertIsNotNone(evaluation.conditions[0]["bytecode"])self.assertIsInstance(evaluation.conditions[0]["bytecode"], list)- def test_sets_bytecode_error_when_compilation_fails(self):- """- If bytecode compilation fails, the bytecode_error field should be set- """+ @parameterized.expand(+ [+ ("set_status", None, "status", EvaluationStatus.ERROR),+ ("pause", {"enabled": False}, "enabled", False),+ ("delete", {"deleted": True}, "deleted", True),+ ]+ )+ def test_save_without_filter_change_succeeds_when_condition_no_longer_compiles(+ self, _name, updates, field, expected+ ):+ evaluation = self._create_hog_evaluation()+with patch("posthog.cdp.filters.compile_filters_bytecode") as mock_compile:mock_compile.return_value = {"bytecode": None, "bytecode_error": "Invalid property filter"}+ if updates is None:+ evaluation.set_status(EvaluationStatus.ERROR, EvaluationStatusReason.HOG_ERROR)+ else:+ for key, value in updates.items():+ setattr(evaluation, key, value)+ evaluation.save()+ mock_compile.assert_called_once()- evaluation = Evaluation.objects.create(- team=self.team,- name="Test Evaluation",- evaluation_type="llm_judge",- evaluation_config={"prompt": "Test prompt"},- output_type="boolean",- output_config={},- enabled=True,- created_by=self.user,- conditions=[- {- "id": "cond-1",- "rollout_percentage": 100,- "properties": [{"key": "invalid"}],- }- ],- )+ evaluation.refresh_from_db()+ self.assertEqual(getattr(evaluation, field), expected)++ def test_full_save_rejects_filter_edited_in_place_after_status_only_save(self):+ evaluation = self._create_hog_evaluation()++ evaluation.conditions[0]["properties"].append({"type": "hogql", "key": "(select 1)"})+ evaluation.set_status(EvaluationStatus.ERROR, EvaluationStatusReason.HOG_ERROR)- evaluation.refresh_from_db()+ with self.assertRaises(ValidationError):+ evaluation.save()+ evaluation.refresh_from_db()+ self.assertEqual(evaluation.conditions[0]["properties"], [])- self.assertEqual(len(evaluation.conditions), 1)- self.assertIn("bytecode_error", evaluation.conditions[0])- self.assertEqual(evaluation.conditions[0]["bytecode_error"], "Invalid property filter")+ def _create_hog_evaluation(self) -> Evaluation:+ return Evaluation.objects.create(+ team=self.team,+ name="Test Evaluation",+ evaluation_type="hog",+ evaluation_config={"source": "return true"},+ output_type="boolean",+ enabled=True,+ conditions=[{"id": "cond-1", "rollout_percentage": 100, "properties": []}],+ )def test_handles_empty_properties_list(self):"""diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsxindex 346fc2fa81ad..0d414ffe995e 100644--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx@@ -612,9 +612,9 @@ export function AIObservabilityEvaluation(): JSX.Element {</LemonField.Pure><p className="text-muted text-sm -mt-2">{isSessionTarget- ? 'Runs once per session on every trace it contains, after the session settles. Only fires for events that carry an AI session id.'+ ? 'Runs once per session on every trace it contains, after the session settles. Only fires for generations that have an $ai_session_id property.': evaluation.target === 'trace'- ? 'Runs once per trace on all of its events together, after it settles.'+ ? 'Runs once per trace on all of its events together, after it settles. Only fires for generations that have an $ai_trace_id property.': 'Runs on each matching generation event individually, right after it is ingested.'}</p>{isAggregateTarget && (