Skip to content

: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.

fix(aio): skip sentiment eval runs without user messages (#73082)

Carlos Marchal96953727f7a7
diff --git a/posthog/temporal/ai_observability/eval_reports/output_types.py b/posthog/temporal/ai_observability/eval_reports/output_types.py
index a0e96547cf82..3d96fb53a86d 100644
--- a/posthog/temporal/ai_observability/eval_reports/output_types.py
+++ b/posthog/temporal/ai_observability/eval_reports/output_types.py
@@ -14,6 +14,11 @@ class EvaluationReportOutcomeDefinition:
score_expression: str
+# String comparison is deliberate: an unregistered JSON bool property extracts as the
+# string 'true', which the bool literal cannot compare against, while a registered
+# Boolean property coerces correctly against the string form.
+_NOT_SKIPPED_PREDICATE = "(isNull(properties.$ai_evaluation_skipped) OR properties.$ai_evaluation_skipped != 'true')"
+
_OUTCOME_DEFINITIONS: Mapping[str, EvaluationReportOutcomeDefinition] = {
"boolean": EvaluationReportOutcomeDefinition(
outcomes=("pass", "fail", "na"),
@@ -22,7 +27,7 @@ _OUTCOME_DEFINITIONS: Mapping[str, EvaluationReportOutcomeDefinition] = {
"fail": "properties.$ai_evaluation_result = false AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)",
"na": "properties.$ai_evaluation_applicable = false",
},
- event_predicate="(properties.$ai_evaluation_result_type = 'boolean' OR isNull(properties.$ai_evaluation_result_type))",
+ event_predicate=f"(properties.$ai_evaluation_result_type = 'boolean' OR isNull(properties.$ai_evaluation_result_type)) AND {_NOT_SKIPPED_PREDICATE}",
result_expression="properties.$ai_evaluation_result",
applicable_expression="properties.$ai_evaluation_applicable",
score_expression="NULL",
@@ -34,7 +39,7 @@ _OUTCOME_DEFINITIONS: Mapping[str, EvaluationReportOutcomeDefinition] = {
"neutral": "properties.$ai_sentiment_label = 'neutral'",
"negative": "properties.$ai_sentiment_label = 'negative'",
},
- event_predicate="properties.$ai_evaluation_result_type = 'sentiment'",
+ event_predicate=f"properties.$ai_evaluation_result_type = 'sentiment' AND {_NOT_SKIPPED_PREDICATE}",
result_expression="properties.$ai_sentiment_label",
applicable_expression="NULL",
score_expression="properties.$ai_sentiment_score",
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
index 66cc5a2c7c7f..4fedf19e63f0 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock, Mock, patch
from django.utils import timezone
+from parameterized import parameterized
+
from posthog.models import Team
from posthog.temporal.ai_observability.eval_reports.activities import (
_check_count_triggered_eval_report_sync,
@@ -575,14 +577,20 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
delivery_targets=[{"type": "email", "value": "[email protected]"}],
)
- def _emit_eval_events(self, team: Team, evaluation_id: str, timestamps: list[dt.datetime]) -> None:
+ def _emit_eval_events(
+ self,
+ team: Team,
+ evaluation_id: str,
+ timestamps: list[dt.datetime],
+ extra_properties: dict | None = None,
+ ) -> None:
for index, ts in enumerate(timestamps):
_create_event(
team=team,
event="$ai_evaluation",
distinct_id=f"d-{evaluation_id}-{index}",
timestamp=ts,
- properties={"$ai_evaluation_id": evaluation_id},
+ properties={"$ai_evaluation_id": evaluation_id, **(extra_properties or {})},
)
def test_counts_respect_since_evaluation_and_threshold(self):
@@ -677,6 +685,43 @@ class TestBatchedCountTriggeredQuery(ClickhouseTestMixin, BaseTest):
self.assertTrue(by_id[str(sentiment_report.id)].due)
self.assertTrue(by_id[str(boolean_report.id)].due)
+ @parameterized.expand([("boolean",), ("sentiment",)])
+ def test_skipped_runs_are_excluded_from_counts(self, output_type: str) -> None:
+ # Sentiment's event_predicate requires the result_type property; boolean's accepts null.
+ base_props = {"$ai_evaluation_result_type": output_type} if output_type == "sentiment" else {}
+ skipped_props = {**base_props, "$ai_evaluation_skipped": True, "$ai_evaluation_skip_reason": "no_user_messages"}
+ in_window = [self.T0 + dt.timedelta(hours=1), self.T0 + dt.timedelta(hours=2)]
+
+ # 2 real runs + 1 skipped vs threshold 3: due only if the skipped run leaks into the count.
+ report_not_due = self._create_report(
+ self.team, threshold=3, since=self.T0, name=f"skip-not-due-{output_type}", output_type=output_type
+ )
+ self._emit_eval_events(self.team, str(report_not_due.evaluation_id), in_window, extra_properties=base_props)
+ self._emit_eval_events(
+ self.team,
+ str(report_not_due.evaluation_id),
+ [self.T0 + dt.timedelta(minutes=90)],
+ extra_properties=skipped_props,
+ )
+
+ # Control: same events vs threshold 2 stays due, so the exclusion can't over-filter real runs.
+ report_due = self._create_report(
+ self.team, threshold=2, since=self.T0, name=f"skip-due-{output_type}", output_type=output_type
+ )
+ self._emit_eval_events(self.team, str(report_due.evaluation_id), in_window, extra_properties=base_props)
+ self._emit_eval_events(
+ self.team,
+ str(report_due.evaluation_id),
+ [self.T0 + dt.timedelta(minutes=90)],
+ extra_properties=skipped_props,
+ )
+
+ results = _check_count_triggered_eval_reports_batch([str(report_not_due.id), str(report_due.id)], self.NOW)
+
+ due_by_id = {r.report_id: r.due for r in results}
+ self.assertFalse(due_by_id[str(report_not_due.id)])
+ self.assertTrue(due_by_id[str(report_due.id)])
+
def test_trace_target_reports_exclude_generation_events(self):
# The batched countIf must carry the evaluation's target predicate like the
# single-report query does: after an evaluation switches to the trace target,
diff --git a/posthog/temporal/ai_observability/evaluation_sentiment.py b/posthog/temporal/ai_observability/evaluation_sentiment.py
index 9c8d2b9c9b06..be1cd486e385 100644
--- a/posthog/temporal/ai_observability/evaluation_sentiment.py
+++ b/posthog/temporal/ai_observability/evaluation_sentiment.py
@@ -12,15 +12,12 @@ from posthog.temporal.ai_observability.sentiment.schema import PendingClassifica
from posthog.temporal.ai_observability.sentiment.utils import build_generation_result
-def _neutral_sentiment_activity_result(reasoning: str) -> EvaluationActivityResult:
+def _skipped_sentiment_activity_result(skip_reason: str, reasoning: str) -> EvaluationActivityResult:
return {
"result_type": "sentiment",
"reasoning": reasoning,
- "sentiment_label": "neutral",
- "sentiment_score": 0.0,
- "sentiment_scores": {"positive": 0.0, "neutral": 0.0, "negative": 0.0},
- "sentiment_messages": {},
- "sentiment_message_count": 0,
+ "skipped": True,
+ "skip_reason": skip_reason,
}
@@ -31,10 +28,12 @@ def _build_sentiment_activity_result(
classification_results: list[SentimentResult],
) -> EvaluationActivityResult:
if not user_messages:
- return _neutral_sentiment_activity_result("No user messages found; sentiment defaults to neutral.")
+ return _skipped_sentiment_activity_result(
+ "no_user_messages", "No user messages found; sentiment evaluation skipped."
+ )
if not classification_results:
- return _neutral_sentiment_activity_result(
- "No sentiment classifications produced; sentiment defaults to neutral."
+ return _skipped_sentiment_activity_result(
+ "no_classifications", "No sentiment classifications produced; sentiment evaluation skipped."
)
pending = [
@@ -96,7 +95,9 @@ async def execute_sentiment_eval_activity(
trace_id = properties.get("$ai_trace_id", event_uuid)
user_messages = extract_sentiment_eval_messages(input_raw)
if not user_messages:
- return _neutral_sentiment_activity_result("No user messages found; sentiment defaults to neutral.")
+ return _skipped_sentiment_activity_result(
+ "no_user_messages", "No user messages found; sentiment evaluation skipped."
+ )
texts = [text for _message_index, text in user_messages]
diff --git a/posthog/temporal/ai_observability/evaluation_types.py b/posthog/temporal/ai_observability/evaluation_types.py
index 46b37c6c6aa7..9613e7a708a3 100644
--- a/posthog/temporal/ai_observability/evaluation_types.py
+++ b/posthog/temporal/ai_observability/evaluation_types.py
@@ -16,8 +16,9 @@ class EvaluationActivityResult(TypedDict, total=False):
attribution doesn't credit phantom calls, and `execute_hog_eval_activity` (whose
output also flows into `emit_evaluation_event_activity`) emits only `verdict`,
`reasoning`, `allows_na`, and optionally `applicable`.
- - `sentiment_*` fields are set for sentiment evaluations and deliberately omit
- `verdict` so report and pass/fail metrics do not treat sentiment as N/A.
+ - `sentiment_*` fields are set for successful sentiment evaluations (the skip path
+ omits them) and deliberately omit `verdict` so report and pass/fail metrics do
+ not treat sentiment as N/A.
"""
result_type: Required[Literal["boolean", "sentiment"]]
diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
index 7165983f1f9e..abeb0eb4fded 100644
--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py
+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py
@@ -253,11 +253,12 @@ def build_evaluation_event_properties(
properties["$ai_evaluation_key_id"] = result.get("key_id")
if result["result_type"] == "sentiment":
- properties["$ai_sentiment_label"] = result.get("sentiment_label")
- properties["$ai_sentiment_score"] = result.get("sentiment_score")
- properties["$ai_sentiment_scores"] = result.get("sentiment_scores")
- properties["$ai_sentiment_messages"] = result.get("sentiment_messages")
- properties["$ai_sentiment_message_count"] = result.get("sentiment_message_count")
+ if not result.get("skipped"):
+ properties["$ai_sentiment_label"] = result.get("sentiment_label")
+ properties["$ai_sentiment_score"] = result.get("sentiment_score")
+ properties["$ai_sentiment_scores"] = result.get("sentiment_scores")
+ properties["$ai_sentiment_messages"] = result.get("sentiment_messages")
+ properties["$ai_sentiment_message_count"] = result.get("sentiment_message_count")
else:
properties["$ai_evaluation_allows_na"] = allows_na
if allows_na:
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index ea6571c26e97..d538268a4199 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -496,6 +496,56 @@ class TestRunEvaluationWorkflow:
assert "$ai_model" not in props
assert "$ai_provider" not in props
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_emit_evaluation_event_activity_sentiment_skipped_omits_sentiment_props(self, setup_data):
+ evaluation_obj = setup_data["evaluation"]
+ team = setup_data["team"]
+
+ evaluation = {
+ "id": str(evaluation_obj.id),
+ "name": "Sentiment Evaluation",
+ "evaluation_type": "sentiment",
+ }
+ event_data = create_mock_event_data(team.id, properties={"$ai_trace_id": "trace-1"})
+ result: EvaluationActivityResult = {
+ "result_type": "sentiment",
+ "reasoning": "No user messages found; sentiment evaluation skipped.",
+ "skipped": True,
+ "skip_reason": "no_user_messages",
+ }
+
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"
+ ) as mock_team_get:
+ with patch(
+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"
+ ) as mock_capture:
+ mock_team_get.return_value = team
+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())
+
+ await emit_evaluation_event_activity(
+ EmitEvaluationEventInputs(
+ evaluation=evaluation,
+ event_data=event_data,
+ result=result,
+ start_time=datetime(2024, 1, 1, 12, 0, 0),
+ )
+ )
+
+ props = mock_capture.call_args[1]["properties"]
+
+ assert props["$ai_evaluation_result_type"] == "sentiment"
+ assert props["$ai_evaluation_skipped"] is True
+ assert props["$ai_evaluation_skip_reason"] == "no_user_messages"
+ assert "$ai_sentiment_label" not in props
+ assert "$ai_sentiment_score" not in props
+ assert "$ai_sentiment_scores" not in props
+ assert "$ai_sentiment_messages" not in props
+ assert "$ai_sentiment_message_count" not in props
+ assert "$ai_evaluation_result" not in props
+ assert "$ai_evaluation_allows_na" not in props
+
def test_parse_inputs(self):
"""Test that parse_inputs correctly parses workflow inputs"""
event_data = create_mock_event_data(team_id=1)
@@ -1726,7 +1776,7 @@ class TestExecuteSentimentEvalActivity:
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
- async def test_sentiment_eval_defaults_to_neutral_without_user_messages(self, setup_data):
+ async def test_sentiment_eval_skips_without_user_messages(self, setup_data):
team = setup_data["team"]
evaluation = {
"id": str(setup_data["evaluation"].id),
@@ -1746,9 +1796,38 @@ class TestExecuteSentimentEvalActivity:
result = await execute_sentiment_eval_activity(evaluation, event_data)
mock_classify.assert_not_called()
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "no_user_messages"
+ assert result["result_type"] == "sentiment"
assert "verdict" not in result
- assert result["sentiment_label"] == "neutral"
- assert result["sentiment_message_count"] == 0
+ assert "sentiment_label" not in result
+ assert "sentiment_message_count" not in result
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_sentiment_eval_skips_when_classifier_returns_nothing(self, setup_data):
+ team = setup_data["team"]
+ evaluation = {
+ "id": str(setup_data["evaluation"].id),
+ "name": "Sentiment Eval",
+ "evaluation_type": "sentiment",
+ "evaluation_config": {"source": "user_messages"},
+ "output_type": "sentiment",
+ "output_config": {},
+ "team_id": team.id,
+ }
+ event_data = create_mock_event_data(
+ team.id,
+ properties={"$ai_input": [{"role": "user", "content": "hello there"}]},
+ )
+
+ with patch("posthog.temporal.ai_observability.sentiment.model.classify", return_value=[]):
+ result = await execute_sentiment_eval_activity(evaluation, event_data)
+
+ assert result["skipped"] is True
+ assert result["skip_reason"] == "no_classifications"
+ assert result["result_type"] == "sentiment"
+ assert "sentiment_label" not in result
class TestEvalResultModels: