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): report boolean evaluation outcomes by declared polarity (#92753)

Carlos Marchal65f18bd850f4
diff --git a/playwright/utils/playwright-setup.ts b/playwright/utils/playwright-setup.ts
index eb39c2737a2e..6529d6312c76 100644
--- a/playwright/utils/playwright-setup.ts
+++ b/playwright/utils/playwright-setup.ts
@@ -310,6 +310,49 @@ export class PlaywrightSetup {
await page.goto(`${this.baseURL}/project/${workspace.team_id}`)
}
+ /**
+ * Seed events (and optional persons) directly into ClickHouse for a team created earlier in
+ * the same test. Use this when an event must reference an id minted after workspace setup
+ * (e.g. an evaluation created through the API) — `createWorkspace`'s own `events` option only
+ * seeds at workspace-creation time.
+ */
+ async seedEvents(
+ teamId: string,
+ events: PlaywrightSetupEvent[],
+ persons?: PlaywrightSetupPerson[]
+ ): Promise<{ team_id: string; events_created: number }> {
+ const result = await this.callSetupEndpoint('seed_events', {
+ data: { team_id: Number(teamId), events, persons },
+ })
+ if (!result.success) {
+ throw new Error(`Failed to seed events: ${result.error}`)
+ }
+ return result.result as { team_id: string; events_created: number }
+ }
+
+ /**
+ * Create an Evaluation with `output_config` stored exactly as given, bypassing the config
+ * normalization the model and the API both apply on every save. Use this to reproduce a
+ * config shaped like it predates a field (e.g. missing `true_is_failure` entirely).
+ */
+ async seedEvaluation(data: {
+ team_id: string
+ name: string
+ evaluation_type: string
+ evaluation_config: Record<string, any>
+ output_type: string
+ output_config: Record<string, any>
+ enabled?: boolean
+ }): Promise<{ evaluation_id: string }> {
+ const result = await this.callSetupEndpoint('seed_evaluation', {
+ data: { ...data, team_id: Number(data.team_id) },
+ })
+ if (!result.success) {
+ throw new Error(`Failed to seed evaluation: ${result.error}`)
+ }
+ return result.result as { evaluation_id: string }
+ }
+
/**
* Seed a single HogFunctionTemplate row. Templates are global (not team-scoped) and
* Playwright CI doesn't run sync_hog_function_templates, so any test that exercises
diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.py
index 600cd0090632..1f2a66fe32c6 100644
--- a/posthog/temporal/ai_observability/eval_reports/activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/activities.py
@@ -621,6 +621,7 @@ async def prepare_report_context_activity(
evaluation_prompt=evaluation.evaluation_config.get("prompt", ""),
evaluation_type=evaluation.evaluation_type,
output_type=evaluation.output_type,
+ true_is_failure=bool(evaluation.output_config.get("true_is_failure")),
period_start=period_start.isoformat(),
period_end=period_end.isoformat(),
previous_period_start=previous_period_start.isoformat(),
@@ -649,7 +650,11 @@ async def run_eval_report_agent_activity(
evaluation_target = _load_evaluation_target(inputs.team_id, inputs.evaluation_id)
return (
- run_eval_report_agent(inputs, evaluation_target=evaluation_target),
+ run_eval_report_agent(
+ inputs,
+ evaluation_target=evaluation_target,
+ detector_evaluation_ids=_load_detector_evaluation_ids(inputs.team_id),
+ ),
evaluation_target,
)
@@ -673,6 +678,22 @@ def _load_evaluation_target(team_id: int, evaluation_id: str) -> str:
return Evaluation.objects.values_list("target", flat=True).get(id=evaluation_id, team_id=team_id)
+def _load_detector_evaluation_ids(team_id: int) -> list[str]:
+ """The generation detail tool lists every evaluation on a generation, not just this report's,
+ so it needs each one's polarity to label it. Read here rather than in the context activity,
+ which would carry the whole team's list through two Temporal payloads to reach this one."""
+ from products.ai_observability.backend.models.evaluations import ( # noqa: PLC0415 -- keep Django model loading inside activity execution
+ Evaluation,
+ )
+
+ return [
+ str(evaluation_id)
+ for evaluation_id in Evaluation.objects.filter(
+ team_id=team_id, output_type="boolean", output_config__true_is_failure=True
+ ).values_list("id", flat=True)
+ ]
+
+
@temporalio.activity.defn
async def store_report_run_activity(
inputs: StoreReportRunInput,
diff --git a/posthog/temporal/ai_observability/eval_reports/output_types.py b/posthog/temporal/ai_observability/eval_reports/output_types.py
index 3d96fb53a86d..8726bc46fa90 100644
--- a/posthog/temporal/ai_observability/eval_reports/output_types.py
+++ b/posthog/temporal/ai_observability/eval_reports/output_types.py
@@ -1,8 +1,15 @@
-"""Trusted query definitions for evaluation report outcomes."""
+"""Trusted query definitions for evaluation report outcomes.
-from collections.abc import Mapping
+Only `outcome_predicates` and `label_for` depend on the evaluation's polarity. `event_predicate`,
+`outcomes`, `result_expression`, `applicable_expression` and `score_expression` do not, so a caller
+that reads only those is correct without passing `true_is_failure`.
+"""
+
+from collections.abc import Callable, Mapping
from dataclasses import dataclass
+SENTIMENT_LABELS = ("positive", "neutral", "negative")
+
@dataclass(frozen=True)
class EvaluationReportOutcomeDefinition:
@@ -12,6 +19,20 @@ class EvaluationReportOutcomeDefinition:
result_expression: str
applicable_expression: str
score_expression: str
+ # Which raw boolean is the desirable outcome, or None for an output type that labels itself.
+ passing_result: bool | None
+
+ def label_for(self, result: object, applicable: object = None) -> str | None:
+ """Map one raw result value to its outcome label, or None when it is not one we report."""
+ if self.passing_result is None:
+ return result if isinstance(result, str) and result in self.outcomes else None
+ if applicable is False:
+ return "na"
+ # Accepts 1/0 alongside True/False: a ClickHouse UInt8 column can hand back an int
+ # for what is logically a boolean result.
+ if result not in (True, False):
+ return None
+ return "pass" if bool(result) is self.passing_result else "fail"
# String comparison is deliberate: an unregistered JSON bool property extracts as the
@@ -19,39 +40,59 @@ class EvaluationReportOutcomeDefinition:
# 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(
+_APPLICABLE_PREDICATE = (
+ "(isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)"
+)
+
+
+def _boolean_definition(true_is_failure: bool) -> EvaluationReportOutcomeDefinition:
+ passing_result = not true_is_failure
+ pass_literal = "true" if passing_result else "false"
+ fail_literal = "false" if passing_result else "true"
+ return EvaluationReportOutcomeDefinition(
outcomes=("pass", "fail", "na"),
outcome_predicates={
- "pass": "properties.$ai_evaluation_result = true AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)",
- "fail": "properties.$ai_evaluation_result = false AND (isNull(properties.$ai_evaluation_applicable) OR properties.$ai_evaluation_applicable != false)",
+ "pass": f"properties.$ai_evaluation_result = {pass_literal} AND {_APPLICABLE_PREDICATE}",
+ "fail": f"properties.$ai_evaluation_result = {fail_literal} AND {_APPLICABLE_PREDICATE}",
"na": "properties.$ai_evaluation_applicable = false",
},
- event_predicate=f"(properties.$ai_evaluation_result_type = 'boolean' OR isNull(properties.$ai_evaluation_result_type)) AND {_NOT_SKIPPED_PREDICATE}",
+ event_predicate=(
+ "(properties.$ai_evaluation_result_type = 'boolean' OR isNull(properties.$ai_evaluation_result_type)) "
+ f"AND {_NOT_SKIPPED_PREDICATE}"
+ ),
result_expression="properties.$ai_evaluation_result",
applicable_expression="properties.$ai_evaluation_applicable",
score_expression="NULL",
- ),
- "sentiment": EvaluationReportOutcomeDefinition(
- outcomes=("positive", "neutral", "negative"),
- outcome_predicates={
- "positive": "properties.$ai_sentiment_label = 'positive'",
- "neutral": "properties.$ai_sentiment_label = 'neutral'",
- "negative": "properties.$ai_sentiment_label = 'negative'",
- },
+ passing_result=passing_result,
+ )
+
+
+def _sentiment_definition(true_is_failure: bool) -> EvaluationReportOutcomeDefinition:
+ return EvaluationReportOutcomeDefinition(
+ outcomes=SENTIMENT_LABELS,
+ outcome_predicates={label: f"properties.$ai_sentiment_label = '{label}'" for label in SENTIMENT_LABELS},
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",
- ),
+ passing_result=None,
+ )
+
+
+_DEFINITION_BUILDERS: Mapping[str, Callable[[bool], EvaluationReportOutcomeDefinition]] = {
+ "boolean": _boolean_definition,
+ "sentiment": _sentiment_definition,
}
-SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = tuple(_OUTCOME_DEFINITIONS)
+SUPPORTED_EVAL_REPORT_OUTPUT_TYPES = tuple(_DEFINITION_BUILDERS)
-def get_outcome_definition(output_type: str | None) -> EvaluationReportOutcomeDefinition:
+def get_outcome_definition(
+ output_type: str | None, *, true_is_failure: bool = False
+) -> EvaluationReportOutcomeDefinition:
normalized_output_type = output_type or "boolean"
try:
- return _OUTCOME_DEFINITIONS[normalized_output_type]
+ builder = _DEFINITION_BUILDERS[normalized_output_type]
except KeyError as error:
raise ValueError(f"Unsupported evaluation report output type: {normalized_output_type}") from error
+ return builder(true_is_failure)
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
index fa4abca7d2f8..4fd30a34b4dd 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py
@@ -1,6 +1,7 @@
"""LangGraph agent for evaluation report generation using create_react_agent."""
import uuid
+from collections.abc import Sequence
from typing import Any
import structlog
@@ -47,6 +48,7 @@ def _compute_metrics(
period_end: str,
previous_period_start: str,
output_type: str = "boolean",
+ true_is_failure: bool = False,
evaluation_target: str = GENERATION_TARGET,
) -> EvalReportMetrics | None:
"""Compute report metrics directly via HogQL (independent of agent state).
@@ -59,7 +61,7 @@ def _compute_metrics(
ts_start = _ch_ts(period_start)
ts_end = _ch_ts(period_end)
ts_prev_start = _ch_ts(previous_period_start)
- definition = get_outcome_definition(output_type)
+ definition = get_outcome_definition(output_type, true_is_failure=true_is_failure)
result_counts, total = _fetch_period_summary(
team_id, evaluation_id, ts_start, ts_end, definition, evaluation_target
@@ -222,6 +224,7 @@ def _validate_agent_output(content: EvalReportContent, handled_ids: set[str] | N
def run_eval_report_agent(
inputs: RunEvalReportAgentInput,
evaluation_target: str = "generation",
+ detector_evaluation_ids: Sequence[str] = (),
) -> EvalReportContent:
"""Run the evaluation report agent and return the generated content.
@@ -244,6 +247,7 @@ def run_eval_report_agent(
inputs.period_end,
inputs.previous_period_start,
output_type=inputs.output_type,
+ true_is_failure=inputs.true_is_failure,
evaluation_target=evaluation_target,
)
@@ -289,6 +293,7 @@ def run_eval_report_agent(
period_start=inputs.period_start,
period_end=inputs.period_end,
report_prompt_guidance=inputs.report_prompt_guidance,
+ true_is_failure=inputs.true_is_failure,
)
agent = create_react_agent(
@@ -311,6 +316,8 @@ def run_eval_report_agent(
"evaluation_type": inputs.evaluation_type,
"evaluation_target": evaluation_target,
"output_type": inputs.output_type,
+ "true_is_failure": inputs.true_is_failure,
+ "detector_evaluation_ids": list(detector_evaluation_ids),
"period_start": inputs.period_start,
"period_end": inputs.period_end,
"previous_period_start": inputs.previous_period_start,
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
index 47913c6ba7b0..1a8430701fd4 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py
@@ -86,8 +86,9 @@ def build_eval_report_system_prompt(
period_end: str,
evaluation_target: str = "generation",
report_prompt_guidance: str = "",
+ true_is_failure: bool = False,
) -> str:
- definition = get_outcome_definition(output_type)
+ definition = get_outcome_definition(output_type, true_is_failure=true_is_failure)
description_section = f"Description: {evaluation_description}\n" if evaluation_description else ""
prompt_section = f"Evaluation prompt/criteria:\n```\n{evaluation_prompt}\n```\n" if evaluation_prompt else ""
guidance_section = ""
@@ -135,11 +136,18 @@ def build_eval_report_system_prompt(
)
elif output_type == "boolean":
evaluated_unit = get_target_descriptor(evaluation_target).unit_label
- result_semantics = (
- f"The evaluation returns a boolean. True means the {evaluated_unit} satisfied the configured criteria and false "
- "means it did not. A fail is not inherently bad: always interpret pass and fail through the evaluation's "
- "specific criteria rather than treating them as generic quality verdicts."
- )
+ if true_is_failure:
+ result_semantics = (
+ f"This evaluation looks for a problem. A true result means the {evaluated_unit} matched the "
+ "condition it looks for, so it is reported as a fail, and a false result is reported as a pass. "
+ "The fail rate is how often the condition fired, not a generic quality score."
+ )
+ else:
+ result_semantics = (
+ f"The evaluation returns a boolean. True means the {evaluated_unit} satisfied the configured criteria "
+ "and false means it did not. A fail is not inherently bad: always interpret pass and fail through the "
+ "evaluation's specific criteria rather than treating them as generic quality verdicts."
+ )
analysis_outcome = "fail"
primary_outcome = "pass"
reasoning_tool_section = (
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
index 4b661f6bef42..7aab5126ddf2 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py
@@ -30,6 +30,8 @@ class EvalReportAgentState(TypedDict):
evaluation_type: str
evaluation_target: str
output_type: str
+ true_is_failure: bool
+ detector_evaluation_ids: list[str]
period_start: str
period_end: str
previous_period_start: str
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index f0d941135825..963a89749e25 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -1,5 +1,6 @@
"""Tests for the v2 eval report agent output tools (set_title, add_section, add_citation)."""
+import re
import json
import time
import datetime as dt
@@ -39,6 +40,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (
_dead_backticked_ids,
_execute_ch_query_with_retry,
_is_retriable_ch_error,
+ _label_generation_evals,
_widened_ts_window,
add_citation,
add_section,
@@ -244,6 +246,54 @@ class TestSummaryMetrics(SimpleTestCase):
self.assertIn("properties.$ai_evaluation_result_type = 'sentiment'", current_query)
self.assertNotIn("properties.$ai_evaluation_result = true", current_query)
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_detector_polarity_counts_a_false_result_as_the_pass(self, mock_execute_hogql):
+ # 18 clean and 80 flagged results: a detector reports the 80 flagged ones as fails.
+ mock_execute_hogql.side_effect = [
+ [[18, 80, 2, 100]],
+ [[2, 7, 1, 10]],
+ ]
+ state = {
+ "team_id": 1,
+ "evaluation_id": "eval-id",
+ "output_type": "boolean",
+ "true_is_failure": True,
+ "period_start": "2026-04-08T14:00:00+00:00",
+ "period_end": "2026-04-08T15:00:00+00:00",
+ "previous_period_start": "2026-04-08T13:00:00+00:00",
+ }
+
+ result = json.loads(_get_summary_metrics_fn(state=state))
+
+ self.assertEqual(result["current_period"]["result_counts"], {"pass": 18, "fail": 80, "na": 2})
+ self.assertEqual(result["current_period"]["pass_rate"], 18.37)
+ pass_column = re.search(r"countIf\((.*?)\) as pass_count", mock_execute_hogql.call_args_list[0].args[1], re.S)
+ assert pass_column is not None
+ self.assertIn("properties.$ai_evaluation_result = false", pass_column.group(1))
+
+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")
+ def test_state_without_polarity_counts_a_true_result_as_the_pass(self, mock_execute_hogql):
+ # A report started before the field existed replays with no polarity key at all.
+ mock_execute_hogql.side_effect = [
+ [[80, 18, 2, 100]],
+ [[7, 2, 1, 10]],
+ ]
+ state = {
+ "team_id": 1,
+ "evaluation_id": "eval-id",
+ "output_type": "boolean",
+ "period_start": "2026-04-08T14:00:00+00:00",
+ "period_end": "2026-04-08T15:00:00+00:00",
+ "previous_period_start": "2026-04-08T13:00:00+00:00",
+ }
+
+ result = json.loads(_get_summary_metrics_fn(state=state))
+
+ self.assertEqual(result["current_period"]["result_counts"], {"pass": 80, "fail": 18, "na": 2})
+ pass_column = re.search(r"countIf\((.*?)\) as pass_count", mock_execute_hogql.call_args_list[0].args[1], re.S)
+ assert pass_column is not None
+ self.assertIn("properties.$ai_evaluation_result = true", pass_column.group(1))
+
class TestTargetAwareEvalResults(SimpleTestCase):
def _state(self, evaluation_target: str, output_type: str = "boolean") -> dict:
@@ -1247,3 +1297,29 @@ class TestToolsCoordinate(SimpleTestCase):
self.assertEqual(len(report.sections), 2)
self.assertIsInstance(report.sections[0], ReportSection)
self.assertEqual(len(report.citations), 1)
+
+
+class TestLabelGenerationEvals(SimpleTestCase):
+ # (eval_id, result_type, result, sentiment_label, sentiment_score, reasoning, applicable)
+ ROWS: list[list[object]] = [
+ ["detector-eval", "boolean", True, None, None, "struggled", None],
+ ["quality-eval", "boolean", True, None, None, "accurate", None],
+ ["sentiment-eval", "sentiment", None, "negative", 0.9, "", None],
+ ]
+
+ def test_each_evaluation_is_labeled_by_its_own_polarity(self):
+ labeled = _label_generation_evals(self.ROWS, {"detector-eval"})
+
+ outcomes = {row["evaluation_id"]: row["outcome"] for row in labeled}
+ self.assertEqual(outcomes, {"detector-eval": "fail", "quality-eval": "pass", "sentiment-eval": "negative"})
+
+ def test_no_detectors_keeps_every_true_result_a_pass(self):
+ labeled = _label_generation_evals(self.ROWS, set())
+
+ outcomes = {row["evaluation_id"]: row["outcome"] for row in labeled}
+ self.assertEqual(outcomes, {"detector-eval": "pass", "quality-eval": "pass", "sentiment-eval": "negative"})
+
+ def test_unsupported_output_type_is_dropped(self):
+ labeled = _label_generation_evals([["numeric-eval", "numeric", 1, None, None, "", None]], set())
+
+ self.assertEqual(labeled, [])
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 8da6284993c7..9edd997f5730 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -11,7 +11,7 @@ import re
import json
import time
import random
-from collections.abc import Callable, Iterable
+from collections.abc import Callable, Container, Iterable, Sequence
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Annotated, Literal, TypeVar
@@ -174,9 +174,10 @@ _TARGET_LOOKUP_TS_START_SENTINEL = "2020-01-01T00:00:00+00:00"
_TARGET_LOOKUP_TS_END_SENTINEL = "2099-01-01T00:00:00+00:00"
-def _resolve_output_type(output_type: str | None) -> tuple[str, EvaluationReportOutcomeDefinition]:
- normalized_output_type = output_type or "boolean"
- return normalized_output_type, get_outcome_definition(normalized_output_type)
+def _definition_from_state(state: dict) -> tuple[str, EvaluationReportOutcomeDefinition]:
+ """Resolve the report's output type and outcome definition. The only reader of the state's polarity."""
+ output_type = state.get("output_type") or "boolean"
+ return output_type, get_outcome_definition(output_type, true_is_failure=bool(state.get("true_is_failure")))
def _summary_select_sql(definition: EvaluationReportOutcomeDefinition) -> str:
@@ -204,18 +205,6 @@ def _summary_value_as_int(value: int | float | str | None) -> int:
return int(value) if value is not None else 0
-def _outcome_for_result(output_type: str, result: object, applicable: object = None) -> str | None:
- if output_type == "sentiment":
- return result if isinstance(result, str) and result in ("positive", "neutral", "negative") else None
- if applicable is False:
- return "na"
- outcomes_by_result: dict[object, str] = {True: "pass", False: "fail"}
- try:
- return outcomes_by_result.get(result)
- except TypeError:
- return None
-
-
@frozen
class TimestampWindow:
ts_start: datetime
@@ -421,7 +410,7 @@ def get_summary_metrics(
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
ts_prev_start = _ch_ts(state["previous_period_start"])
- output_type, definition = _resolve_output_type(state.get("output_type"))
+ output_type, definition = _definition_from_state(state)
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
result_counts, total = _fetch_period_summary(
@@ -457,7 +446,7 @@ def get_result_distribution_over_time(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
- output_type, definition = _resolve_output_type(state.get("output_type"))
+ output_type, definition = _definition_from_state(state)
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
# Whitelisted truncation function — `bucket` is an LLM-controlled arg, so pick
@@ -518,7 +507,7 @@ def list_all_eval_results(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
- output_type, definition = _resolve_output_type(state.get("output_type"))
+ output_type, definition = _definition_from_state(state)
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
shared_placeholders = {
@@ -576,7 +565,7 @@ def list_all_eval_results(
lines = []
for row in rows:
target_id = str(row[0]) if row[0] else "?"
- outcome = _outcome_for_result(output_type, row[1], row[2]) or "?"
+ outcome = definition.label_for(row[1], row[2]) or "?"
score = f" ({row[3]:.2f})" if isinstance(row[3], int | float) else ""
fields = [f"{outcome}{score}", target_id]
if output_type != "sentiment":
@@ -615,7 +604,7 @@ def sample_eval_results(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
- output_type, definition = _resolve_output_type(state.get("output_type"))
+ output_type, definition = _definition_from_state(state)
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
if order_by == "score" and output_type != "sentiment":
return json.dumps({"error": "Score ordering is only available for sentiment results"})
@@ -664,7 +653,7 @@ def sample_eval_results(
for row in rows:
entry = {
target_id_key: str(row[0]) if row[0] else "",
- "outcome": _outcome_for_result(output_type, row[1], row[3]),
+ "outcome": definition.label_for(row[1], row[3]),
}
if output_type == "sentiment":
entry["score"] = row[4]
@@ -787,6 +776,31 @@ def sample_generation_details(
return json.dumps(result, indent=2)
+def _label_generation_evals(
+ eval_rows: Sequence[Sequence[object]], detector_evaluation_ids: Container[str]
+) -> list[dict]:
+ """Label every evaluation on one generation, each by its own polarity."""
+ labeled = []
+ for row in eval_rows:
+ output_type = str(row[1]) if row[1] else "boolean"
+ evaluation_id = str(row[0]) if row[0] else ""
+ try:
+ definition = get_outcome_definition(output_type, true_is_failure=evaluation_id in detector_evaluation_ids)
+ except ValueError:
+ continue
+ raw_result = row[3] if output_type == "sentiment" else row[2]
+ entry = {
+ "evaluation_id": evaluation_id,
+ "output_type": output_type,
+ "outcome": definition.label_for(raw_result, row[6]),
+ "reasoning": row[5] or "",
+ }
+ if output_type == "sentiment":
+ entry["score"] = row[4]
+ labeled.append(entry)
+ return labeled
+
+
@tool
def get_generation_detail(
state: Annotated[dict, InjectedState],
@@ -898,23 +912,7 @@ def get_generation_detail(
placeholders=shared_placeholders,
)
- evals = []
- for er in eval_rows:
- output_type = str(er[1]) if er[1] else "boolean"
- try:
- get_outcome_definition(output_type)
- except ValueError:
- continue
- raw_result = er[3] if output_type == "sentiment" else er[2]
- entry = {
- "evaluation_id": str(er[0]) if er[0] else "",
- "output_type": output_type,
- "outcome": _outcome_for_result(output_type, raw_result, er[6]),
- "reasoning": er[5] or "",
- }
- if output_type == "sentiment":
- entry["score"] = er[4]
- evals.append(entry)
+ evals = _label_generation_evals(eval_rows, set(state.get("detector_evaluation_ids") or []))
result: dict = {
"generation_id": str(row[0]) if row[0] else "",
@@ -1416,7 +1414,7 @@ def get_top_outcome_reasons(
evaluation_id = state["evaluation_id"]
ts_start = _ch_ts(state["period_start"])
ts_end = _ch_ts(state["period_end"])
- output_type, definition = _resolve_output_type(state.get("output_type"))
+ output_type, definition = _definition_from_state(state)
evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))
selected_outcome = outcome or ("negative" if output_type == "sentiment" else "fail")
outcome_predicate = definition.outcome_predicates.get(selected_outcome)
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 c06baca4bb5b..eea9fabb0dae 100644
--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, Mock, patch
from django.test import SimpleTestCase
from django.utils import timezone
+from asgiref.sync import sync_to_async
from parameterized import parameterized
from posthog.exceptions import ClickHouseQueryTimeOut
@@ -20,9 +21,11 @@ from posthog.temporal.ai_observability.eval_reports.activities import (
_CountEntry,
_fetch_count_triggered_eval_report_candidate_groups,
_find_nth_eval_timestamp,
+ _load_detector_evaluation_ids,
_load_evaluation_target,
_period_for_scheduled_report,
_update_next_delivery_date,
+ prepare_report_context_activity,
run_eval_report_agent_activity,
store_report_run_activity,
)
@@ -33,6 +36,7 @@ from posthog.temporal.ai_observability.eval_reports.constants import (
from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics
from posthog.temporal.ai_observability.eval_reports.targets import target_event_predicate
from posthog.temporal.ai_observability.eval_reports.types import (
+ PrepareReportContextInput,
RunEvalReportAgentInput,
StoreReportRunInput,
UpdateNextDeliveryDateInput,
@@ -126,6 +130,26 @@ class TestEvaluationTargetLoading(BaseTest):
self.assertEqual(target, "trace")
+ def test_loads_only_the_team_evaluations_that_declare_true_a_failure(self) -> None:
+ def _evaluation(name: str, output_config: dict) -> Evaluation:
+ return Evaluation.objects.create(
+ team=self.team,
+ name=name,
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "test prompt"},
+ output_type="boolean",
+ output_config=output_config,
+ enabled=True,
+ created_by=self.user,
+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
+ )
+
+ detector = _evaluation("Detector", {"true_is_failure": True})
+ _evaluation("Quality check", {"true_is_failure": False})
+ _evaluation("Legacy config", {})
+
+ self.assertEqual(_load_detector_evaluation_ids(self.team.id), [str(detector.id)])
+
@pytest.mark.parametrize(
"target,expected",
@@ -180,6 +204,10 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
"posthog.temporal.ai_observability.eval_reports.activities._load_evaluation_target",
return_value=evaluation_target,
) as load_target,
+ patch(
+ "posthog.temporal.ai_observability.eval_reports.activities._load_detector_evaluation_ids",
+ return_value=["detector-id"],
+ ) as load_detectors,
):
result = await run_eval_report_agent_activity(inputs)
@@ -188,7 +216,9 @@ async def test_run_agent_activity_loads_target_and_forwards_output_type(
assert result.generation_status == "completed"
assert run_agent.call_args.args[0] is inputs
assert run_agent.call_args.kwargs["evaluation_target"] == evaluation_target
+ assert run_agent.call_args.kwargs["detector_evaluation_ids"] == ["detector-id"]
load_target.assert_called_once_with(inputs.team_id, inputs.evaluation_id)
+ load_detectors.assert_called_once_with(inputs.team_id)
@pytest.mark.asyncio
@@ -489,6 +519,37 @@ class TestPrepareReportContext(BaseTest):
self.assertEqual(result["team_id"], self.team.id)
[email protected]_db(transaction=True)
+async def test_prepare_activity_reads_detector_polarity_from_evaluation(team, user) -> None:
+ def _create_report() -> EvaluationReport:
+ evaluation = Evaluation.objects.create(
+ team=team,
+ name="Detector Eval",
+ evaluation_type="llm_judge",
+ evaluation_config={"prompt": "test prompt"},
+ output_type="boolean",
+ output_config={"true_is_failure": True},
+ enabled=True,
+ created_by=user,
+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],
+ )
+ return EvaluationReport.objects.create(
+ team=team,
+ evaluation=evaluation,
+ frequency=EvaluationReport.Frequency.SCHEDULED,
+ rrule="FREQ=HOURLY",
+ starts_at=timezone.now() - dt.timedelta(hours=5),
+ delivery_targets=[{"type": "email", "value": "[email protected]"}],
+ )
+
+ report = await sync_to_async(_create_report)()
+
+ context = await prepare_report_context_activity(PrepareReportContextInput(report_id=str(report.id)))
+
+ assert context.true_is_failure is True
+
+
class TestCountTriggeredReportChecks(BaseTest):
def _create_report(self, team: Team | None = None, **kwargs) -> EvaluationReport:
team = team or self.team
diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py b/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py
new file mode 100644
index 000000000000..e0aa860e0da4
--- /dev/null
+++ b/posthog/temporal/ai_observability/eval_reports/test/test_output_types.py
@@ -0,0 +1,82 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.temporal.ai_observability.eval_reports.output_types import (
+ SUPPORTED_EVAL_REPORT_OUTPUT_TYPES,
+ get_outcome_definition,
+)
+
+
+class TestOutcomeDefinitions(SimpleTestCase):
+ def test_absent_polarity_keeps_true_as_the_pass(self):
+ definition = get_outcome_definition("boolean")
+ self.assertIn("properties.$ai_evaluation_result = true", definition.outcome_predicates["pass"])
+ self.assertIn("properties.$ai_evaluation_result = false", definition.outcome_predicates["fail"])
+ self.assertEqual(definition.label_for(True), "pass")
+ self.assertEqual(definition.label_for(False), "fail")
+
+ def test_detector_polarity_makes_true_the_fail(self):
+ definition = get_outcome_definition("boolean", true_is_failure=True)
+ self.assertIn("properties.$ai_evaluation_result = false", definition.outcome_predicates["pass"])
+ self.assertIn("properties.$ai_evaluation_result = true", definition.outcome_predicates["fail"])
+ self.assertEqual(definition.label_for(True), "fail")
+ self.assertEqual(definition.label_for(False), "pass")
+
+ @parameterized.expand([(False,), (True,)])
+ def test_not_applicable_wins_over_polarity(self, true_is_failure: bool):
+ definition = get_outcome_definition("boolean", true_is_failure=true_is_failure)
+ self.assertEqual(definition.label_for(True, applicable=False), "na")
+ self.assertEqual(definition.label_for(False, applicable=False), "na")
+
+ @parameterized.expand([(False,), (True,)])
+ def test_polarity_does_not_touch_sentiment(self, true_is_failure: bool):
+ definition = get_outcome_definition("sentiment", true_is_failure=true_is_failure)
+ self.assertEqual(definition.outcomes, ("positive", "neutral", "negative"))
+ self.assertEqual(definition.label_for("negative"), "negative")
+ self.assertIsNone(definition.label_for("nonsense"))
+
+ @parameterized.expand([(None,), ("true",), (2,)])
+ def test_non_boolean_result_has_no_label(self, result: object):
+ definition = get_outcome_definition("boolean")
+ self.assertIsNone(definition.label_for(result))
+
+ def test_integer_boolean_result_gets_a_label(self):
+ # A ClickHouse UInt8 column can hand back an int for a logically boolean result.
+ definition = get_outcome_definition("boolean")
+ self.assertEqual(definition.label_for(1), "pass")
+ self.assertEqual(definition.label_for(0), "fail")
+
+ def test_supported_types_are_derived_from_the_builders(self):
+ self.assertEqual(set(SUPPORTED_EVAL_REPORT_OUTPUT_TYPES), {"boolean", "sentiment"})
+ for output_type in SUPPORTED_EVAL_REPORT_OUTPUT_TYPES:
+ self.assertIsNotNone(get_outcome_definition(output_type))
+
+ def test_unsupported_type_raises(self):
+ with self.assertRaises(ValueError):
+ get_outcome_definition("numeric")
+
+
+class TestReportPromptPolarity(SimpleTestCase):
+ def _prompt(self, *, true_is_failure: bool) -> str:
+ from posthog.temporal.ai_observability.eval_reports.report_agent.prompts import build_eval_report_system_prompt
+
+ return build_eval_report_system_prompt(
+ evaluation_name="Struggle detector",
+ evaluation_description="",
+ evaluation_prompt="",
+ evaluation_type="llm_judge",
+ output_type="boolean",
+ period_start="2026-04-08T14:00:00+00:00",
+ period_end="2026-04-08T15:00:00+00:00",
+ true_is_failure=true_is_failure,
+ )
+
+ def test_detector_prompt_says_a_true_result_is_reported_as_a_fail(self):
+ prompt = self._prompt(true_is_failure=True)
+ self.assertIn("reported as a fail", prompt)
+
+ def test_default_prompt_keeps_the_pass_on_true_story(self):
+ prompt = self._prompt(true_is_failure=False)
+ self.assertIn("satisfied the configured criteria", prompt)
+ self.assertNotIn("reported as a fail", prompt)
diff --git a/posthog/temporal/ai_observability/eval_reports/types.py b/posthog/temporal/ai_observability/eval_reports/types.py
index b5c181ecd45c..288da7844fe7 100644
--- a/posthog/temporal/ai_observability/eval_reports/types.py
+++ b/posthog/temporal/ai_observability/eval_reports/types.py
@@ -3,6 +3,8 @@
import dataclasses
from typing import Any
+from posthog.dataclasses import frozen
+
@dataclasses.dataclass
class ScheduleAllEvalReportsWorkflowInputs:
@@ -51,7 +53,7 @@ class PrepareReportContextInput:
manual: bool = False
+@frozen
class PrepareReportContextOutput:
report_id: str
team_id: int
@@ -65,9 +67,10 @@ class PrepareReportContextOutput:
previous_period_start: str
report_prompt_guidance: str = ""
output_type: str = "boolean"
+ true_is_failure: bool = False
+@frozen
class RunEvalReportAgentInput:
report_id: str
team_id: int
@@ -81,6 +84,7 @@ class RunEvalReportAgentInput:
previous_period_start: str
report_prompt_guidance: str = ""
output_type: str = "boolean"
+ true_is_failure: bool = False
trace_id: str = ""
session_id: str = ""
diff --git a/posthog/temporal/ai_observability/eval_reports/workflow.py b/posthog/temporal/ai_observability/eval_reports/workflow.py
index c26c14f32fbe..ba38e91b317e 100644
--- a/posthog/temporal/ai_observability/eval_reports/workflow.py
+++ b/posthog/temporal/ai_observability/eval_reports/workflow.py
@@ -315,6 +315,7 @@ class GenerateAndDeliverEvalReportWorkflow(PostHogWorkflow):
evaluation_prompt=context.evaluation_prompt,
evaluation_type=context.evaluation_type,
output_type=context.output_type,
+ true_is_failure=context.true_is_failure,
period_start=context.period_start,
period_end=context.period_end,
previous_period_start=context.previous_period_start,
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index a75044f1ec06..b620446df959 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -297,7 +297,7 @@ class TestRunEvaluationWorkflow:
assert result["evaluation_type"] == "llm_judge"
assert result["evaluation_config"] == {"prompt": "Is this response factually accurate?"}
assert result["output_type"] == "boolean"
- assert result["output_config"] == {"allows_na": False}
+ assert result["output_config"] == {"allows_na": False, "true_is_failure": False}
@pytest.mark.django_db(transaction=True)
def test_execute_llm_judge_activity(self, setup_data, active_key_config):
diff --git a/posthog/test/playwright_setup_functions.py b/posthog/test/playwright_setup_functions.py
index b393f6bcad45..061421a185f7 100644
--- a/posthog/test/playwright_setup_functions.py
+++ b/posthog/test/playwright_setup_functions.py
@@ -252,7 +252,7 @@ def create_organization_with_team(
created_variables = _create_variables(data, team)
created_insights = _create_insights(data, team, user, created_variables)
created_dashboards = _create_dashboards(data, team, user, created_variables, created_insights)
- _create_events_and_persons(data, team)
+ _create_events_and_persons(data.events, data.persons, team)
created_experiments = _create_experiments(data, team, user)
return PlaywrightWorkspaceSetupResult(
@@ -437,45 +437,68 @@ def _wait_for_events_in_clickhouse(team_id: int, expected_count: int, timeout_se
)
-def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -> None:
- if not data.events and not data.persons:
+def _create_events_and_persons(
+ events: list[PlaywrightSetupEvent] | None, persons: list[PlaywrightSetupPerson] | None, team: Team
+) -> None:
+ if not events and not persons:
return
import uuid as uuid_module
from posthog.models.event.util import create_event
- from posthog.models.person.util import create_person, create_person_distinct_id
+ from posthog.models.person.util import create_person, create_person_distinct_id, get_persons_mapped_by_distinct_id
from posthog.models.utils import UUIDT
from posthog.test.persons import (
add_distinct_id,
create_person as create_test_person,
)
- person_uuids: dict[str, str] = {}
+ # The harness retries a 500 (e.g. a transient ClickHouse blip during the insert loop
+ # below) up to 3 times. Person/distinct-id rows already committed to Postgres by an
+ # earlier attempt must not be recreated — the unique_distinct_id_for_team constraint
+ # would reject it, turning a retryable failure into a hard one and burying the
+ # original error under a confusing one. Look up what already exists first and reuse
+ # it, so a retry is a no-op for anything the previous attempt already seeded.
+ all_requested_distinct_ids = list(
+ {distinct_id for person_spec in (persons or []) for distinct_id in person_spec.distinct_ids}
+ | {event_spec.distinct_id for event_spec in (events or [])}
+ )
+ person_uuids: dict[str, str] = {
+ distinct_id: str(existing_person.uuid)
+ for distinct_id, existing_person in (
+ get_persons_mapped_by_distinct_id(team.pk, all_requested_distinct_ids).items()
+ if all_requested_distinct_ids
+ else []
+ )
+ }
# Create explicit persons (may have multiple distinct IDs)
- if data.persons:
- for person_spec in data.persons:
+ if persons:
+ for person_spec in persons:
+ if all(distinct_id in person_uuids for distinct_id in person_spec.distinct_ids):
+ continue
person_uuid = str(UUIDT())
props = person_spec.properties or {}
create_person(team_id=team.pk, version=0, uuid=person_uuid, properties=props)
pg_person = create_test_person(team=team, uuid=person_uuid, properties=props)
for distinct_id in person_spec.distinct_ids:
+ if distinct_id in person_uuids:
+ continue
create_person_distinct_id(team_id=team.pk, distinct_id=distinct_id, person_id=person_uuid)
add_distinct_id(person=pg_person, distinct_id=distinct_id)
person_uuids[distinct_id] = person_uuid
- if not data.events:
+ if not events:
return
# Collect person properties from $set in event properties (last write wins)
person_props: dict[str, dict[str, Any]] = {}
- for event_spec in data.events:
+ for event_spec in events:
if event_spec.properties and "$set" in event_spec.properties:
person_props.setdefault(event_spec.distinct_id, {}).update(event_spec.properties["$set"])
- # Create persons for distinct_ids not already created via explicit persons
- distinct_ids = {e.distinct_id for e in data.events}
+ # Create persons for distinct_ids not already created via explicit persons or a prior attempt
+ distinct_ids = {e.distinct_id for e in events}
for distinct_id in distinct_ids:
if distinct_id in person_uuids:
continue
@@ -489,7 +512,7 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -
baseline_count = _count_events_in_clickhouse(team.pk)
- for event_spec in data.events:
+ for event_spec in events:
ts = datetime.fromisoformat(event_spec.timestamp.replace("Z", "+00:00"))
create_event(
event_uuid=UUIDT(unix_time_ms=int(ts.timestamp() * 1000)),
@@ -501,7 +524,7 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -
person_id=uuid_module.UUID(person_uuids[event_spec.distinct_id]),
)
- _wait_for_events_in_clickhouse(team.pk, baseline_count + len(data.events))
+ _wait_for_events_in_clickhouse(team.pk, baseline_count + len(events))
# Populate event/property definitions so the taxonomic filter works
from products.demo.backend.facade.api import infer_taxonomy_for_team
@@ -510,6 +533,64 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -
infer_taxonomy_for_team(team.pk)
+class PlaywrightSeedEventsData(BaseModel):
+ team_id: int
+ events: list[PlaywrightSetupEvent]
+ persons: list[PlaywrightSetupPerson] | None = None
+
+
+class PlaywrightSeedEventsResult(BaseModel):
+ team_id: int
+ events_created: int
+
+
+def seed_events(data: PlaywrightSeedEventsData) -> PlaywrightSeedEventsResult:
+ """Seed events (and optional persons) directly into ClickHouse for a team created earlier in
+ the same test. Use this when an event must reference an id minted after workspace setup (e.g.
+ an evaluation created through the API), so it can't be seeded via `events` on
+ `organization_with_team`, which only runs at workspace-creation time."""
+ team = Team.objects.get(id=data.team_id)
+ _create_events_and_persons(data.events, data.persons, team)
+ return PlaywrightSeedEventsResult(team_id=data.team_id, events_created=len(data.events))
+
+
+class PlaywrightSeedEvaluationData(BaseModel):
+ team_id: int
+ name: str
+ evaluation_type: str
+ evaluation_config: dict[str, Any]
+ output_type: str
+ output_config: dict[str, Any]
+ enabled: bool = False
+
+
+class PlaywrightSeedEvaluationResult(BaseModel):
+ evaluation_id: str
+
+
+def seed_evaluation(data: PlaywrightSeedEvaluationData) -> PlaywrightSeedEvaluationResult:
+ """Create an Evaluation with `output_config` stored exactly as given, bypassing the config
+ normalization every `save()` call applies. Use this to reproduce a config shaped like it
+ predates a field (e.g. missing `true_is_failure` entirely) — no through-the-app path can
+ produce that shape, since both the API and the model's own `save()` fill in every default."""
+ from products.ai_observability.backend.models.evaluations import Evaluation
+
+ evaluation = Evaluation.objects.create(
+ team_id=data.team_id,
+ name=data.name,
+ evaluation_type=data.evaluation_type,
+ evaluation_config=data.evaluation_config,
+ output_type=data.output_type,
+ output_config=data.output_config,
+ enabled=data.enabled,
+ )
+ # save() just normalized output_config above — overwrite via a queryset update, which bypasses
+ # save(), so the row ends up with exactly the caller's shape.
+ Evaluation.objects.filter(pk=evaluation.pk).update(output_config=data.output_config)
+
+ return PlaywrightSeedEvaluationResult(evaluation_id=str(evaluation.pk))
+
+
class PlaywrightHogFunctionTemplateData(BaseModel):
template_id: str
name: str = "Test template"
@@ -623,6 +704,16 @@ PLAYWRIGHT_SETUP_FUNCTIONS: dict[str, SetupFunctionConfig] = {
input_model=PlaywrightHogFunctionTemplateData,
description="Seeds a single HogFunctionTemplate row (templates are global, not team-scoped)",
),
+ "seed_events": SetupFunctionConfig(
+ function=seed_events, # type: ignore
+ input_model=PlaywrightSeedEventsData,
+ description="Seeds events (and optional persons) into ClickHouse for an existing team",
+ ),
+ "seed_evaluation": SetupFunctionConfig(
+ function=seed_evaluation, # type: ignore
+ input_model=PlaywrightSeedEvaluationData,
+ description="Seeds an Evaluation row with output_config stored exactly as given, bypassing save() normalization",
+ ),
"oauth_application": SetupFunctionConfig(
function=create_oauth_application, # type: ignore
input_model=PlaywrightOAuthApplicationData,
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 233a634c590c..7f5c4bfabcbe 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -101,7 +101,7 @@ logger = structlog.get_logger(__name__)
"properties": {
"source": {
"type": "string",
- "description": "Hog source code. Must return true (pass), false (fail), or null for N/A.",
+ "description": "Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
}
},
@@ -139,7 +139,16 @@ class _EvaluationConfigField(serializers.JSONField):
"type": "boolean",
"description": "Whether the evaluation can return N/A for non-applicable generations.",
"default": False,
- }
+ },
+ "true_is_failure": {
+ "type": "boolean",
+ "description": (
+ "Whether a true result means the evaluation found a problem. False (the default) suits "
+ "pass/fail evaluations, where a true result satisfied the criteria. Set it to true for "
+ "detector-style evaluations, so a true result is counted and labeled as a fail."
+ ),
+ "default": False,
+ },
},
"additionalProperties": False,
}
@@ -318,7 +327,10 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
)
output_config = _OutputConfigField(
required=False,
- help_text="Output config. For 'boolean' output_type: {allows_na} to permit N/A results.",
+ help_text=(
+ "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and "
+ "{true_is_failure} to declare that a true result means the evaluation found a problem."
+ ),
)
target_config = _TargetConfigField(
required=False,
@@ -449,6 +461,8 @@ class EvaluationSerializer(UserAccessControlSerializerMixin, serializers.ModelSe
"output_config",
getattr(self.instance, "output_config", {}) if self.instance else {},
)
+ if self.partial and self.instance is not None and "output_config" in data:
+ output_config = {**self.instance.output_config, **output_config}
try:
data["evaluation_config"], data["output_config"] = validate_evaluation_configs(
evaluation_type, output_type, evaluation_config, output_config
@@ -759,7 +773,10 @@ class TestHogRequestSerializer(serializers.Serializer):
source = serializers.CharField(
required=True,
min_length=1,
- help_text="Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.",
+ help_text=(
+ "Hog source code to test. Must return true or false, or null for N/A. "
+ "Output settings determine which boolean counts as a failure."
+ ),
) # type: ignore[assignment]
sample_count = serializers.IntegerField(
required=False,
@@ -810,7 +827,9 @@ class TestHogResultItemSerializer(serializers.Serializer):
trace_id = serializers.CharField(allow_null=True, help_text="Trace ID if available.")
input_preview = serializers.CharField(help_text="First 200 characters of input from the sampled unit.")
output_preview = serializers.CharField(help_text="First 200 characters of output from the sampled unit.")
- result = serializers.BooleanField(allow_null=True, help_text="True = pass, False = fail, null = N/A or error.")
+ result = serializers.BooleanField(
+ allow_null=True, help_text="Raw boolean result, or null when the evaluation returns N/A or raises an error."
+ )
reasoning = serializers.CharField(allow_null=True, help_text="Hog evaluation reasoning string, if any.")
error = serializers.CharField(allow_null=True, help_text="Error message if the Hog code raised an exception.")
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index d8a1983d0fef..cca163537cf8 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -149,7 +149,7 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertEqual(evaluation_config.evaluation_type, "llm_judge")
self.assertEqual(evaluation_config.evaluation_config, {"prompt": "Test prompt"})
self.assertEqual(evaluation_config.output_type, "boolean")
- self.assertEqual(evaluation_config.output_config, {"allows_na": False})
+ self.assertEqual(evaluation_config.output_config, {"allows_na": False, "true_is_failure": False})
self.assertEqual(len(evaluation_config.conditions), 1)
self.assertEqual(evaluation_config.conditions[0]["id"], "test-condition")
self.assertEqual(evaluation_config.team, self.team)
@@ -168,6 +168,42 @@ class TestEvaluationConfigsApi(APIBaseTest):
self.assertFalse(report.deleted)
self.assertEqual(report.delivery_targets, [])
+ @parameterized.expand(
+ [
+ (
+ "allows_na",
+ {"allows_na": False},
+ {"allows_na": False, "true_is_failure": True},
+ ),
+ (
+ "true_is_failure",
+ {"true_is_failure": False},
+ {"allows_na": True, "true_is_failure": False},
+ ),
+ ]
+ )
+ def test_partial_update_preserves_other_output_config_fields(
+ self, _field_name: str, output_config: dict[str, bool], expected: dict[str, bool]
+ ) -> None:
+ evaluation = Evaluation.objects.create(
+ team=self.team,
+ name="Boolean evaluation",
+ evaluation_type="hog",
+ evaluation_config={"source": "return true"},
+ output_type="boolean",
+ output_config={"allows_na": True, "true_is_failure": True},
+ created_by=self.user,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/evaluations/{evaluation.id}/",
+ {"output_config": output_config},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["output_config"], expected)
+
def test_target_defaults_to_generation(self):
response = self.client.post(
f"/api/environments/{self.team.id}/evaluations/",
diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.py
index 16408b06409a..699deaf7eda3 100644
--- a/products/ai_observability/backend/models/evaluation_configs.py
+++ b/products/ai_observability/backend/models/evaluation_configs.py
@@ -51,6 +51,10 @@ class BooleanOutputConfig(BaseModel):
"""Configuration for boolean output type"""
allows_na: bool = False
+ # Detector-style evaluations look for a problem, so their true result is the undesirable one and
+ # must be reported as a fail. Defaulting to False keeps stored configs written before this field
+ # reading exactly as they did, with no backfill and no default to re-supply at each read site.
+ true_is_failure: bool = False
class SentimentEvalConfig(BaseModel):
diff --git a/products/ai_observability/backend/text_repr/formatters/event_formatter.py b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
index b84483d74461..d86c27cc7b70 100644
--- a/products/ai_observability/backend/text_repr/formatters/event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/event_formatter.py
@@ -180,7 +180,7 @@ def format_embedding_text_repr(event: dict[str, Any], options: FormatterOptions
def format_evaluation_text_repr(event: dict[str, Any], options: FormatterOptions | None = None) -> str:
"""
Generate text representation of an evaluation event.
- Shows the evaluation name, result (pass/fail/N/A), and reasoning.
+ Shows the evaluation name, result (true/false/N/A), and reasoning.
"""
lines: list[str] = []
props = event.get("properties", {})
@@ -196,9 +196,9 @@ def format_evaluation_text_repr(event: dict[str, Any], options: FormatterOptions
if applicable is False or applicable == "false":
result_str = "N/A"
elif result is True or result == "true":
- result_str = "PASS"
+ result_str = "true"
elif result is False or result == "false":
- result_str = "FAIL"
+ result_str = "false"
else:
result_str = "UNKNOWN"
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py
index 938a5c666795..78af4c91f15d 100644
--- a/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py
@@ -212,7 +212,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "EVALUATION: Factual accuracy | Result: PASS | Reasoning: The response is factually correct." in result
+ assert "EVALUATION: Factual accuracy | Result: true | Reasoning: The response is factually correct." in result
def test_evaluation_fail_with_reasoning(self):
event = {
@@ -224,7 +224,8 @@ class TestEvaluationFormatting:
}
result = format_evaluation_text_repr(event)
assert (
- "EVALUATION: Relevance check | Result: FAIL | Reasoning: The response does not address the query." in result
+ "EVALUATION: Relevance check | Result: false | Reasoning: The response does not address the query."
+ in result
)
def test_evaluation_na(self):
@@ -246,7 +247,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "EVALUATION: Check | Result: PASS" in result
+ assert "EVALUATION: Check | Result: true" in result
def test_evaluation_no_reasoning(self):
event = {
@@ -256,7 +257,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "EVALUATION: Quick check | Result: PASS" in result
+ assert "EVALUATION: Quick check | Result: true" in result
assert "Reasoning:" not in result
def test_evaluation_missing_name(self):
@@ -266,7 +267,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "EVALUATION: Unknown evaluation | Result: FAIL" in result
+ assert "EVALUATION: Unknown evaluation | Result: false" in result
def test_evaluation_hog_runtime(self):
event = {
@@ -277,7 +278,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "EVALUATION: Length check | Result: PASS (hog)" in result
+ assert "EVALUATION: Length check | Result: true (hog)" in result
def test_evaluation_llm_judge_runtime_with_model(self):
event = {
@@ -290,7 +291,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "Result: FAIL (llm_judge/gpt-4)" in result
+ assert "Result: false (llm_judge/gpt-4)" in result
assert "Reasoning: Claim contradicts source." in result
def test_evaluation_llm_judge_runtime_without_model(self):
@@ -302,7 +303,7 @@ class TestEvaluationFormatting:
}
}
result = format_evaluation_text_repr(event)
- assert "Result: PASS (llm_judge)" in result
+ assert "Result: true (llm_judge)" in result
class TestFormatEventTextReprFromAiEventsRow:
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
index 5249a444489c..c29a308840c6 100644
--- a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py
@@ -129,8 +129,7 @@ class TestGetEventSummary:
},
}
summary = _get_event_summary(event)
- assert "Factual accuracy" in summary
- assert "PASS" in summary
+ assert "Factual accuracy (true)" in summary
def test_evaluation_summary_fail(self):
event = {
@@ -141,8 +140,7 @@ class TestGetEventSummary:
},
}
summary = _get_event_summary(event)
- assert "Relevance" in summary
- assert "FAIL" in summary
+ assert "Relevance (false)" in summary
def test_evaluation_summary_na(self):
event = {
@@ -174,9 +172,7 @@ class TestGetEventSummary:
},
}
summary = _get_event_summary(event)
- assert "Length check" in summary
- assert "hog" in summary
- assert "PASS" in summary
+ assert "Length check (hog, true)" in summary
def test_evaluation_summary_includes_llm_judge_runtime(self):
event = {
@@ -188,9 +184,7 @@ class TestGetEventSummary:
},
}
summary = _get_event_summary(event)
- assert "Factual accuracy" in summary
- assert "llm_judge" in summary
- assert "FAIL" in summary
+ assert "Factual accuracy (llm_judge, false)" in summary
def test_unknown_event_type(self):
"""Should return event type for unknown events."""
diff --git a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
index e397f50db7c2..37ba0d57953e 100644
--- a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
+++ b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py
@@ -277,9 +277,9 @@ def _get_event_summary(event: dict[str, Any]) -> str:
if applicable is False or applicable == "false":
parts.append("N/A")
elif result is True or result == "true":
- parts.append("PASS")
+ parts.append("true")
elif result is False or result == "false":
- parts.append("FAIL")
+ parts.append("false")
summary = eval_name
if parts:
diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.py
index 308dad73d224..0f0837738ed4 100644
--- a/products/ai_observability/backend/tools/run_hog_eval.py
+++ b/products/ai_observability/backend/tools/run_hog_eval.py
@@ -26,7 +26,7 @@ from ee.hogai.tool import MaxTool
TOOL_DESCRIPTION = f"""Test Hog evaluation code against sample data from the last {EVALUATION_TEST_LOOKBACK_DAYS} days.
-Returns compilation errors if the code is invalid, or pass/fail/error results for each sample.
+Returns compilation errors if the code is invalid, or raw true/false/N/A/error results for each sample.
Set `target` to match how the evaluation will run: `generation` samples individual generations,
`trace` samples whole traces, and `session` samples whole sessions that have gone quiet. For
@@ -46,7 +46,7 @@ Saved evaluations can still use the generation-only compatibility globals `input
`properties`, and `event`, but do not use them in new source that should also work for traces
or sessions.
-The code must return a boolean: `true` for pass, `false` for fail.
+The code must return `true` or `false`. Evaluation output settings determine which value counts as a failure.
Use `print()` statements to output reasoning.
"""
@@ -63,9 +63,9 @@ def _format_sample(
if error:
verdict_str = "ERROR"
elif verdict is True:
- verdict_str = "PASS"
+ verdict_str = "true"
elif verdict is False:
- verdict_str = "FAIL"
+ verdict_str = "false"
else:
verdict_str = "N/A"
@@ -261,9 +261,9 @@ class RunHogEvalTestTool(MaxTool):
if result["error"]:
verdict_str = "ERROR"
elif verdict is True:
- verdict_str = "PASS"
+ verdict_str = "true"
elif verdict is False:
- verdict_str = "FAIL"
+ verdict_str = "false"
else:
verdict_str = "N/A"
diff --git a/products/ai_observability/backend/tools/test_run_hog_eval.py b/products/ai_observability/backend/tools/test_run_hog_eval.py
index 68b50b4031c8..4e6e2b7d432c 100644
--- a/products/ai_observability/backend/tools/test_run_hog_eval.py
+++ b/products/ai_observability/backend/tools/test_run_hog_eval.py
@@ -78,9 +78,9 @@ class TestRunHogEvalTestTool(BaseTest):
assert artifact is None
if expected_verdict:
- assert "PASS" in result
+ assert "Result: true" in result
else:
- assert "FAIL" in result
+ assert "Result: false" in result
def test_compilation_error(self):
tool = self._make_tool()
@@ -129,7 +129,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Input:" in result
assert "Output:" in result
- assert "Result: PASS" in result
+ assert "Result: true" in result
@patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_null_return_shows_na(self, mock_query):
@@ -173,7 +173,7 @@ class TestRunHogEvalTestTool(BaseTest):
tool = self._make_tool()
result, artifact = _run_tool(tool, source="return true;", sample_count=1)
- assert "PASS" in result
+ assert "Result: true" in result
assert "$ai_metric" in result
@patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
@@ -215,7 +215,7 @@ class TestRunHogEvalTestTool(BaseTest):
sample_count=1,
)
- assert "Result: PASS" in result, f"expected PASS after heavy-merge, got: {result}"
+ assert "Result: true" in result, f"expected true after heavy-merge, got: {result}"
@patch("posthog.temporal.ai_observability.run_trace_evaluation.run_hog_eval_over_recent_traces")
def test_trace_target_evaluates_whole_traces(self, mock_run_over_traces):
@@ -244,7 +244,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert artifact is None
assert mock_run_over_traces.call_args.kwargs["window_seconds"] == 120
assert "Trace trace-1" in result
- assert "Result: PASS" in result
+ assert "Result: true" in result
@patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
def test_query_targets_ai_events(self, mock_query):
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
index 4b00a0c084f3..e338e68822ac 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.test.tsx
@@ -5,8 +5,29 @@ import { Provider } from 'kea'
import { initKeaTests } from '~/test/init'
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
+import { EvaluationConfig } from '../evaluations/types'
import { EvaluationDisplay } from './EvaluationDisplay'
+const detectorEvaluation: EvaluationConfig = {
+ id: 'eval-detector',
+ name: 'Detects struggle',
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'hog',
+ evaluation_config: { source: 'return true' },
+ output_type: 'boolean',
+ output_config: { true_is_failure: true },
+ conditions: [{ id: 'cond-1', rollout_percentage: 100, properties: [] }],
+ target: 'generation',
+ target_config: {},
+ model_configuration: null,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+}
+
describe('EvaluationDisplay', () => {
beforeEach(() => {
initKeaTests()
@@ -43,4 +64,24 @@ describe('EvaluationDisplay', () => {
expect(screen.getByText('N/A')).toBeInTheDocument()
expect(screen.queryByText('False')).not.toBeInTheDocument()
})
+
+ it('colors a detector true result as danger, matching the badges elsewhere on the page', () => {
+ const evaluationsLogic = llmEvaluationsLogic()
+ evaluationsLogic.mount()
+ evaluationsLogic.actions.loadEvaluationsSuccess([detectorEvaluation])
+
+ render(
+ <Provider>
+ <EvaluationDisplay
+ eventProperties={{ $ai_evaluation_id: 'eval-detector', $ai_evaluation_result: true }}
+ />
+ </Provider>
+ )
+
+ expect(screen.getByText('True')).toBeInTheDocument()
+ expect(document.querySelector('.LemonTag--danger')).toBeInTheDocument()
+ expect(document.querySelector('.LemonTag--success')).not.toBeInTheDocument()
+
+ evaluationsLogic.unmount()
+ })
})
diff --git a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
index f67e8376a123..f614e648e94c 100644
--- a/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
+++ b/products/ai_observability/frontend/ConversationDisplay/EvaluationDisplay.tsx
@@ -1,3 +1,5 @@
+import { useValues } from 'kea'
+
import { Link } from '@posthog/lemon-ui'
import { lowercaseFirstLetter } from 'lib/utils/strings'
@@ -7,14 +9,17 @@ import { EventType } from '~/types'
import { EvaluationResultTag } from '../components/EvaluationResultTag'
import { MetadataTag } from '../components/MetadataTag'
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
import { normalizeEvaluationResultProperties } from '../utils'
export function EvaluationDisplay({ eventProperties }: { eventProperties: EventType['properties'] }): JSX.Element {
+ const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
const reasoning = eventProperties.$ai_evaluation_reasoning
const evaluationName = eventProperties.$ai_evaluation_name
const model = eventProperties.$ai_model ?? eventProperties.$ai_evaluation_model
const traceId = eventProperties.$ai_trace_id
const targetEventId = eventProperties.$ai_target_event_id
+ const evaluationId = eventProperties.$ai_evaluation_id
const resultRun = {
status: 'completed' as const,
...normalizeEvaluationResultProperties({
@@ -30,7 +35,7 @@ export function EvaluationDisplay({ eventProperties }: { eventProperties: EventT
return (
<div className="space-y-4">
<div className="flex flex-wrap gap-2">
- <EvaluationResultTag run={resultRun} />
+ <EvaluationResultTag run={resultRun} trueIsFailure={detectorEvaluationIds.includes(evaluationId)} />
{evaluationName && (
<MetadataTag label="Evaluation" textToCopy={evaluationName}>
{evaluationName}
diff --git a/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx b/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
index 9fd627ca2914..d421d46df956 100644
--- a/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
+++ b/products/ai_observability/frontend/LLMASessionEvaluationsDisplay.tsx
@@ -4,6 +4,7 @@ import { LemonTag, Tooltip } from '@posthog/lemon-ui'
import { aiObservabilitySessionEvaluationsLogic } from './aiObservabilitySessionEvaluationsLogic'
import { EvalTooltipContent, getEvalBadgeProps, getEvalSummaries } from './components/EvalResultBadges'
+import { llmEvaluationsLogic } from './evaluations/llmEvaluationsLogic'
interface LLMASessionEvaluationsDisplayProps {
sessionId: string
@@ -11,6 +12,7 @@ interface LLMASessionEvaluationsDisplayProps {
export function LLMASessionEvaluationsDisplay({ sessionId }: LLMASessionEvaluationsDisplayProps): JSX.Element | null {
const { sessionEvaluations } = useValues(aiObservabilitySessionEvaluationsLogic({ sessionId }))
+ const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
// A session that resumes after being evaluated can be graded again; collapse to the newest
// verdict per evaluation so a stale tag never sits beside a fresh one. Same helper the trace
@@ -24,7 +26,9 @@ export function LLMASessionEvaluationsDisplay({ sessionId }: LLMASessionEvaluati
return (
<>
{summaries.map((summary) => {
- const { type, icon, label } = getEvalBadgeProps(summary.latestRun)
+ const { type, icon, label } = getEvalBadgeProps(summary.latestRun, {
+ trueIsFailure: detectorEvaluationIds.includes(summary.latestRun.evaluation_id),
+ })
return (
<Tooltip key={summary.latestRun.evaluation_id} title={<EvalTooltipContent {...summary} />}>
<span>
diff --git a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
index 95ca348ece03..d073e0043e00 100644
--- a/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
+++ b/products/ai_observability/frontend/clusters/clusterDetailLogic.ts
@@ -16,6 +16,7 @@ import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } f
import type { ProductIntentProperties } from '../../../../frontend/src/lib/utils/product-intents'
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
+import { llmEvaluationsLogic, waitForEvaluationsSettled } from '../evaluations/llmEvaluationsLogic'
import { loadClusterMetrics } from './clusterMetricsLoader'
import type { ClusterScatterSeries } from './clusterScatter'
import {
@@ -61,6 +62,7 @@ export interface ClusterData {
export interface clusterDetailLogicValues {
propertyFilters: AnyPropertyFilter[] // aiObservabilitySharedLogic
shouldFilterTestAccounts: boolean // aiObservabilitySharedLogic
+ detectorEvaluationIds: string[] // llmEvaluationsLogic
breadcrumbs: Breadcrumb[]
cluster: Cluster | null
clusterData: ClusterData | null
@@ -206,7 +208,12 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
props({} as ClusterDetailLogicProps),
key((props) => `${props.runId}:${props.clusterId}`),
connect(() => ({
- values: [aiObservabilitySharedLogic, ['propertyFilters', 'shouldFilterTestAccounts']],
+ values: [
+ aiObservabilitySharedLogic,
+ ['propertyFilters', 'shouldFilterTestAccounts'],
+ llmEvaluationsLogic,
+ ['detectorEvaluationIds'],
+ ],
actions: [
teamLogic,
['addProductIntent'],
@@ -663,12 +670,21 @@ export const clusterDetailLogic = kea<clusterDetailLogicType>([
actions.setTraceSummariesLoading(true)
try {
+ // Only evaluation-level clustering derives a verdict, so only that level
+ // needs to wait for llmEvaluationsLogic's evaluations to settle first —
+ // otherwise a clustering response that resolves first would read
+ // detectorEvaluationIds as [] and bake a wrong verdict into a cached summary
+ // that never gets refetched (loadTraceSummaries only fetches missing ids).
+ if (clusteringLevel === 'evaluation') {
+ await waitForEvaluationsSettled()
+ }
const summaries = await loadTraceSummaries(
traceIds,
values.traceSummaries,
windowStart,
windowEnd,
- clusteringLevel
+ clusteringLevel,
+ values.detectorEvaluationIds
)
actions.setTraceSummaries(summaries)
} catch (error) {
diff --git a/products/ai_observability/frontend/clusters/clustersLogic.evaluationsRace.test.ts b/products/ai_observability/frontend/clusters/clustersLogic.evaluationsRace.test.ts
new file mode 100644
index 000000000000..df98bb497d6e
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/clustersLogic.evaluationsRace.test.ts
@@ -0,0 +1,193 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
+import { EvaluationConfig, EvaluationOutputConfig } from '../evaluations/types'
+import { clustersLogic } from './clustersLogic'
+import { ClusteringRun } from './types'
+
+jest.mock('lib/api', () => {
+ const actual = jest.requireActual('lib/api')
+
+ return {
+ __esModule: true,
+ ...actual,
+ default: {
+ ...actual.default,
+ queryHogQL: jest.fn(),
+ },
+ }
+})
+
+const evaluationWithOutputConfig = (id: string, outputConfig: EvaluationOutputConfig): EvaluationConfig =>
+ ({
+ id,
+ name: `Evaluation ${id}`,
+ description: '',
+ directory_id: null,
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: 'Prompt' },
+ output_type: 'boolean',
+ output_config: outputConfig,
+ conditions: [],
+ target: 'generation',
+ target_config: {},
+ model_configuration: null,
+ total_runs: 0,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ }) as EvaluationConfig
+
+describe('clustersLogic / llmEvaluationsLogic load-order race', () => {
+ let resolveEvaluationsFetch: (() => void) | undefined
+
+ beforeEach(() => {
+ const evaluationsFetchGate = new Promise<void>((resolve) => {
+ resolveEvaluationsFetch = resolve
+ })
+
+ // Deliberately gated: this only resolves once the test calls resolveEvaluationsFetch(),
+ // simulating llmEvaluationsLogic's own fetch losing the race against the clustering data.
+ useMocks({
+ get: {
+ '/api/projects/:teamId/evaluations/': async () => {
+ await evaluationsFetchGate
+ return { results: [evaluationWithOutputConfig('det-1', { true_is_failure: true })] }
+ },
+ },
+ })
+
+ initKeaTests()
+ })
+
+ it('waits for evaluations to settle before deriving a detector verdict, instead of reading detectorEvaluationIds as []', async () => {
+ const queryHogQLMock = api.queryHogQL as jest.Mock
+ queryHogQLMock.mockResolvedValue({
+ // eval_id, name, result, applicable, evaluation_id — matches loadEvaluationItemAttributes's SELECT
+ results: [['eval-uuid-1', 'Struggle detector', 'true', null, 'det-1']],
+ })
+
+ const logic = clustersLogic()
+ logic.mount()
+ // afterMount fires its own unrelated loadClusteringRuns() HogQL call — clear it so the
+ // assertion below only reflects the eval-attributes read this test cares about.
+ queryHogQLMock.mockClear()
+
+ const mockRun = {
+ runId: 'race-run',
+ windowStart: '2026-04-13T00:00:00Z',
+ windowEnd: '2026-04-20T00:00:00Z',
+ totalItemsAnalyzed: 1,
+ clusters: [
+ {
+ cluster_id: 0,
+ size: 1,
+ title: 'Detector cluster',
+ description: '',
+ traces: {
+ 'eval-uuid-1': {
+ distance_to_centroid: 0,
+ rank: 0,
+ x: 0,
+ y: 0,
+ timestamp: '2026-04-20T00:00:00Z',
+ trace_id: 'eval-uuid-1',
+ },
+ },
+ centroid: [],
+ centroid_x: 0,
+ centroid_y: 0,
+ },
+ ],
+ timestamp: '2026-04-20T00:00:00Z',
+ level: 'evaluation',
+ } as ClusteringRun
+
+ // Fire the eval-level attributes loader directly — mirrors what
+ // loadClusteringRunSuccess dispatches for an evaluation-level run — while
+ // llmEvaluationsLogic's own evaluations fetch is still gated (evaluationsLoading is
+ // true, detectorEvaluationIds is still []).
+ logic.actions.loadEvaluationAttributesForRun(mockRun)
+
+ // The gate must actually hold: the HogQL read must not fire before evaluations settle,
+ // otherwise it would run with a stale, empty detectorEvaluationIds.
+ expect(queryHogQLMock).not.toHaveBeenCalled()
+
+ await expectLogic(llmEvaluationsLogic(), () => {
+ resolveEvaluationsFetch?.()
+ }).toDispatchActions(['loadEvaluationsSuccess'])
+
+ await expectLogic(logic).toDispatchActions(['setEvaluationItemAttributes'])
+
+ expect(llmEvaluationsLogic().values.detectorEvaluationIds).toEqual(['det-1'])
+ expect(logic.values.evaluationItemAttributes['eval-uuid-1'].verdict).toBe('fail')
+
+ logic.unmount()
+ })
+
+ it('does not block forever when the evaluations fetch fails — falls back to non-detector verdicts', async () => {
+ const queryHogQLMock = api.queryHogQL as jest.Mock
+ queryHogQLMock.mockResolvedValue({
+ results: [['eval-uuid-1', 'Struggle detector', 'true', null, 'det-1']],
+ })
+
+ // Override the gated success handler from beforeEach with one that fails instead.
+ useMocks({
+ get: {
+ '/api/projects/:teamId/evaluations/': () => [500, { detail: 'boom' }],
+ },
+ })
+
+ const logic = clustersLogic()
+ logic.mount()
+
+ const mockRun = {
+ runId: 'race-run-failure',
+ windowStart: '2026-04-13T00:00:00Z',
+ windowEnd: '2026-04-20T00:00:00Z',
+ totalItemsAnalyzed: 1,
+ clusters: [
+ {
+ cluster_id: 0,
+ size: 1,
+ title: 'Detector cluster',
+ description: '',
+ traces: {
+ 'eval-uuid-1': {
+ distance_to_centroid: 0,
+ rank: 0,
+ x: 0,
+ y: 0,
+ timestamp: '2026-04-20T00:00:00Z',
+ trace_id: 'eval-uuid-1',
+ },
+ },
+ centroid: [],
+ centroid_x: 0,
+ centroid_y: 0,
+ },
+ ],
+ timestamp: '2026-04-20T00:00:00Z',
+ level: 'evaluation',
+ } as ClusteringRun
+
+ logic.actions.loadEvaluationAttributesForRun(mockRun)
+
+ await expectLogic(logic).toDispatchActions(['setEvaluationItemAttributes'])
+
+ // A failed evaluations fetch must not hang the scene: detectorEvaluationIds stays [],
+ // so the verdict falls back to today's non-detector reading rather than never resolving.
+ expect(llmEvaluationsLogic().values.detectorEvaluationIds).toEqual([])
+ expect(logic.values.evaluationItemAttributes['eval-uuid-1'].verdict).toBe('pass')
+
+ logic.unmount()
+ })
+})
diff --git a/products/ai_observability/frontend/clusters/clustersLogic.ts b/products/ai_observability/frontend/clusters/clustersLogic.ts
index 33f4733d734f..c97fb61a1cde 100644
--- a/products/ai_observability/frontend/clusters/clustersLogic.ts
+++ b/products/ai_observability/frontend/clusters/clustersLogic.ts
@@ -16,6 +16,7 @@ import { AnyPropertyFilter, Breadcrumb, PropertyFilterType, PropertyOperator } f
import { aiObservabilitySharedLogic } from '../aiObservabilitySharedLogic'
import type { ApplyUrlStatePayload } from '../aiObservabilitySharedLogic'
+import { llmEvaluationsLogic, waitForEvaluationsSettled } from '../evaluations/llmEvaluationsLogic'
import { loadClusterMetrics } from './clusterMetricsLoader'
import type { ClusterScatterSeries } from './clusterScatter'
import {
@@ -65,6 +66,7 @@ export type ClustersLogicProps = Record<string, never>
export interface clustersLogicValues {
propertyFilters: AnyPropertyFilter[] // aiObservabilitySharedLogic
shouldFilterTestAccounts: boolean // aiObservabilitySharedLogic
+ detectorEvaluationIds: string[] // llmEvaluationsLogic
anyFiltersActive: boolean
availableEvaluatorNames: {
count: number
@@ -275,7 +277,12 @@ export const clustersLogic = kea<clustersLogicType>([
props({} as ClustersLogicProps),
connect(() => ({
- values: [aiObservabilitySharedLogic, ['propertyFilters', 'shouldFilterTestAccounts']],
+ values: [
+ aiObservabilitySharedLogic,
+ ['propertyFilters', 'shouldFilterTestAccounts'],
+ llmEvaluationsLogic,
+ ['detectorEvaluationIds'],
+ ],
actions: [aiObservabilitySharedLogic, ['setPropertyFilters', 'setShouldFilterTestAccounts', 'applyUrlState']],
})),
@@ -913,7 +920,19 @@ export const clustersLogic = kea<clustersLogicType>([
return
}
try {
- const attrs = await loadEvaluationItemAttributes(allItemIds, run.windowStart, run.windowEnd)
+ // detectorEvaluationIds reads as [] until llmEvaluationsLogic's own fetch
+ // settles. Wait for it here so a clustering response that resolves first
+ // can't bake a wrong (non-detector) verdict into a cached summary that never
+ // gets refetched — loadTraceSummaries only fetches ids missing from the cache.
+ // No separate level check needed here, unlike the other call sites below: the
+ // early return above already confines this listener to evaluation-level runs.
+ await waitForEvaluationsSettled()
+ const attrs = await loadEvaluationItemAttributes(
+ allItemIds,
+ run.windowStart,
+ run.windowEnd,
+ values.detectorEvaluationIds
+ )
// Guard against a slow response for a prior run overwriting attributes
// after the user has switched to a different run. If currentRun has
// advanced past the one we were loading for, drop the response on the
@@ -937,12 +956,18 @@ export const clustersLogic = kea<clustersLogicType>([
actions.setTraceSummariesLoading(true)
try {
+ // Same rationale as loadEvaluationAttributesForRun: only evaluation-level
+ // clustering derives a verdict, so only that level needs to wait.
+ if (values.clusteringLevel === 'evaluation') {
+ await waitForEvaluationsSettled()
+ }
const summaries = await loadTraceSummaries(
allItemIds,
values.traceSummaries,
run.windowStart,
run.windowEnd,
- values.clusteringLevel
+ values.clusteringLevel,
+ values.detectorEvaluationIds
)
actions.setTraceSummaries(summaries)
} catch (error) {
@@ -967,12 +992,17 @@ export const clustersLogic = kea<clustersLogicType>([
actions.setTraceSummariesLoading(true)
try {
+ // Same rationale as loadEvaluationAttributesForRun.
+ if (values.clusteringLevel === 'evaluation') {
+ await waitForEvaluationsSettled()
+ }
const summaries = await loadTraceSummaries(
itemIds,
values.traceSummaries,
run.windowStart,
run.windowEnd,
- values.clusteringLevel
+ values.clusteringLevel,
+ values.detectorEvaluationIds
)
actions.setTraceSummaries(summaries)
} catch (error) {
diff --git a/products/ai_observability/frontend/clusters/traceSummaryLoader.test.ts b/products/ai_observability/frontend/clusters/traceSummaryLoader.test.ts
new file mode 100644
index 000000000000..054197585f53
--- /dev/null
+++ b/products/ai_observability/frontend/clusters/traceSummaryLoader.test.ts
@@ -0,0 +1,22 @@
+import { deriveVerdict } from './traceSummaryLoader'
+
+describe('deriveVerdict', () => {
+ it('reads a true result as a pass for a normal evaluation', () => {
+ expect(deriveVerdict('true', null, false)).toBe('pass')
+ expect(deriveVerdict('false', null, false)).toBe('fail')
+ })
+
+ it('reads a true result as a fail for a detector', () => {
+ expect(deriveVerdict('true', null, true)).toBe('fail')
+ expect(deriveVerdict('false', null, true)).toBe('pass')
+ })
+
+ it.each([false, true])('reports a non-applicable result as n/a (detector: %s)', (trueIsFailure) => {
+ expect(deriveVerdict('true', 'false', trueIsFailure)).toBe('n/a')
+ })
+
+ it.each([false, true])('reports an unreadable result as unknown (detector: %s)', (trueIsFailure) => {
+ expect(deriveVerdict(null, null, trueIsFailure)).toBe('unknown')
+ expect(deriveVerdict('nonsense', null, trueIsFailure)).toBe('unknown')
+ })
+})
diff --git a/products/ai_observability/frontend/clusters/traceSummaryLoader.ts b/products/ai_observability/frontend/clusters/traceSummaryLoader.ts
index 59302e740f9b..3e09db9d2909 100644
--- a/products/ai_observability/frontend/clusters/traceSummaryLoader.ts
+++ b/products/ai_observability/frontend/clusters/traceSummaryLoader.ts
@@ -16,7 +16,8 @@ export async function loadTraceSummaries(
existingSummaries: Record<string, TraceSummary>,
windowStart: string,
windowEnd: string,
- level: ClusteringLevel = 'trace'
+ level: ClusteringLevel,
+ detectorEvaluationIds: string[]
): Promise<Record<string, TraceSummary>> {
const missingItemIds = itemIds.filter((id) => !existingSummaries[id])
@@ -25,7 +26,7 @@ export async function loadTraceSummaries(
}
if (level === 'evaluation') {
- return loadEvaluationSummaries(missingItemIds, windowStart, windowEnd)
+ return loadEvaluationSummaries(missingItemIds, windowStart, windowEnd, detectorEvaluationIds)
}
const eventName = level === 'generation' ? '$ai_generation_summary' : '$ai_trace_summary'
@@ -85,7 +86,8 @@ export async function loadTraceSummaries(
async function loadEvaluationSummaries(
evalIds: string[],
windowStart: string,
- windowEnd: string
+ windowEnd: string,
+ detectorEvaluationIds: string[]
): Promise<Record<string, TraceSummary>> {
// Cluster members can include eval events from Stage B's embedding lookback,
// which extends a few days past the UI's run-day window. Widen by 7 days on
@@ -101,7 +103,8 @@ async function loadEvaluationSummaries(
properties.$ai_evaluation_runtime as runtime,
properties.$ai_target_event_id as target_generation_id,
properties.$ai_trace_id as trace_id,
- timestamp
+ timestamp,
+ properties.$ai_evaluation_id as evaluation_id
FROM events
WHERE event = '$ai_evaluation'
AND timestamp >= parseDateTimeBestEffort(${windowStart}) - INTERVAL 7 DAY
@@ -120,7 +123,7 @@ async function loadEvaluationSummaries(
if (!evalId) {
continue
}
- const verdict = deriveVerdict(r[2], r[3])
+ const verdict = deriveVerdict(r[2], r[3], detectorEvaluationIds.includes(r[9] || ''))
const name = r[1] || 'Evaluation'
summaries[evalId] = {
traceId: r[7] || '',
@@ -158,7 +161,8 @@ export interface EvaluationItemAttributes {
export async function loadEvaluationItemAttributes(
evalIds: string[],
windowStart: string,
- windowEnd: string
+ windowEnd: string,
+ detectorEvaluationIds: string[]
): Promise<Record<string, EvaluationItemAttributes>> {
if (evalIds.length === 0) {
return {}
@@ -172,7 +176,8 @@ export async function loadEvaluationItemAttributes(
toString(uuid) as eval_id,
properties.$ai_evaluation_name as name,
properties.$ai_evaluation_result as result,
- properties.$ai_evaluation_applicable as applicable
+ properties.$ai_evaluation_applicable as applicable,
+ properties.$ai_evaluation_id as evaluation_id
FROM events
WHERE event = '$ai_evaluation'
AND timestamp >= parseDateTimeBestEffort(${windowStart}) - INTERVAL 7 DAY
@@ -191,7 +196,7 @@ export async function loadEvaluationItemAttributes(
}
out[evalId] = {
evaluatorName: r[1] || 'Unknown',
- verdict: deriveVerdict(r[2], r[3]),
+ verdict: deriveVerdict(r[2], r[3], detectorEvaluationIds.includes(r[4] || '')),
}
}
return out
@@ -223,17 +228,18 @@ export function formatEvalTitle(summary: TraceSummary | undefined, maxReasoningC
return `${name} — ${preview}`
}
-function deriveVerdict(result: string | null, applicable: string | null): 'pass' | 'fail' | 'n/a' | 'unknown' {
+export function deriveVerdict(
+ result: string | null,
+ applicable: string | null,
+ trueIsFailure: boolean
+): 'pass' | 'fail' | 'n/a' | 'unknown' {
const a = (applicable || '').toLowerCase()
if (a === 'false') {
return 'n/a'
}
const v = (result || '').toLowerCase()
- if (v === 'true') {
- return 'pass'
- }
- if (v === 'false') {
- return 'fail'
+ if (v !== 'true' && v !== 'false') {
+ return 'unknown'
}
- return 'unknown'
+ return (v === 'true') === trueIsFailure ? 'fail' : 'pass'
}
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
index a7fb02914410..c1e2ff921c0f 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.test.tsx
@@ -1,6 +1,15 @@
-import { EvaluationRun } from '../evaluations/types'
-import { getEvalBadgeProps, getEvalSummaries, scopeRunsToTarget } from './EvalResultBadges'
-import { isSentimentRun } from './EvaluationResultTag'
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
+import { EvaluationConfig, EvaluationRun } from '../evaluations/types'
+import { generationEvaluationRunsLogic } from '../generationEvaluationRunsLogic'
+import { EvalResultBadges, getEvalBadgeProps, getEvalSummaries, scopeRunsToTarget } from './EvalResultBadges'
+import { getEvaluationResultDisplay, getEvaluationResultSortValue, isSentimentRun } from './EvaluationResultTag'
function makeRun(overrides: Partial<EvaluationRun> = {}): EvaluationRun {
return {
@@ -135,6 +144,25 @@ describe('EvalResultBadges', () => {
})
})
+ describe('getEvaluationResultDisplay polarity', () => {
+ it('keeps the True label but marks a detector true result as danger', () => {
+ const run = { status: 'completed', result: true, skipped: false } as any
+ expect(getEvaluationResultDisplay(run, { trueIsFailure: true })).toMatchObject({
+ type: 'danger',
+ label: 'True',
+ })
+ expect(getEvaluationResultDisplay(run)).toMatchObject({ type: 'success', label: 'True' })
+ })
+
+ it('sorts a detector false result above its true result', () => {
+ const trueRun = { status: 'completed', result: true, skipped: false } as any
+ const falseRun = { status: 'completed', result: false, skipped: false } as any
+ expect(getEvaluationResultSortValue(falseRun, { trueIsFailure: true })).toBeGreaterThan(
+ getEvaluationResultSortValue(trueRun, { trueIsFailure: true })
+ )
+ })
+ })
+
describe('isSentimentRun', () => {
it.each([
['evaluation type', makeRun({ evaluation_type: 'sentiment' })],
@@ -148,4 +176,58 @@ describe('EvalResultBadges', () => {
expect(isSentimentRun(makeRun())).toBe(false)
})
})
+
+ describe('rendered with the trace scene evaluations logic', () => {
+ const detectorEvaluation: EvaluationConfig = {
+ id: 'eval-detector',
+ name: 'Detects struggle',
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'hog',
+ evaluation_config: { source: 'return true' },
+ output_type: 'boolean',
+ output_config: { true_is_failure: true },
+ conditions: [{ id: 'cond-1', rollout_percentage: 100, properties: [] }],
+ target: 'trace',
+ target_config: {},
+ model_configuration: null,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('colors a detector true result as danger, matching the config switch', () => {
+ const evaluationsLogic = llmEvaluationsLogic()
+ evaluationsLogic.mount()
+ evaluationsLogic.actions.loadEvaluationsSuccess([detectorEvaluation])
+
+ const runsLogic = generationEvaluationRunsLogic({ traceId: 'trace-1' })
+ runsLogic.mount()
+ runsLogic.actions.loadGenerationEvaluationRunsSuccess([
+ makeRun({ evaluation_id: 'eval-detector', evaluation_name: 'Detects struggle', generation_id: '' }),
+ ])
+
+ render(
+ <Provider>
+ <EvalResultBadges traceId="trace-1" />
+ </Provider>
+ )
+
+ expect(screen.getByText('Detects struggle: True')).toBeInTheDocument()
+ expect(document.querySelector('.LemonTag--danger')).toBeInTheDocument()
+ expect(document.querySelector('.LemonTag--success')).not.toBeInTheDocument()
+
+ evaluationsLogic.unmount()
+ runsLogic.unmount()
+ })
+ })
})
diff --git a/products/ai_observability/frontend/components/EvalResultBadges.tsx b/products/ai_observability/frontend/components/EvalResultBadges.tsx
index edf0e5efc41b..c8eacd3970af 100644
--- a/products/ai_observability/frontend/components/EvalResultBadges.tsx
+++ b/products/ai_observability/frontend/components/EvalResultBadges.tsx
@@ -6,9 +6,10 @@ import { dayjs } from 'lib/dayjs'
import { pluralize } from 'lib/utils/strings'
import { TraceViewMode, aiObservabilityTraceLogic } from '../aiObservabilityTraceLogic'
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
import { EvaluationRun } from '../evaluations/types'
import { generationEvaluationRunsLogic } from '../generationEvaluationRunsLogic'
-import { getEvaluationResultDisplay } from './EvaluationResultTag'
+import { EvaluationResultDisplayOptions, getEvaluationResultDisplay } from './EvaluationResultTag'
export interface EvalSummary {
latestRun: EvaluationRun
@@ -29,12 +30,15 @@ export function getEvalSummaries(runs: EvaluationRun[]): EvalSummary[] {
return Array.from(byEvalId.values())
}
-export function getEvalBadgeProps(run: EvaluationRun): {
+export function getEvalBadgeProps(
+ run: EvaluationRun,
+ options: EvaluationResultDisplayOptions = {}
+): {
type: LemonTagProps['type']
icon: JSX.Element
label: string
} {
- const { type, icon, label } = getEvaluationResultDisplay(run)
+ const { type, icon, label } = getEvaluationResultDisplay(run, options)
return { type, icon, label }
}
@@ -70,6 +74,7 @@ export function EvalResultBadges({
const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(
generationEvaluationRunsLogic({ traceId })
)
+ const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
const traceLogic = useMountedLogic(aiObservabilityTraceLogic)
const { setViewMode } = useActions(traceLogic)
@@ -93,7 +98,9 @@ export function EvalResultBadges({
return (
<div className="flex flex-row flex-wrap items-center gap-1.5">
{summaries.map((summary) => {
- const { type, icon, label } = getEvalBadgeProps(summary.latestRun)
+ const { type, icon, label } = getEvalBadgeProps(summary.latestRun, {
+ trueIsFailure: detectorEvaluationIds.includes(summary.latestRun.evaluation_id),
+ })
return (
<Tooltip key={summary.latestRun.evaluation_id} title={<EvalTooltipContent {...summary} />}>
<LemonTag
diff --git a/products/ai_observability/frontend/components/EvaluationResultTag.tsx b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
index 14499caee870..ef1d6142b404 100644
--- a/products/ai_observability/frontend/components/EvaluationResultTag.tsx
+++ b/products/ai_observability/frontend/components/EvaluationResultTag.tsx
@@ -17,6 +17,11 @@ interface EvaluationResultDisplay {
sortValue: number
}
+export interface EvaluationResultDisplayOptions {
+ /** When true, the evaluation looks for a problem, so a true result is the undesirable one. */
+ trueIsFailure?: boolean
+}
+
const SENTIMENT_DISPLAY: Record<string, Pick<EvaluationResultDisplay, 'type' | 'icon' | 'sortValue'>> = {
positive: { type: 'success', icon: <IconCheck />, sortValue: 3 },
neutral: { type: 'none', icon: <IconMinus />, sortValue: 2 },
@@ -27,7 +32,10 @@ export function isSentimentRun(run: EvaluationResultLike): boolean {
return run.result_type === 'sentiment' || run.evaluation_type === 'sentiment' || !!run.sentiment_label
}
-export function getEvaluationResultDisplay(run: EvaluationResultLike): EvaluationResultDisplay {
+export function getEvaluationResultDisplay(
+ run: EvaluationResultLike,
+ options: EvaluationResultDisplayOptions = {}
+): EvaluationResultDisplay {
if (run.status === 'failed') {
return { type: 'danger', icon: <IconWarning />, label: 'Error', sortValue: -2 }
}
@@ -54,24 +62,31 @@ export function getEvaluationResultDisplay(run: EvaluationResultLike): Evaluatio
if (run.result === null) {
return { type: 'muted', icon: <IconMinus />, label: 'N/A', sortValue: 0.5 }
}
- if (run.result) {
- return { type: 'success', icon: <IconCheck />, label: 'True', sortValue: 1 }
- }
- return { type: 'danger', icon: <IconX />, label: 'False', sortValue: 0 }
+ // The label states the raw result either way; only the verdict it carries depends on polarity.
+ const isDesirable = run.result !== Boolean(options.trueIsFailure)
+ const label = run.result ? 'True' : 'False'
+ return isDesirable
+ ? { type: 'success', icon: <IconCheck />, label, sortValue: 1 }
+ : { type: 'danger', icon: <IconX />, label, sortValue: 0 }
}
-export function getEvaluationResultSortValue(run: EvaluationResultLike): number {
- return getEvaluationResultDisplay(run).sortValue
+export function getEvaluationResultSortValue(
+ run: EvaluationResultLike,
+ options: EvaluationResultDisplayOptions = {}
+): number {
+ return getEvaluationResultDisplay(run, options).sortValue
}
export function EvaluationResultTag({
run,
+ trueIsFailure,
size,
}: {
run: EvaluationResultLike
+ trueIsFailure?: boolean
size?: LemonTagProps['size']
}): JSX.Element {
- const { type, icon, label } = getEvaluationResultDisplay(run)
+ const { type, icon, label } = getEvaluationResultDisplay(run, { trueIsFailure })
return (
<LemonTag type={type} icon={icon} size={size}>
{label}
diff --git a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
index 904e1d7c4481..2c97a54e5291 100644
--- a/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
+++ b/products/ai_observability/frontend/components/GenerationEvalRunsTable.tsx
@@ -6,6 +6,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { urls } from 'scenes/urls'
+import { llmEvaluationsLogic } from '../evaluations/llmEvaluationsLogic'
import { EvaluationRun } from '../evaluations/types'
import type { generationEvaluationRunsLogicType } from '../generationEvaluationRunsLogic'
import { EvaluationResultTag, getEvaluationResultSortValue } from './EvaluationResultTag'
@@ -17,6 +18,7 @@ export function GenerationEvalRunsTable({
generationRunsLogic: BuiltLogic<generationEvaluationRunsLogicType>
}): JSX.Element {
const { generationEvaluationRuns, generationEvaluationRunsLoading } = useValues(generationRunsLogic)
+ const { detectorEvaluationIds } = useValues(llmEvaluationsLogic)
const columns: LemonTableColumns<EvaluationRun> = [
{
@@ -42,9 +44,18 @@ export function GenerationEvalRunsTable({
{
title: 'Result',
key: 'result',
- render: (_, run) => <EvaluationResultTag run={run} />,
+ render: (_, run) => (
+ <EvaluationResultTag run={run} trueIsFailure={detectorEvaluationIds.includes(run.evaluation_id)} />
+ ),
sorter: (a, b) => {
- return getEvaluationResultSortValue(b) - getEvaluationResultSortValue(a)
+ return (
+ getEvaluationResultSortValue(b, {
+ trueIsFailure: detectorEvaluationIds.includes(b.evaluation_id),
+ }) -
+ getEvaluationResultSortValue(a, {
+ trueIsFailure: detectorEvaluationIds.includes(a.evaluation_id),
+ })
+ )
},
},
{
diff --git a/products/ai_observability/frontend/e2e/evaluation-polarity.spec.ts b/products/ai_observability/frontend/e2e/evaluation-polarity.spec.ts
new file mode 100644
index 000000000000..b8530b3629b3
--- /dev/null
+++ b/products/ai_observability/frontend/e2e/evaluation-polarity.spec.ts
@@ -0,0 +1,441 @@
+import type { PlaywrightSetupEvent } from '@playwright-utils/playwright-setup'
+import { expect, test } from '@playwright-utils/workspace-test-base'
+import fs from 'fs'
+import path from 'path'
+
+// Reused verbatim from llmEvaluationLogic.ts's LEGACY_HOG_DEFAULT_SOURCES — a known-good Hog
+// snippet, so seeding an evaluation directly still stores compilable bytecode.
+const HOG_SOURCE = `// Check that the output is not empty
+let result := length(output) > 0
+if (not result) {
+ print('Output is empty')
+}
+return result`
+
+const SCREENSHOT_DIR = path.join(__dirname, '../../../../.playwright-screenshots')
+
+interface BooleanRunSpec {
+ result: boolean | null
+ skipped?: boolean
+}
+
+function buildBooleanRunEvents(
+ evaluationId: string,
+ evaluationName: string,
+ specs: BooleanRunSpec[],
+ baseTimestampMs: number
+): PlaywrightSetupEvent[] {
+ return specs.map((spec, index) => {
+ const suffix = `${evaluationId.slice(0, 8)}-${index}`
+ const properties: Record<string, unknown> = {
+ $ai_evaluation_id: evaluationId,
+ $ai_evaluation_name: evaluationName,
+ $ai_trace_id: `e2e-trace-${suffix}`,
+ $ai_target_event_id: `e2e-gen-${suffix}`,
+ $ai_evaluation_reasoning: 'Synthetic e2e reasoning.',
+ }
+ if (spec.result !== null) {
+ properties.$ai_evaluation_result = spec.result
+ }
+ if (spec.skipped) {
+ properties.$ai_evaluation_skipped = true
+ }
+ return {
+ event: '$ai_evaluation',
+ distinct_id: `e2e-eval-user-${suffix}`,
+ timestamp: new Date(baseTimestampMs + index * 1000).toISOString(),
+ properties,
+ }
+ })
+}
+
+function buildSentimentRunEvents(
+ evaluationId: string,
+ evaluationName: string,
+ labels: string[],
+ baseTimestampMs: number
+): PlaywrightSetupEvent[] {
+ return labels.map((label, index) => {
+ const suffix = `${evaluationId.slice(0, 8)}-${index}`
+ return {
+ event: '$ai_evaluation',
+ distinct_id: `e2e-eval-user-${suffix}`,
+ timestamp: new Date(baseTimestampMs + index * 1000).toISOString(),
+ properties: {
+ $ai_evaluation_id: evaluationId,
+ $ai_evaluation_name: evaluationName,
+ $ai_sentiment_label: label,
+ $ai_trace_id: `e2e-trace-${suffix}`,
+ $ai_target_event_id: `e2e-gen-${suffix}`,
+ },
+ }
+ })
+}
+
+test.describe('AI observability boolean evaluation polarity', () => {
+ test.beforeAll(() => {
+ fs.mkdirSync(SCREENSHOT_DIR, { recursive: true })
+ })
+
+ test.use({ viewport: { width: 1440, height: 900 }, colorScheme: 'light' })
+
+ test('the polarity switch round-trips, and a legacy config behaves as pass-on-true', async ({
+ page,
+ playwrightSetup,
+ }) => {
+ test.setTimeout(120_000)
+
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ await playwrightSetup.login(page, workspace)
+
+ await test.step('the switch renders under Allow N/A responses and round-trips through save + reload', async () => {
+ await page.goto('/ai-evals/evaluations/new')
+ await expect(page.getByRole('heading', { name: 'New evaluation' })).toBeVisible()
+
+ await page.getByPlaceholder('e.g., Helpfulness Check').fill('User struggled')
+ await page.getByRole('button', { name: 'LLM as a judge' }).click()
+ await page.getByRole('menuitem', { name: 'Hog code' }).click()
+
+ const trueIsFailureSwitch = page.getByTestId('llma-evaluation-true-is-failure-switch')
+ const allowsNaLabel = page.getByText('Allow N/A responses', { exact: true })
+ const trueIsFailureLabel = page.getByText('A true result flags a problem', { exact: true })
+
+ // Settle scrolling before taking any measurement — every bounding box read below has
+ // to share one coordinate space with the eventual screenshot clip, and a later click
+ // auto-scrolling the page would otherwise invalidate boxes read before it.
+ await trueIsFailureSwitch.scrollIntoViewIfNeeded()
+
+ await expect(allowsNaLabel).toBeVisible()
+ await expect(trueIsFailureLabel).toBeVisible()
+ const naBox = await allowsNaLabel.boundingBox()
+ const flagBox = await trueIsFailureLabel.boundingBox()
+ if (!naBox || !flagBox) {
+ throw new Error('Expected both switch labels to have a bounding box')
+ }
+ expect(flagBox.y).toBeGreaterThan(naBox.y)
+
+ await expect(trueIsFailureSwitch).toHaveAttribute('aria-checked', 'false')
+ await expect(page.getByText('A true result counts as a pass', { exact: true })).toBeVisible()
+
+ await trueIsFailureSwitch.click()
+ await expect(trueIsFailureSwitch).toHaveAttribute('aria-checked', 'true')
+ const failDescription = page.getByText('A true result counts as a fail', { exact: true })
+ await expect(failDescription).toBeVisible()
+
+ const naDescription = page.getByText('Evaluation must return true or false', { exact: true })
+ const failBox = await failDescription.boundingBox()
+ const switchBox = await trueIsFailureSwitch.boundingBox()
+ const naDescriptionBox = await naDescription.boundingBox()
+ if (failBox && switchBox && naDescriptionBox) {
+ const pad = 24
+ const left = Math.min(naBox.x, switchBox.x) - pad
+ const top = naBox.y - 10
+ const right =
+ Math.max(
+ naBox.x + naBox.width,
+ naDescriptionBox.x + naDescriptionBox.width,
+ failBox.x + failBox.width
+ ) + pad
+ const bottom = failBox.y + failBox.height + pad
+ await page.screenshot({
+ path: path.join(SCREENSHOT_DIR, '01-switch.png'),
+ clip: { x: left, y: top, width: right - left, height: bottom - top },
+ animations: 'disabled',
+ })
+ }
+
+ const [createResponse] = await Promise.all([
+ page.waitForResponse(
+ (resp) => resp.url().includes('/evaluations/') && resp.request().method() === 'POST'
+ ),
+ page.getByRole('button', { name: 'Create evaluation' }).click(),
+ ])
+ await expect(page).toHaveURL(/\/ai-evals\/evaluations$/, { timeout: 30_000 })
+ const created = await createResponse.json()
+ const evalAId = created.id as string
+
+ const gotoEvalA = async (): Promise<void> => {
+ await page.goto(`/ai-evals/evaluations/${evalAId}`)
+ await page.getByTestId('llma-evaluation-configuration-tab').click()
+ }
+
+ await gotoEvalA()
+ await expect(page.getByTestId('llma-evaluation-true-is-failure-switch')).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+ await page.reload()
+ await page.getByTestId('llma-evaluation-configuration-tab').click()
+ await expect(page.getByTestId('llma-evaluation-true-is-failure-switch')).toHaveAttribute(
+ 'aria-checked',
+ 'true'
+ )
+
+ await page.getByTestId('llma-evaluation-true-is-failure-switch').click()
+ await expect(page.getByTestId('llma-evaluation-true-is-failure-switch')).toHaveAttribute(
+ 'aria-checked',
+ 'false'
+ )
+ await page.getByRole('button', { name: 'Save changes' }).click()
+ await expect(page).toHaveURL(/\/ai-evals\/evaluations$/, { timeout: 30_000 })
+
+ await gotoEvalA()
+ await expect(page.getByTestId('llma-evaluation-true-is-failure-switch')).toHaveAttribute(
+ 'aria-checked',
+ 'false'
+ )
+ await page.reload()
+ await page.getByTestId('llma-evaluation-configuration-tab').click()
+ await expect(page.getByTestId('llma-evaluation-true-is-failure-switch')).toHaveAttribute(
+ 'aria-checked',
+ 'false'
+ )
+ })
+
+ await test.step('a legacy evaluation whose config never had the key behaves as pass-on-true', async () => {
+ const legacy = await playwrightSetup.seedEvaluation({
+ team_id: workspace.team_id,
+ name: 'Response is accurate',
+ evaluation_type: 'hog',
+ evaluation_config: { source: HOG_SOURCE },
+ output_type: 'boolean',
+ output_config: {},
+ })
+
+ await page.goto(`/ai-evals/evaluations/${legacy.evaluation_id}`)
+ await page.getByTestId('llma-evaluation-configuration-tab').click()
+ await expect(page.getByTestId('llma-evaluation-true-is-failure-switch')).toHaveAttribute(
+ 'aria-checked',
+ 'false'
+ )
+ await expect(page.getByText('A true result counts as a pass', { exact: true })).toBeVisible()
+ })
+ })
+
+ test('seeded results propagate correctly across the list, the runs table, and edge cases', async ({
+ page,
+ playwrightSetup,
+ }) => {
+ test.setTimeout(180_000)
+
+ const workspace = await playwrightSetup.createWorkspace({ skip_onboarding: true, no_demo_data: true })
+ await playwrightSetup.login(page, workspace)
+
+ // Enabled so a reviewer glancing at the list screenshot doesn't have to wonder
+ // whether the rates are stale because the evaluations are off.
+ const detector = await playwrightSetup.seedEvaluation({
+ team_id: workspace.team_id,
+ name: 'User struggled',
+ evaluation_type: 'hog',
+ evaluation_config: { source: HOG_SOURCE },
+ output_type: 'boolean',
+ output_config: { true_is_failure: true },
+ enabled: true,
+ })
+ const evalAId = detector.evaluation_id
+
+ const quality = await playwrightSetup.seedEvaluation({
+ team_id: workspace.team_id,
+ name: 'Response is accurate',
+ evaluation_type: 'hog',
+ evaluation_config: { source: HOG_SOURCE },
+ output_type: 'boolean',
+ output_config: {},
+ enabled: true,
+ })
+ const evalBId = quality.evaluation_id
+
+ await test.step('identical results invert the pass rate between a detector and a quality check', async () => {
+ const now = Date.now()
+ const detectorEvents = buildBooleanRunEvents(
+ evalAId,
+ 'User struggled',
+ [
+ { result: true },
+ { result: true },
+ { result: true },
+ { result: true },
+ { result: false },
+ { result: null },
+ { result: false, skipped: true },
+ ],
+ now
+ )
+ const qualityEvents = buildBooleanRunEvents(
+ evalBId,
+ 'Response is accurate',
+ [
+ { result: true },
+ { result: true },
+ { result: true },
+ { result: true },
+ { result: false },
+ { result: null },
+ { result: false, skipped: true },
+ ],
+ now
+ )
+ await playwrightSetup.seedEvents(workspace.team_id, [...detectorEvents, ...qualityEvents])
+
+ await page.goto('/ai-evals/evaluations')
+ const detectorRow = page.getByRole('row', { name: /User struggled/ })
+ const qualityRow = page.getByRole('row', { name: /Response is accurate/ })
+ await expect(detectorRow).toBeVisible()
+ await expect(qualityRow).toBeVisible()
+
+ // Scroll before measuring — the table can render below the fold on a fresh
+ // page load, and a clip built from boxes measured pre-scroll lands off-image.
+ await detectorRow.scrollIntoViewIfNeeded()
+
+ // Byte-identical seed data on both evaluations (same 4 true / 1 false / 1 null /
+ // 1 skipped pattern) — the run count has to match too, or a reviewer glancing at the
+ // screenshot could mistake the inverted rates for a difference in the underlying data
+ // rather than in the declared polarity.
+ const detectorRuns = detectorRow.getByText('7 runs', { exact: true })
+ const qualityRuns = qualityRow.getByText('7 runs', { exact: true })
+ await expect(detectorRuns).toBeVisible()
+ await expect(qualityRuns).toBeVisible()
+
+ const detectorRate = detectorRow.getByText('20%', { exact: true })
+ const qualityRate = qualityRow.getByText('80%', { exact: true })
+ await expect(detectorRate).toBeVisible()
+ await expect(detectorRate).toHaveClass(/text-danger/)
+ await expect(qualityRate).toBeVisible()
+ await expect(qualityRate).toHaveClass(/text-success/)
+
+ const detectorBox = await detectorRow.boundingBox()
+ const qualityBox = await qualityRow.boundingBox()
+ const detectorRateBox = await detectorRate.boundingBox()
+ const qualityRateBox = await qualityRate.boundingBox()
+ if (detectorBox && qualityBox && detectorRateBox && qualityRateBox) {
+ const pad = 12
+ const top = Math.max(0, Math.min(detectorBox.y, qualityBox.y) - pad)
+ const bottom = Math.max(detectorBox.y + detectorBox.height, qualityBox.y + qualityBox.height) + pad
+ const left = Math.max(0, Math.min(detectorBox.x, qualityBox.x) - pad)
+ // End at the Runs column's right edge, not the row's full width — the Actions
+ // column past it (folder/edit/delete buttons) adds nothing to the story and,
+ // depending on row width, could clip a button mid-icon with a white gutter after it.
+ const right =
+ Math.max(detectorRateBox.x + detectorRateBox.width, qualityRateBox.x + qualityRateBox.width) + pad
+ await page.screenshot({
+ path: path.join(SCREENSHOT_DIR, '02-list-pass-rate.png'),
+ clip: { x: left, y: top, width: right - left, height: bottom - top },
+ animations: 'disabled',
+ })
+ }
+ })
+
+ await test.step('a true run renders as the undesirable outcome, and the Passing/Failing filter inverts', async () => {
+ await page.goto(`/ai-evals/evaluations/${evalAId}`)
+ await expect(page.getByRole('heading', { name: 'User struggled' })).toBeVisible()
+
+ const trueTags = page.getByText('True', { exact: true })
+ const falseTags = page.getByText('False', { exact: true })
+ await expect(trueTags).toHaveCount(4)
+ await expect(falseTags).toHaveCount(1)
+ for (let i = 0; i < 4; i++) {
+ await expect(trueTags.nth(i)).toHaveClass(/LemonTag--danger/)
+ }
+ await expect(falseTags).toHaveClass(/LemonTag--success/)
+
+ await page.getByRole('button', { name: 'Passing', exact: true }).click()
+ await expect(trueTags).toHaveCount(0)
+ await expect(falseTags).toHaveCount(1)
+ await expect(page.getByText('N/A', { exact: true })).toHaveCount(0)
+ await expect(page.getByText('Skipped', { exact: true })).toHaveCount(0)
+
+ await page.getByRole('button', { name: 'Failing', exact: true }).click()
+ await expect(trueTags).toHaveCount(4)
+ await expect(falseTags).toHaveCount(0)
+ await expect(page.getByText('N/A', { exact: true })).toHaveCount(0)
+ await expect(page.getByText('Skipped', { exact: true })).toHaveCount(0)
+
+ const runsTable = page.getByRole('table')
+ await runsTable.scrollIntoViewIfNeeded()
+ const filtersAndTable = await runsTable.boundingBox()
+ const failingButton = await page.getByRole('button', { name: 'Failing', exact: true }).boundingBox()
+ if (filtersAndTable && failingButton) {
+ const pad = 16
+ const top = Math.max(0, Math.min(filtersAndTable.y, failingButton.y) - pad)
+ const left = Math.max(0, Math.min(filtersAndTable.x, failingButton.x) - pad)
+ const right = filtersAndTable.x + filtersAndTable.width + pad
+ const bottom = Math.min(filtersAndTable.y + 420, filtersAndTable.y + filtersAndTable.height) + pad
+ await page.screenshot({
+ path: path.join(SCREENSHOT_DIR, '03-run-outcomes.png'),
+ clip: { x: left, y: top, width: right - left, height: bottom - top },
+ animations: 'disabled',
+ })
+ }
+ })
+
+ await test.step('a skipped run is excluded from both the passing and failing buckets', async () => {
+ await page.getByRole('button', { name: 'All', exact: true }).click()
+ const skippedTag = page.getByText('Skipped', { exact: true })
+ await expect(skippedTag).toHaveCount(1)
+ await expect(skippedTag).toHaveClass(/LemonTag--muted/)
+ })
+
+ await test.step('N/A and a skipped run behave the same way for the non-detector evaluation', async () => {
+ await expect(page.getByText('N/A', { exact: true })).toHaveCount(1)
+
+ await page.goto(`/ai-evals/evaluations/${evalBId}`)
+ await expect(page.getByRole('heading', { name: 'Response is accurate' })).toBeVisible()
+ const naTag = page.getByText('N/A', { exact: true })
+ const skippedTag = page.getByText('Skipped', { exact: true })
+ await expect(naTag).toHaveCount(1)
+ await expect(naTag).toHaveClass(/LemonTag--muted/)
+ await expect(skippedTag).toHaveCount(1)
+ await expect(skippedTag).toHaveClass(/LemonTag--muted/)
+
+ // Mirrors the detector's Passing/Failing check above — a skipped run is excluded
+ // from both buckets regardless of which polarity the evaluation declares.
+ await page.getByRole('button', { name: 'Passing', exact: true }).click()
+ await expect(skippedTag).toHaveCount(0)
+ await page.getByRole('button', { name: 'Failing', exact: true }).click()
+ await expect(skippedTag).toHaveCount(0)
+ })
+
+ await test.step('a sentiment evaluation is entirely unaffected by the flag', async () => {
+ const sentiment = await playwrightSetup.seedEvaluation({
+ team_id: workspace.team_id,
+ name: 'User message tone',
+ evaluation_type: 'sentiment',
+ evaluation_config: { source: 'user_messages' },
+ output_type: 'sentiment',
+ output_config: {},
+ })
+ const evalCId = sentiment.evaluation_id
+
+ await page.goto(`/ai-evals/evaluations/${evalCId}`)
+ await page.getByTestId('llma-evaluation-configuration-tab').click()
+ await expect(page.getByText('Allow N/A responses', { exact: true })).toHaveCount(0)
+ await expect(page.getByText('A true result flags a problem', { exact: true })).toHaveCount(0)
+
+ const sentimentEvents = buildSentimentRunEvents(
+ evalCId,
+ 'User message tone',
+ ['negative', 'positive'],
+ Date.now()
+ )
+ await playwrightSetup.seedEvents(workspace.team_id, sentimentEvents)
+
+ await page.goto(`/ai-evals/evaluations/${evalCId}`)
+ await expect(page.getByRole('heading', { name: 'User message tone' })).toBeVisible()
+ // The config-tab visit above already mounted this page once, loading (and caching)
+ // an empty runs query before any events existed — a plain reload replays that cached
+ // empty result. Force a fresh query past the cache, same as a user clicking Refresh.
+ await page.getByTestId('llma-evaluation-refresh-runs').click()
+ // Default filter is 'negative' (DEFAULT_SENTIMENT_RUNS_FILTER) — switch to 'All' so
+ // both seeded runs show, and scope tag lookups to the table so they can't resolve to
+ // the segmented filter buttons, which carry the same label text ('Negative', 'Positive').
+ await page.getByRole('button', { name: 'All', exact: true }).click()
+ const runsTable = page.getByRole('table')
+ const negativeTag = runsTable.getByText('Negative', { exact: true })
+ const positiveTag = runsTable.getByText('Positive', { exact: true })
+ await expect(negativeTag).toBeVisible()
+ await expect(positiveTag).toBeVisible()
+ await expect(negativeTag).toHaveClass(/LemonTag--danger/)
+ await expect(positiveTag).toHaveClass(/LemonTag--success/)
+ })
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
index 85860d0bb475..74f35a089f9f 100644
--- a/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
+++ b/products/ai_observability/frontend/evaluations/AIObservabilityEvaluation.tsx
@@ -44,7 +44,7 @@ import { EvaluationReportsCallout } from './components/EvaluationReportsCallout'
import { EvaluationReportsTab } from './components/EvaluationReportsTab'
import { EvaluationRunsTable } from './components/EvaluationRunsTable'
import { EvaluationTriggers } from './components/EvaluationTriggers'
-import { EVALUATION_PASSED_HOGQL, EVALUATION_RUNS_QUERY_LIMIT } from './constants'
+import { EVALUATION_RUNS_QUERY_LIMIT, evaluationPassedHogQL, evaluationPassRateHogQL } from './constants'
import {
evaluationOffersSessionTarget,
evaluationSupportsReports,
@@ -91,6 +91,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
setEvaluationDescription,
setEvaluationEnabled,
setAllowsNA,
+ setTrueIsFailure,
saveEvaluation,
resetEvaluation,
setEvaluationType,
@@ -147,7 +148,7 @@ export function AIObservabilityEvaluation(): JSX.Element {
event: '$ai_evaluation',
custom_name: `${evaluation.name} — Pass rate`,
math: HogQLMathType.HogQL,
- math_hogql: `if(countIf(properties.$ai_evaluation_result IS NOT NULL) > 0, countIf(${EVALUATION_PASSED_HOGQL}) / countIf(properties.$ai_evaluation_result IS NOT NULL) * 100, 0)`,
+ math_hogql: evaluationPassRateHogQL(evaluationPassedHogQL(evaluation)),
properties: [
{
key: '$ai_evaluation_id',
@@ -727,6 +728,32 @@ export function AIObservabilityEvaluation(): JSX.Element {
</div>
</LemonField.Pure>
)}
+
+ {isBooleanOutput && (
+ <LemonField.Pure
+ label={
+ <div className="flex items-center gap-1">
+ <span>A true result flags a problem</span>
+ <Tooltip title="Turn this on when the evaluation looks for something you don't want, like a struggling user or a hallucination. A true result then counts as a fail in reports and pass rates. The evaluation results themselves don't change.">
+ <IconInfo className="text-muted text-base" />
+ </Tooltip>
+ </div>
+ }
+ >
+ <div className="flex items-center gap-2">
+ <LemonSwitch
+ checked={evaluation.output_config.true_is_failure ?? false}
+ onChange={setTrueIsFailure}
+ data-attr="llma-evaluation-true-is-failure-switch"
+ />
+ <span className="text-muted text-sm">
+ {evaluation.output_config.true_is_failure
+ ? 'A true result counts as a fail'
+ : 'A true result counts as a pass'}
+ </span>
+ </div>
+ </LemonField.Pure>
+ )}
</div>
</div>
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
new file mode 100644
index 000000000000..156f13982870
--- /dev/null
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.test.tsx
@@ -0,0 +1,137 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { TestHogResultItemApi } from '../../generated/api.schemas'
+import { llmEvaluationLogic } from '../llmEvaluationLogic'
+import { EvaluationConfig } from '../types'
+import { EvaluationCodeEditor, HogTestResultsPanel } from './EvaluationCodeEditor'
+
+jest.mock('lib/monaco/CodeEditorResizable', () => ({
+ CodeEditorResizeable: () => <div data-attr="mock-code-editor" />,
+}))
+
+const props = { evaluationId: 'eval-123' }
+
+const baseEvaluation: EvaluationConfig = {
+ id: 'eval-123',
+ name: 'Test Evaluation',
+ description: '',
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'hog',
+ evaluation_config: { source: 'return true' },
+ output_type: 'boolean',
+ output_config: { allows_na: false },
+ conditions: [{ id: 'cond-1', rollout_percentage: 100, properties: [] }],
+ target: 'generation',
+ target_config: {},
+ model_configuration: null,
+ total_runs: 0,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+}
+
+const trueResult: TestHogResultItemApi = {
+ sample_id: 'gen-1',
+ sample_type: 'generation',
+ event_uuid: 'gen-1',
+ trace_id: 'trace-1',
+ input_preview: 'hello',
+ output_preview: 'world',
+ result: true,
+ reasoning: '',
+ error: null,
+}
+
+function renderPanel(): void {
+ render(
+ <Provider>
+ <BindLogic logic={llmEvaluationLogic} props={props}>
+ <HogTestResultsPanel />
+ </BindLogic>
+ </Provider>
+ )
+}
+
+function renderEditor(): void {
+ render(
+ <Provider>
+ <BindLogic logic={llmEvaluationLogic} props={props}>
+ <EvaluationCodeEditor />
+ </BindLogic>
+ </Provider>
+ )
+}
+
+describe('EvaluationCodeEditor', () => {
+ let logic: ReturnType<typeof llmEvaluationLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:teamId/llm_analytics/provider_keys/': { results: [] },
+ '/api/environments/:teamId/llm_analytics/evaluation_config/': {
+ active_provider_key: null,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ },
+ '/api/projects/:teamId/evaluations/:id/': {},
+ },
+ })
+ initKeaTests()
+ logic = llmEvaluationLogic(props)
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic?.unmount()
+ })
+
+ it('labels a true result as a pass for a plain evaluation', () => {
+ logic.actions.loadEvaluationSuccess(baseEvaluation)
+ logic.actions.testHogOnSampleSuccess([trueResult])
+ renderPanel()
+
+ expect(screen.getByText('1 passed')).toBeInTheDocument()
+ expect(screen.getByText('0 failed')).toBeInTheDocument()
+ expect(screen.getByText('Pass')).toBeInTheDocument()
+ expect(screen.queryByText('Fail')).not.toBeInTheDocument()
+ })
+
+ it('labels a true result as a fail for a detector, matching the polarity switch', () => {
+ logic.actions.loadEvaluationSuccess({
+ ...baseEvaluation,
+ output_config: { allows_na: false, true_is_failure: true },
+ })
+ logic.actions.testHogOnSampleSuccess([trueResult])
+ renderPanel()
+
+ expect(screen.getByText('0 passed')).toBeInTheDocument()
+ expect(screen.getByText('1 failed')).toBeInTheDocument()
+ expect(screen.getByText('Fail')).toBeInTheDocument()
+ expect(screen.queryByText('Pass')).not.toBeInTheDocument()
+ })
+
+ it('describes detector polarity in the authoring tip', () => {
+ logic.actions.loadEvaluationSuccess({
+ ...baseEvaluation,
+ output_config: { allows_na: false, true_is_failure: true },
+ })
+ renderEditor()
+
+ expect(
+ screen.getByText(
+ (_, element) =>
+ element?.tagName === 'LI' && element.textContent === 'Return true (fail) or false (pass)'
+ )
+ ).toBeInTheDocument()
+ })
+})
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
index 80070606c6a6..1b66f5fbe4de 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx
@@ -10,6 +10,7 @@ import { useOpenAi } from '~/scenes/max/useOpenAi'
import { urls } from '~/scenes/urls'
import type { TestHogResultItemApi } from '../../generated/api.schemas'
+import { evaluationIsDetector } from '../constants'
import { HOG_EVAL_EXAMPLES } from '../hogEvalExamples'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import type { EvaluationTarget } from '../types'
@@ -187,16 +188,18 @@ const HOG_EVAL_GLOBALS_BY_TARGET = {
session: HOG_EVAL_COMMON_GLOBALS_BY_TARGET.session,
}
-function HogTestResultsPanel(): JSX.Element | null {
- const { hogTestResults, hogTestResultsLoading, hogTestMessage } = useValues(llmEvaluationLogic)
+export function HogTestResultsPanel(): JSX.Element | null {
+ const { hogTestResults, hogTestResultsLoading, hogTestMessage, evaluation } = useValues(llmEvaluationLogic)
const { clearHogTestResults } = useActions(llmEvaluationLogic)
if (!hogTestResults && !hogTestResultsLoading) {
return null
}
- const passed = hogTestResults?.filter((r) => r.result === true).length ?? 0
- const failed = hogTestResults?.filter((r) => r.result === false).length ?? 0
+ // Every result here belongs to `evaluation`, so its polarity applies to the whole panel.
+ const trueIsFailure = !!evaluation && evaluationIsDetector(evaluation)
+ const passed = hogTestResults?.filter((r) => r.result === !trueIsFailure).length ?? 0
+ const failed = hogTestResults?.filter((r) => r.result === trueIsFailure).length ?? 0
const na = hogTestResults?.filter((r) => r.result === null && !r.error).length ?? 0
const errors = hogTestResults?.filter((r) => r.error !== null).length ?? 0
@@ -256,7 +259,7 @@ function HogTestResultsPanel(): JSX.Element | null {
</LemonTag>
)
}
- return row.result ? (
+ return row.result !== trueIsFailure ? (
<LemonTag type="success" icon={<IconCheck />}>
Pass
</LemonTag>
@@ -329,6 +332,7 @@ export function EvaluationCodeEditor(): JSX.Element {
const source = evaluation.evaluation_config.source
const isSessionTarget = evaluation.target === 'session'
+ const trueIsFailure = evaluationIsDetector(evaluation)
return (
<div className="space-y-4">
@@ -457,7 +461,8 @@ export function EvaluationCodeEditor(): JSX.Element {
<h4 className="text-sm font-semibold mt-3 mb-2">Tips</h4>
<ul className="text-sm text-muted space-y-1 list-disc list-inside">
<li>
- Return <code>true</code> (pass) or <code>false</code> (fail)
+ Return <code>true</code> ({trueIsFailure ? 'fail' : 'pass'}) or <code>false</code> (
+ {trueIsFailure ? 'pass' : 'fail'})
{evaluation.output_config.allows_na ? (
<>
{' '}
diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
index 254aaa9f3b41..4c0ba8361983 100644
--- a/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
+++ b/products/ai_observability/frontend/evaluations/components/EvaluationRunsTable.tsx
@@ -8,6 +8,7 @@ import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { EvaluationResultTag, getEvaluationResultSortValue } from '../../components/EvaluationResultTag'
import { EvaluationRunTargetCell } from '../../components/EvaluationRunTargetCell'
+import { evaluationIsDetector } from '../constants'
import { evaluationSupportsRunOutcomes } from '../evaluationCapabilities'
import { llmEvaluationLogic } from '../llmEvaluationLogic'
import { EvaluationRun, SentimentEvaluationRunsFilter } from '../types'
@@ -43,6 +44,8 @@ export function EvaluationRunsTable(): JSX.Element {
const { refreshEvaluationRuns } = useActions(llmEvaluationLogic)
const showOutcomeFilters = evaluationSupportsRunOutcomes(evaluation)
const showSentimentFilters = evaluation?.evaluation_type === 'sentiment'
+ // Every run in this table belongs to `evaluation`, so its polarity applies to the whole column.
+ const trueIsFailure = !!evaluation && evaluationIsDetector(evaluation)
// A filter is hiding rows when the evaluation has runs but none match the current filter.
const filterHidesRuns = evaluationRuns.length > 0 && filteredEvaluationRuns.length === 0
@@ -95,9 +98,12 @@ export function EvaluationRunsTable(): JSX.Element {
{
title: 'Result',
key: 'result',
- render: (_, run) => <EvaluationResultTag run={run} />,
+ render: (_, run) => <EvaluationResultTag run={run} trueIsFailure={trueIsFailure} />,
sorter: (a, b) => {
- return getEvaluationResultSortValue(b) - getEvaluationResultSortValue(a)
+ return (
+ getEvaluationResultSortValue(b, { trueIsFailure }) -
+ getEvaluationResultSortValue(a, { trueIsFailure })
+ )
},
},
{
diff --git a/products/ai_observability/frontend/evaluations/constants.ts b/products/ai_observability/frontend/evaluations/constants.ts
index 37f0d0609b45..56c6f4eb901e 100644
--- a/products/ai_observability/frontend/evaluations/constants.ts
+++ b/products/ai_observability/frontend/evaluations/constants.ts
@@ -1,3 +1,7 @@
+import { escapeHogQLString } from '~/queries/utils'
+
+import type { EvaluationConfig } from './types'
+
// Most-recent runs fetched for an evaluation's runs table and its result badges
export const EVALUATION_RUNS_QUERY_LIMIT = 250
@@ -7,7 +11,8 @@ export const EVALUATION_RUNS_QUERY_LIMIT = 250
// still compare correctly against the string form. Reading the property directly rather than via
// JSONExtractString keeps the lookup on the properties_group_ai column and its bloom filter index.
// Same reasoning as the predicates in posthog/temporal/ai_observability/eval_reports/output_types.py.
-export const EVALUATION_PASSED_HOGQL = "properties.$ai_evaluation_result = 'true'"
+export const EVALUATION_RESULT_TRUE_HOGQL = "properties.$ai_evaluation_result = 'true'"
+const EVALUATION_RESULT_FALSE_HOGQL = "properties.$ai_evaluation_result = 'false'"
// A skipped run was never graded, but an evaluation that disallows N/A still emits result=false
// alongside skipped=true, so any count that doesn't exclude skips reads them as failures. Mirrors
@@ -15,3 +20,31 @@ export const EVALUATION_PASSED_HOGQL = "properties.$ai_evaluation_result = 'true
// the report metrics already apply — without this the two surfaces disagree about the same runs.
export const EVALUATION_NOT_SKIPPED_HOGQL =
"(isNull(properties.$ai_evaluation_skipped) OR properties.$ai_evaluation_skipped != 'true')"
+
+/** A detector looks for a problem, so its true result is the undesirable one. */
+export function evaluationIsDetector(evaluation: Pick<EvaluationConfig, 'output_config'>): boolean {
+ return evaluation.output_config.true_is_failure === true
+}
+
+/** The HogQL that counts a pass for one evaluation. */
+export function evaluationPassedHogQL(evaluation: Pick<EvaluationConfig, 'output_config'>): string {
+ return evaluationIsDetector(evaluation) ? EVALUATION_RESULT_FALSE_HOGQL : EVALUATION_RESULT_TRUE_HOGQL
+}
+
+/**
+ * The HogQL for a pass rate, as a percentage of the graded runs. Skipped runs leave both sides of
+ * the ratio, so a detector never reads the false a skip stores as a pass.
+ */
+export function evaluationPassRateHogQL(passedExpression: string): string {
+ const graded = `countIf(properties.$ai_evaluation_result IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL})`
+ return `if(${graded} > 0, countIf((${passedExpression}) AND ${EVALUATION_NOT_SKIPPED_HOGQL}) / ${graded} * 100, 0)`
+}
+
+/** The HogQL that counts a pass across many evaluations at once, for a grouped or broken-down query. */
+export function evaluationPassedHogQLForMany(detectorEvaluationIds: string[]): string {
+ if (detectorEvaluationIds.length === 0) {
+ return EVALUATION_RESULT_TRUE_HOGQL
+ }
+ const ids = detectorEvaluationIds.map((id) => escapeHogQLString(id)).join(', ')
+ return `if(properties.$ai_evaluation_id IN (${ids}), ${EVALUATION_RESULT_FALSE_HOGQL}, ${EVALUATION_RESULT_TRUE_HOGQL})`
+}
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
index 5531dfb78f7f..6c889c3cdfc1 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.test.ts
@@ -6,10 +6,13 @@ import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { evaluationMetricsLogic, EvaluationStats } from './evaluationMetricsLogic'
+import { EVALUATION_NOT_SKIPPED_HOGQL, EVALUATION_RESULT_TRUE_HOGQL } from './constants'
+import { evaluationMetricsLogic, EvaluationStatsRow } from './evaluationMetricsLogic'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
import { LLMJudgeEvaluation } from './types'
+const queryMock = jest.fn().mockResolvedValue({ results: [] })
+
jest.mock('lib/api', () => {
const actual = jest.requireActual('lib/api')
@@ -18,7 +21,7 @@ jest.mock('lib/api', () => {
...actual,
default: {
...actual.default,
- query: jest.fn().mockResolvedValue({ results: [] }),
+ query: (...args: unknown[]) => queryMock(...args),
},
}
})
@@ -45,12 +48,11 @@ const evaluation = (id: string, directoryId: string | null, name = `Evaluation $
updated_at: '2024-01-01T00:00:00Z',
})
-const stats = (evaluationId: string, runsCount: number): EvaluationStats => ({
+const stats = (evaluationId: string, runsCount: number, trueCount = runsCount): EvaluationStatsRow => ({
evaluation_id: evaluationId,
runs_count: runsCount,
applicable_count: runsCount,
- pass_count: runsCount,
- pass_rate: 100,
+ true_count: trueCount,
applicability_rate: 100,
})
@@ -131,4 +133,43 @@ describe('evaluationMetricsLogic', () => {
expect(metricsLogic.values.chartQuery?.breakdownFilter?.breakdown).not.toContain(firstRootEvaluation.id)
expect(metricsLogic.values.summaryMetrics.total_runs).toBe(2)
})
+
+ it('reads a detector pass rate from its false results', () => {
+ const detector = { ...evaluation('detector', null), output_config: { true_is_failure: true } }
+ const quality = evaluation('quality', null)
+
+ evaluationsLogic.actions.loadEvaluationsSuccess([detector, quality])
+ metricsLogic.actions.loadStatsSuccess([stats('detector', 100, 80), stats('quality', 100, 80)])
+
+ expect(metricsLogic.values.evaluationsWithMetrics).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ id: 'detector', stats: expect.objectContaining({ pass_rate: 20 }) }),
+ expect.objectContaining({ id: 'quality', stats: expect.objectContaining({ pass_rate: 80 }) }),
+ ])
+ )
+ })
+
+ it('scopes the chart pass expression to a detector among the enabled evaluations', () => {
+ const detector = { ...evaluation('detector', null), output_config: { true_is_failure: true } }
+ const quality = evaluation('quality', null)
+
+ evaluationsLogic.actions.loadEvaluationsSuccess([detector, quality])
+ metricsLogic.actions.loadStatsSuccess([stats('detector', 10, 2), stats('quality', 10, 8)])
+
+ const mathHogql = metricsLogic.values.chartQuery?.series?.[0].math_hogql ?? ''
+ expect(mathHogql).toContain("properties.$ai_evaluation_id IN ('detector')")
+ expect(mathHogql).toContain("properties.$ai_evaluation_result = 'false'")
+ // Both sides of the ratio drop skipped runs — otherwise the false a skip stores reads as
+ // a detector pass, and the chart disagrees with the list, which already excludes them.
+ expect(mathHogql).toContain(`AND ${EVALUATION_NOT_SKIPPED_HOGQL}) /`)
+ expect(mathHogql).toContain(`IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}`)
+ })
+
+ it('excludes skipped runs from both counts, so a detector cannot count them as a pass', async () => {
+ await expectLogic(metricsLogic, () => metricsLogic.actions.loadStats()).toFinishAllListeners()
+
+ const query = queryMock.mock.calls.at(-1)?.[0]
+ expect(query.query).toContain(`IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}`)
+ expect(query.query).toContain(`${EVALUATION_RESULT_TRUE_HOGQL} AND ${EVALUATION_NOT_SKIPPED_HOGQL}`)
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
index 6028ad568f0f..2ca1442aa9be 100644
--- a/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/evaluationMetricsLogic.ts
@@ -10,20 +10,32 @@ import { ChartDisplayType, HogQLMathType, PropertyFilterType, PropertyOperator }
// eslint-disable-next-line import/no-cycle
import { PASS_RATE_SUCCESS_THRESHOLD } from './components/EvaluationMetrics'
-import { EVALUATION_PASSED_HOGQL } from './constants'
+import {
+ EVALUATION_NOT_SKIPPED_HOGQL,
+ EVALUATION_RESULT_TRUE_HOGQL,
+ evaluationIsDetector,
+ evaluationPassedHogQLForMany,
+ evaluationPassRateHogQL,
+} from './constants'
import { llmEvaluationsLogic } from './llmEvaluationsLogic'
import { EvaluationConfig } from './types'
const MIN_RUNS_FOR_FAILING_STATUS = 3
const MAX_EVALUATION_CHART_SERIES = 10
-export interface EvaluationStats {
+/** One row from the stats query. Polarity-free by design — the query never claims a pass. */
+export interface EvaluationStatsRow {
evaluation_id: string
runs_count: number
applicable_count: number
+ true_count: number
+ applicability_rate: number
+}
+
+/** A stats row with the evaluation's own polarity applied. */
+export interface EvaluationStats extends EvaluationStatsRow {
pass_count: number
pass_rate: number
- applicability_rate: number
}
export interface SummaryMetrics {
@@ -32,7 +44,7 @@ export interface SummaryMetrics {
failing_evaluations_count: number
}
-type RawStatsRow = [evaluation_id: string, runs_count: number, applicable_count: number, pass_count: number]
+type RawStatsRow = [evaluation_id: string, runs_count: number, applicable_count: number, true_count: number]
export type EvaluationMetricsLogicProps = Record<string, never>
@@ -96,7 +108,7 @@ export interface evaluationMetricsLogicValues {
stats?: EvaluationStats
}
>
- stats: EvaluationStats[]
+ stats: EvaluationStatsRow[]
statsLoading: boolean
summaryMetrics: SummaryMetrics
}
@@ -123,9 +135,8 @@ export interface evaluationMetricsLogicActions {
applicability_rate: number
applicable_count: number
evaluation_id: string
- pass_count: number
- pass_rate: number
runs_count: number
+ true_count: number
}[],
payload?: any
) => {
@@ -133,9 +144,8 @@ export interface evaluationMetricsLogicActions {
applicability_rate: number
applicable_count: number
evaluation_id: string
- pass_count: number
- pass_rate: number
runs_count: number
+ true_count: number
}[]
payload?: any
}
@@ -151,15 +161,20 @@ export interface evaluationMetricsLogicMeta {
evaluations: EvaluationConfig[],
selectedDirectoryId: string | null
) => EvaluationConfig[]
- summaryMetrics: (stats: EvaluationStats[], evaluationsForMetrics: EvaluationConfig[]) => SummaryMetrics
evaluationsWithMetrics: (
evaluations: EvaluationConfig[],
- stats: EvaluationStats[]
+ stats: EvaluationStatsRow[]
) => Array<
EvaluationConfig & {
stats?: EvaluationStats
}
>
+ summaryMetrics: (
+ evaluationsWithMetrics: (EvaluationConfig & {
+ stats?: EvaluationStats
+ })[],
+ evaluationsForMetrics: EvaluationConfig[]
+ ) => SummaryMetrics
chartQuery: (
evaluationsForMetrics: EvaluationConfig[],
dateFilter: {
@@ -192,7 +207,7 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
loaders(({ values }) => ({
stats: [
- [] as EvaluationStats[],
+ [] as EvaluationStatsRow[],
{
loadStats: async () => {
const dateFrom = values.dateFilter.dateFrom || '-1d'
@@ -204,8 +219,8 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
SELECT
properties.$ai_evaluation_id as evaluation_id,
count() as runs_count,
- countIf(properties.$ai_evaluation_result IS NOT NULL) as applicable_count,
- countIf(${EVALUATION_PASSED_HOGQL}) as pass_count
+ countIf(properties.$ai_evaluation_result IS NOT NULL AND ${EVALUATION_NOT_SKIPPED_HOGQL}) as applicable_count,
+ countIf(${EVALUATION_RESULT_TRUE_HOGQL} AND ${EVALUATION_NOT_SKIPPED_HOGQL}) as true_count
FROM events
WHERE event = '$ai_evaluation' AND {filters}
GROUP BY evaluation_id
@@ -224,17 +239,14 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
return (response.results || []).map((row: RawStatsRow) => {
const runs_count = row[1]
const applicable_count = row[2]
- const pass_count = row[3]
- // Pass rate excludes N/A results (uses applicable_count as denominator)
- const pass_rate = applicable_count > 0 ? (pass_count / applicable_count) * 100 : 0
+ const true_count = row[3]
const applicability_rate = runs_count > 0 ? (applicable_count / runs_count) * 100 : 0
return {
evaluation_id: row[0],
runs_count,
applicable_count,
- pass_count,
- pass_rate: Math.round(pass_rate * 10) / 10,
+ true_count,
applicability_rate: Math.round(applicability_rate * 10) / 10,
}
})
@@ -253,14 +265,45 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
(evaluations: EvaluationConfig[], selectedDirectoryId: string | null): EvaluationConfig[] =>
evaluations.filter((evaluation) => (evaluation.directory_id ?? null) === selectedDirectoryId),
],
+ evaluationsWithMetrics: [
+ (s) => [s.evaluations, s.stats],
+ (
+ evaluations: EvaluationConfig[],
+ stats: EvaluationStatsRow[]
+ ): Array<EvaluationConfig & { stats?: EvaluationStats }> => {
+ const statsMap = new Map(stats.map((stat) => [stat.evaluation_id, stat]))
+
+ return evaluations.map((evaluation) => {
+ const stat = statsMap.get(evaluation.id)
+ if (!stat) {
+ return { ...evaluation }
+ }
+ // Pass rate excludes N/A results (uses applicable_count as denominator)
+ const pass_count = evaluationIsDetector(evaluation)
+ ? stat.applicable_count - stat.true_count
+ : stat.true_count
+ const pass_rate =
+ stat.applicable_count > 0 ? Math.round((pass_count / stat.applicable_count) * 1000) / 10 : 0
+ return { ...evaluation, stats: { ...stat, pass_count, pass_rate } }
+ })
+ },
+ ],
+
summaryMetrics: [
- (s) => [s.stats, s.evaluationsForMetrics],
- (stats: EvaluationStats[], evaluationsForMetrics: EvaluationConfig[]): SummaryMetrics => {
- const evaluationIds = new Set(evaluationsForMetrics.map((evaluation) => evaluation.id))
- const statsForMetrics = stats.filter((stat) => evaluationIds.has(stat.evaluation_id))
- const total_runs = statsForMetrics.reduce((sum: number, stat) => sum + stat.runs_count, 0)
- const total_applicable = statsForMetrics.reduce((sum: number, stat) => sum + stat.applicable_count, 0)
- const total_passes = statsForMetrics.reduce((sum: number, stat) => sum + stat.pass_count, 0)
+ (s) => [s.evaluationsWithMetrics, s.evaluationsForMetrics],
+ (
+ evaluationsWithMetrics: Array<EvaluationConfig & { stats?: EvaluationStats }>,
+ evaluationsForMetrics: EvaluationConfig[]
+ ): SummaryMetrics => {
+ const ids = new Set(evaluationsForMetrics.map((evaluation) => evaluation.id))
+ const statsForMetrics = evaluationsWithMetrics
+ .filter((evaluation) => ids.has(evaluation.id))
+ .map((evaluation) => evaluation.stats)
+ .filter((stat): stat is EvaluationStats => stat != null)
+
+ const total_runs = statsForMetrics.reduce((sum, stat) => sum + stat.runs_count, 0)
+ const total_applicable = statsForMetrics.reduce((sum, stat) => sum + stat.applicable_count, 0)
+ const total_passes = statsForMetrics.reduce((sum, stat) => sum + stat.pass_count, 0)
// Overall pass rate excludes N/A results
const overall_pass_rate = total_applicable > 0 ? (total_passes / total_applicable) * 100 : 0
@@ -280,21 +323,6 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
},
],
- evaluationsWithMetrics: [
- (s) => [s.evaluations, s.stats],
- (
- evaluations: EvaluationConfig[],
- stats: EvaluationStats[]
- ): Array<EvaluationConfig & { stats?: EvaluationStats }> => {
- const statsMap = new Map(stats.map((stat) => [stat.evaluation_id, stat]))
-
- return evaluations.map((evaluation) => ({
- ...evaluation,
- stats: statsMap.get(evaluation.id),
- }))
- },
- ],
-
chartQuery: [
(s) => [s.evaluationsForMetrics, s.dateFilter],
(
@@ -320,8 +348,11 @@ export const evaluationMetricsLogic = kea<evaluationMetricsLogicType>([
kind: NodeKind.EventsNode,
event: '$ai_evaluation',
math: HogQLMathType.HogQL,
- // Pass rate excludes N/A results, returns 0 if all results are N/A
- math_hogql: `if(countIf(properties.$ai_evaluation_result IS NOT NULL) > 0, countIf(${EVALUATION_PASSED_HOGQL}) / countIf(properties.$ai_evaluation_result IS NOT NULL) * 100, 0)`,
+ math_hogql: evaluationPassRateHogQL(
+ evaluationPassedHogQLForMany(
+ enabledEvaluations.filter(evaluationIsDetector).map((evaluation) => evaluation.id)
+ )
+ ),
properties: [
{
key: '$ai_evaluation_id',
diff --git a/products/ai_observability/frontend/evaluations/hogEvalExamples.json b/products/ai_observability/frontend/evaluations/hogEvalExamples.json
index 7c95ac776c57..78ee14c44392 100644
--- a/products/ai_observability/frontend/evaluations/hogEvalExamples.json
+++ b/products/ai_observability/frontend/evaluations/hogEvalExamples.json
@@ -2,7 +2,7 @@
{
"key": "quickstart",
"label": "Quickstart",
- "source": "// Globals: evaluation_events (one generation event, or every event in a trace) and target\nprint(concat('Evaluating ', target.type, ' ', target.id))\n\nfor (let i, item in evaluation_events) {\n print(concat('Event ', toString(i), ': ', item.event))\n if (length(item.input_text) > 0) {\n print(concat('Input: ', substring(item.input_text, 1, 100)))\n }\n if (length(item.output_text) > 0) {\n print(concat('Output: ', substring(item.output_text, 1, 100)))\n }\n if (item.properties.$ai_model != null) {\n print(concat('Model: ', item.properties.$ai_model))\n }\n}\n\n// Return true (pass) or false (fail)\nreturn true"
+ "source": "// Globals: evaluation_events (one generation event, or every event in a trace) and target\nprint(concat('Evaluating ', target.type, ' ', target.id))\n\nfor (let i, item in evaluation_events) {\n print(concat('Event ', toString(i), ': ', item.event))\n if (length(item.input_text) > 0) {\n print(concat('Input: ', substring(item.input_text, 1, 100)))\n }\n if (length(item.output_text) > 0) {\n print(concat('Output: ', substring(item.output_text, 1, 100)))\n }\n if (item.properties.$ai_model != null) {\n print(concat('Model: ', item.properties.$ai_model))\n }\n}\n\n// The evaluation's output settings decide which boolean counts as a failure\nreturn true"
},
{
"key": "output_not_empty",
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 8251276a26b0..2e9fd104fd8a 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -300,6 +300,18 @@ describe('llmEvaluationLogic', () => {
})
})
+ it('records the polarity on the boolean output config', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadEvaluationSuccess({ ...mockEvaluation })
+ logic.actions.setTrueIsFailure(true)
+ }).toMatchValues({
+ evaluation: expect.objectContaining({
+ output_config: { allows_na: false, true_is_failure: true },
+ }),
+ hasUnsavedChanges: true,
+ })
+ })
+
it('setTriggerConditions updates conditions', async () => {
await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])
@@ -739,7 +751,7 @@ return result`,
})
it('calculates summary from server-side aggregate counts', async () => {
- logic.actions.loadRunsStatsSuccess({ total: 3, applicable: 2, passed: 1 })
+ logic.actions.loadRunsStatsSuccess({ total: 3, applicable: 2, trueCount: 1 })
await expectLogic(logic).toMatchValues({
runsSummary: {
@@ -992,6 +1004,19 @@ return result`,
})
})
+ it('treats a false result as a pass for a detector', async () => {
+ logic.actions.loadEvaluationSuccess({
+ ...mockEvaluation,
+ output_config: { allows_na: false, true_is_failure: true },
+ })
+ logic.actions.loadEvaluationRunsSuccess(mockRuns)
+ logic.actions.setEvaluationRunsFilter('pass', 'all')
+
+ await expectLogic(logic).toMatchValues({
+ filteredEvaluationRuns: [expect.objectContaining({ id: 'run-2', result: false })],
+ })
+ })
+
it('returns only failing runs when filter is fail', async () => {
logic.actions.loadEvaluationRunsSuccess(mockRuns)
logic.actions.setEvaluationRunsFilter('fail', 'all')
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
index 9e622bf81d31..ba563849bde1 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts
@@ -25,6 +25,7 @@ import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmPr
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { EvaluationRunsStats, queryEvaluationRuns, queryEvaluationRunsStats } from '../utils'
import { evaluationErrorMessage } from './apiErrors'
+import { evaluationIsDetector } from './constants'
import {
evaluationCanResolveModel,
evaluationSupportsReports,
@@ -148,7 +149,11 @@ function toSentimentEvaluation(evaluation: EvaluationConfig): SentimentEvaluatio
}
}
-function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationRunsFilter): EvaluationRun[] {
+function filterEvaluationRuns(
+ runs: EvaluationRun[],
+ filter: EvaluationRunsFilter,
+ evaluation: EvaluationConfig | null
+): EvaluationRun[] {
if (filter === 'all') {
return runs
}
@@ -157,11 +162,12 @@ function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationRunsFilte
// A skipped run carries result=false when the evaluation disallows N/A, so it has to be
// excluded before the outcome is read or it lands in the fail bucket without being graded.
const gradedRuns = completedRuns.filter((r) => !r.skipped)
+ const passingResult = !(evaluation && evaluationIsDetector(evaluation))
if (filter === 'pass') {
- return gradedRuns.filter((r) => r.result === true)
+ return gradedRuns.filter((r) => r.result === passingResult)
}
if (filter === 'fail') {
- return gradedRuns.filter((r) => r.result === false)
+ return gradedRuns.filter((r) => r.result === !passingResult)
}
if (filter === 'na') {
return gradedRuns.filter((r) => r.result === null)
@@ -379,6 +385,9 @@ export interface llmEvaluationLogicActions {
setTriggerConditions: (conditions: EvaluationConditionSet[]) => {
conditions: EvaluationConditionSet[]
}
+ setTrueIsFailure: (trueIsFailure: boolean) => {
+ trueIsFailure: boolean
+ }
testHogOnSample: (_?: void) => void
testHogOnSampleFailure: (
error: string,
@@ -417,7 +426,10 @@ export interface llmEvaluationLogicMeta {
evaluation: EvaluationConfig | null,
providerKeys: LLMProviderKey[]
) => LLMProviderKey | null
- runsSummary: (runsStats: EvaluationRunsStats | null) => {
+ runsSummary: (
+ runsStats: EvaluationRunsStats | null,
+ evaluation: EvaluationConfig | null
+ ) => {
applicabilityRate: number
errors: number
failed: number
@@ -427,7 +439,8 @@ export interface llmEvaluationLogicMeta {
} | null
filteredEvaluationRuns: (
evaluationRuns: EvaluationRun[],
- evaluationRunsFilter: EvaluationRunsFilter
+ evaluationRunsFilter: EvaluationRunsFilter,
+ evaluation: EvaluationConfig | null
) => EvaluationRun[]
breadcrumbs: (
evaluation: EvaluationConfig | null,
@@ -475,6 +488,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setEvaluationPrompt: (prompt: string) => ({ prompt }),
setEvaluationEnabled: (enabled: boolean) => ({ enabled }),
setAllowsNA: (allowsNA: boolean) => ({ allowsNA }),
+ setTrueIsFailure: (trueIsFailure: boolean) => ({ trueIsFailure }),
setTriggerConditions: (conditions: EvaluationConditionSet[]) => ({ conditions }),
setModelConfiguration: (modelConfiguration: ModelConfiguration | null) => ({ modelConfiguration }),
setEvaluationType: (evaluationType: EvaluationType) => ({ evaluationType }),
@@ -626,6 +640,10 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
state && isBooleanEvaluationOutput(state.output_type)
? { ...state, output_config: { ...state.output_config, allows_na: allowsNA } }
: state,
+ setTrueIsFailure: (state, { trueIsFailure }) =>
+ state && isBooleanEvaluationOutput(state.output_type)
+ ? { ...state, output_config: { ...state.output_config, true_is_failure: trueIsFailure } }
+ : state,
setTriggerConditions: (state, { conditions }) =>
state
? {
@@ -766,6 +784,7 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
setEvaluationPrompt: () => true,
setEvaluationEnabled: () => true,
setAllowsNA: () => true,
+ setTrueIsFailure: () => true,
setTriggerConditions: () => true,
setModelConfiguration: () => true,
setEvaluationType: () => true,
@@ -1150,13 +1169,14 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
],
runsSummary: [
- (s) => [s.runsStats],
- (stats: EvaluationRunsStats | null) => {
+ (s) => [s.runsStats, s.evaluation],
+ (stats: EvaluationRunsStats | null, evaluation: EvaluationConfig | null) => {
if (!stats || stats.total === 0) {
return null
}
- const { total, applicable, passed } = stats
+ const { total, applicable, trueCount } = stats
+ const passed = evaluation && evaluationIsDetector(evaluation) ? applicable - trueCount : trueCount
// Applicable runs excludes N/A results
const failed = applicable - passed
@@ -1172,9 +1192,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([
],
filteredEvaluationRuns: [
- (s) => [s.evaluationRuns, s.evaluationRunsFilter],
- (runs: EvaluationRun[], filter: EvaluationRunsFilter): EvaluationRun[] =>
- filterEvaluationRuns(runs, filter),
+ (s) => [s.evaluationRuns, s.evaluationRunsFilter, s.evaluation],
+ (
+ runs: EvaluationRun[],
+ filter: EvaluationRunsFilter,
+ evaluation: EvaluationConfig | null
+ ): EvaluationRun[] => filterEvaluationRuns(runs, filter, evaluation),
],
breadcrumbs: [
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
index 376f3e0665a6..00dc936eb663 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
@@ -1,14 +1,21 @@
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
-import { llmEvaluationsLogic } from './llmEvaluationsLogic'
-import { HogEvaluation, LLMJudgeEvaluation, SentimentEvaluation } from './types'
+import { llmEvaluationsLogic, waitForEvaluationsSettled } from './llmEvaluationsLogic'
+import {
+ EvaluationConfig,
+ EvaluationOutputConfig,
+ HogEvaluation,
+ LLMJudgeEvaluation,
+ SentimentEvaluation,
+} from './types'
const mockProviderKeys: LLMProviderKey[] = [
{
@@ -52,6 +59,29 @@ const mockProviderKeys: LLMProviderKey[] = [
},
]
+const evaluationWithOutputConfig = (id: string, outputConfig: EvaluationOutputConfig): EvaluationConfig =>
+ ({
+ id,
+ name: `Evaluation ${id}`,
+ description: '',
+ directory_id: null,
+ enabled: true,
+ status: 'active',
+ status_reason: null,
+ status_reason_detail: null,
+ evaluation_type: 'llm_judge',
+ evaluation_config: { prompt: 'Prompt' },
+ output_type: 'boolean',
+ output_config: outputConfig,
+ conditions: [],
+ target: 'generation',
+ target_config: {},
+ model_configuration: null,
+ total_runs: 0,
+ created_at: '2024-01-01T00:00:00Z',
+ updated_at: '2024-01-01T00:00:00Z',
+ }) as EvaluationConfig
+
const evaluationWithKey = (
id: string,
providerKeyId: string | null,
@@ -342,4 +372,106 @@ describe('llmEvaluationsLogic', () => {
expect(logic.values.evaluations).toEqual([newerEvaluation, olderEvaluation])
})
})
+
+ describe('detectorEvaluationIds', () => {
+ it('lists only evaluations whose true result is a failure', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadEvaluationsSuccess([
+ evaluationWithOutputConfig('detector', { true_is_failure: true }),
+ evaluationWithOutputConfig('quality', { true_is_failure: false }),
+ evaluationWithOutputConfig('legacy', {}),
+ ])
+ }).toMatchValues({ detectorEvaluationIds: ['detector'] })
+ })
+ })
+
+ describe('evaluationsLoading', () => {
+ it('clears when no team is available, instead of hanging forever', async () => {
+ // A hard load straight onto a scene before the team resolves is a real way to hit
+ // this: currentTeamId reads null, and the loader must still settle.
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+
+ await expectLogic(logic, () => {
+ logic.actions.loadEvaluations()
+ }).toDispatchActions(['loadEvaluations', 'loadEvaluationsFailure'])
+
+ expect(logic.values.evaluationsLoading).toBe(false)
+ })
+ })
+
+ describe('evaluationsSettled', () => {
+ it('is false while never-started and loading look identical on evaluationsLoading, then flips true on success', async () => {
+ // beforeEach's mount() has already dispatched loadEvaluations synchronously, so the
+ // fetch is in flight here: evaluationsLoading is true, but settling hasn't happened.
+ expect(logic.values.evaluationsSettled).toBe(false)
+
+ await expectLogic(logic).toDispatchActions(['loadEvaluationsSuccess'])
+
+ expect(logic.values.evaluationsSettled).toBe(true)
+ })
+
+ it('flips true on failure too, unlike evaluationsLoading which reads the same as never-started', async () => {
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+
+ await expectLogic(logic, () => {
+ logic.actions.loadEvaluations()
+ }).toDispatchActions(['loadEvaluationsFailure'])
+
+ expect(logic.values.evaluationsLoading).toBe(false)
+ expect(logic.values.evaluationsSettled).toBe(true)
+ })
+ })
+
+ describe('waitForEvaluationsSettled', () => {
+ it('waits for a pending fetch instead of resolving against an empty evaluations list', async () => {
+ let resolveRequest: (value: { results: EvaluationConfig[] }) => void = () => {}
+ useMocks({
+ get: {
+ '/api/projects/:teamId/evaluations/': () => new Promise((resolve) => (resolveRequest = resolve)),
+ },
+ })
+ logic.unmount()
+ logic = llmEvaluationsLogic()
+ logic.mount()
+
+ let resolved = false
+ const waiting = waitForEvaluationsSettled().then(() => {
+ resolved = true
+ })
+
+ await Promise.resolve()
+ expect(resolved).toBe(false)
+
+ resolveRequest({ results: [] })
+ await waiting
+ expect(resolved).toBe(true)
+ })
+
+ it('resolves immediately once evaluations have already settled', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationsSuccess'])
+
+ await expect(waitForEvaluationsSettled()).resolves.toBeUndefined()
+ })
+
+ it('waits again for a refetch instead of resolving against the polarity of the previous list', async () => {
+ await expectLogic(logic).toDispatchActions(['loadEvaluationsSuccess'])
+
+ let resolveRefetch: (value: { results: EvaluationConfig[] }) => void = () => {}
+ const refetch = new Promise<{ results: EvaluationConfig[] }>((resolve) => (resolveRefetch = resolve))
+ useMocks({ get: { '/api/projects/:teamId/evaluations/': () => refetch } })
+ logic.actions.loadEvaluations()
+
+ let resolved = false
+ const waiting = waitForEvaluationsSettled().then(() => {
+ resolved = true
+ })
+
+ await Promise.resolve()
+ expect(resolved).toBe(false)
+
+ resolveRefetch({ results: [] })
+ await waiting
+ expect(resolved).toBe(true)
+ })
+ })
})
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
index 8af4d5043c83..561ce0a03d95 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.ts
@@ -1,4 +1,16 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ getContext,
+ kea,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
import { loaders } from 'kea-loaders'
import { combineUrl, router, urlToAction } from 'kea-router'
@@ -20,6 +32,7 @@ import type { EvaluationDirectoryApi } from '../generated/api.schemas'
import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'
import { getUnhealthyProviderKey } from '../settings/providerKeyStateUtils'
import { evaluationErrorMessage } from './apiErrors'
+import { evaluationIsDetector } from './constants'
import { evaluationCanResolveModel } from './evaluationCapabilities'
import { listAllEvaluations, patchEvaluation } from './evaluationsApi'
import { EvaluationConfig } from './types'
@@ -59,6 +72,7 @@ export interface llmEvaluationsLogicValues {
dateTo: string | null
}
deletingDirectoryId: string | null
+ detectorEvaluationIds: string[]
directoryEditor: EvaluationDirectoryEditor | null
displayedEvaluations: EvaluationConfig[]
evaluationDirectories: EvaluationDirectoryApi[]
@@ -67,6 +81,7 @@ export interface llmEvaluationsLogicValues {
evaluationsFilter: string
evaluationsLoadFailed: boolean
evaluationsLoading: boolean
+ evaluationsSettled: boolean
filteredEvaluations: EvaluationConfig[]
movingEvaluationId: string | null
selectedDirectory: EvaluationDirectoryApi | null
@@ -201,6 +216,7 @@ export interface llmEvaluationsLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface llmEvaluationsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
+ detectorEvaluationIds: (evaluations: EvaluationConfig[]) => string[]
filteredEvaluations: (
evaluations: EvaluationConfig[],
evaluationsFilter: string,
@@ -329,6 +345,17 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
loadEvaluationsSuccess: () => false,
},
],
+ // Distinguishes "settled" from "never started" — evaluationsLoading is false in both,
+ // so a caller gating on that alone can't tell whether afterMount has fired yet. A refetch
+ // unsettles it again, so a caller can't read polarity from the previous list mid-refresh.
+ evaluationsSettled: [
+ false,
+ {
+ loadEvaluations: () => false,
+ loadEvaluationsSuccess: () => true,
+ loadEvaluationsFailure: () => true,
+ },
+ ],
evaluationsLoadFailed: [
false,
{
@@ -416,6 +443,10 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
try {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
+ // No team resolved yet (e.g. a hard load straight onto a clusters URL).
+ // Settle the flag anyway so callers gated on it — waitForEvaluationsSettled —
+ // don't wait forever for a fetch that was never going to happen.
+ actions.loadEvaluationsFailure()
return
}
@@ -552,6 +583,11 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
})),
selectors({
+ detectorEvaluationIds: [
+ (s) => [s.evaluations],
+ (evaluations: EvaluationConfig[]): string[] =>
+ evaluations.filter((evaluation) => evaluationIsDetector(evaluation)).map((evaluation) => evaluation.id),
+ ],
filteredEvaluations: [
(s) => [s.evaluations, s.evaluationsFilter, s.showDisabledEvaluations],
(evaluations: EvaluationConfig[], filter: string, showDisabledEvaluations: boolean) => {
@@ -695,3 +731,30 @@ export const llmEvaluationsLogic = kea<llmEvaluationsLogicType>([
actions.loadEvaluationDirectories()
}),
])
+
+/**
+ * Resolves once this logic's evaluations have settled — loaded or failed — never while the
+ * fetch is still in flight and never for a fetch that was never started. Callers that derive
+ * detector polarity (`detectorEvaluationIds`) from `evaluations` must await this before reading
+ * it: `evaluations` starts as `[]`, so a read before the fetch settles silently treats every
+ * evaluation, detectors included, as non-detector. Resolves immediately when already settled,
+ * so the common (already-loaded) path adds no latency. `evaluationsSettled` goes true on both
+ * `loadEvaluationsSuccess` and `loadEvaluationsFailure`, so a failed fetch still unblocks
+ * callers — with detectorEvaluationIds staying [], i.e. today's non-detector-aware verdicts —
+ * rather than waiting forever on a request that will never resolve. Requires
+ * `llmEvaluationsLogic` to already be mounted (e.g. via the caller's own `connect()`), which
+ * also guarantees `loadEvaluations` has already been dispatched by the time this runs.
+ */
+export async function waitForEvaluationsSettled(): Promise<void> {
+ if (llmEvaluationsLogic.values.evaluationsSettled) {
+ return
+ }
+ await new Promise<void>((resolve) => {
+ const unsubscribe = getContext().store.subscribe(() => {
+ if (llmEvaluationsLogic.values.evaluationsSettled) {
+ unsubscribe()
+ resolve()
+ }
+ })
+ })
+}
diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.ts
index 5fc8f8daf41f..35aa972762b8 100644
--- a/products/ai_observability/frontend/evaluations/types.ts
+++ b/products/ai_observability/frontend/evaluations/types.ts
@@ -34,6 +34,9 @@ export interface ModelConfiguration {
export interface EvaluationOutputConfig {
allows_na?: boolean
+ /** Whether a true result means the evaluation found a problem. Absent or false means a true
+ * result is a pass, which is what every evaluation stored before this field intends. */
+ true_is_failure?: boolean
}
/** Settle config for aggregate targets (trace, session). A missing `strategy` resolves per target:
diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.ts
index fafec91827ab..8a69d575fd09 100644
--- a/products/ai_observability/frontend/generated/api.schemas.ts
+++ b/products/ai_observability/frontend/generated/api.schemas.ts
@@ -894,7 +894,7 @@ export type EvaluationApiEvaluationConfig =
}
| {
/**
- * Hog source code. Must return true (pass), false (fail), or null for N/A.
+ * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string
@@ -905,11 +905,13 @@ export type EvaluationApiEvaluationConfig =
}
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem.
*/
export type EvaluationApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
+ /** Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ true_is_failure?: boolean
}
/**
@@ -982,7 +984,7 @@ export interface EvaluationApi {
* * `boolean` - Boolean (Pass/Fail)
* * `sentiment` - Sentiment */
output_type: OutputTypeEnumApi
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. */
output_config?: EvaluationApiOutputConfig
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationConditionApi[]
@@ -1031,7 +1033,7 @@ export type PatchedEvaluationApiEvaluationConfig =
}
| {
/**
- * Hog source code. Must return true (pass), false (fail), or null for N/A.
+ * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string
@@ -1042,11 +1044,13 @@ export type PatchedEvaluationApiEvaluationConfig =
}
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem.
*/
export type PatchedEvaluationApiOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean
+ /** Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ true_is_failure?: boolean
}
/**
@@ -1119,7 +1123,7 @@ export interface PatchedEvaluationApi {
* * `boolean` - Boolean (Pass/Fail)
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnumApi
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. */
output_config?: PatchedEvaluationApiOutputConfig
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationConditionApi[]
@@ -1165,7 +1169,7 @@ export interface TestHogTargetConfigApi {
export interface TestHogRequestApi {
/**
- * Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.
+ * Hog source code to test. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string
@@ -1213,7 +1217,7 @@ export interface TestHogResultItemApi {
/** First 200 characters of output from the sampled unit. */
output_preview: string
/**
- * True = pass, False = fail, null = N/A or error.
+ * Raw boolean result, or null when the evaluation returns N/A or raises an error.
* @nullable
*/
result: boolean | null
diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.ts
index 666320791114..ecbcb034a390 100644
--- a/products/ai_observability/frontend/generated/api.zod.ts
+++ b/products/ai_observability/frontend/generated/api.zod.ts
@@ -260,6 +260,7 @@ export const evaluationsCreateBodyNameMax = 400
export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsCreateBodyOutputConfigAllowsNaDefault = false
+export const evaluationsCreateBodyOutputConfigTrueIsFailureDefault = false
export const evaluationsCreateBodyConditionsItemIdMax = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -307,7 +308,9 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
source: zod
.string()
.min(1)
- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
+ .describe(
+ 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
}),
zod.object({
source: zod
@@ -334,9 +337,17 @@ export const EvaluationsCreateBody = /* @__PURE__ */ zod
.boolean()
.default(evaluationsCreateBodyOutputConfigAllowsNaDefault)
.describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: zod
+ .boolean()
+ .default(evaluationsCreateBodyOutputConfigTrueIsFailureDefault)
+ .describe(
+ 'Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ ),
})
.optional()
- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),
+ .describe(
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem."
+ ),
conditions: zod
.array(
zod
@@ -457,6 +468,7 @@ export const evaluationsUpdateBodyNameMax = 400
export const evaluationsUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsUpdateBodyOutputConfigAllowsNaDefault = false
+export const evaluationsUpdateBodyOutputConfigTrueIsFailureDefault = false
export const evaluationsUpdateBodyConditionsItemIdMax = 100
export const evaluationsUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -504,7 +516,9 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
source: zod
.string()
.min(1)
- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
+ .describe(
+ 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
}),
zod.object({
source: zod
@@ -531,9 +545,17 @@ export const EvaluationsUpdateBody = /* @__PURE__ */ zod
.boolean()
.default(evaluationsUpdateBodyOutputConfigAllowsNaDefault)
.describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: zod
+ .boolean()
+ .default(evaluationsUpdateBodyOutputConfigTrueIsFailureDefault)
+ .describe(
+ 'Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ ),
})
.optional()
- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),
+ .describe(
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem."
+ ),
conditions: zod
.array(
zod
@@ -654,6 +676,7 @@ export const evaluationsPartialUpdateBodyNameMax = 400
export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault = false
+export const evaluationsPartialUpdateBodyOutputConfigTrueIsFailureDefault = false
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -702,7 +725,9 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
source: zod
.string()
.min(1)
- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
+ .describe(
+ 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
}),
zod.object({
source: zod
@@ -730,9 +755,17 @@ export const EvaluationsPartialUpdateBody = /* @__PURE__ */ zod
.boolean()
.default(evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault)
.describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: zod
+ .boolean()
+ .default(evaluationsPartialUpdateBodyOutputConfigTrueIsFailureDefault)
+ .describe(
+ 'Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ ),
})
.optional()
- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),
+ .describe(
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem."
+ ),
conditions: zod
.array(
zod
@@ -870,7 +903,9 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({
source: zod
.string()
.min(1)
- .describe('Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N\/A.'),
+ .describe(
+ 'Hog source code to test. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
sample_count: zod
.number()
.min(1)
diff --git a/products/ai_observability/frontend/utils.ts b/products/ai_observability/frontend/utils.ts
index 459888554bfb..ced5141272f7 100644
--- a/products/ai_observability/frontend/utils.ts
+++ b/products/ai_observability/frontend/utils.ts
@@ -10,7 +10,7 @@ import { hogql } from '~/queries/utils'
import type { SpanAggregation } from './aiObservabilityTraceDataLogic'
import {
EVALUATION_NOT_SKIPPED_HOGQL,
- EVALUATION_PASSED_HOGQL,
+ EVALUATION_RESULT_TRUE_HOGQL,
EVALUATION_RUNS_QUERY_LIMIT,
} from './evaluations/constants'
import type { EvaluationOutputType, EvaluationRun, EvaluationType } from './evaluations/types'
@@ -1296,7 +1296,7 @@ export async function queryEvaluationRuns(params: {
export interface EvaluationRunsStats {
total: number
applicable: number
- passed: number
+ trueCount: number
}
// Counts every matching run server-side. queryEvaluationRuns caps its fetch at
@@ -1322,7 +1322,7 @@ export async function queryEvaluationRunsStats(params: {
SELECT
count() as total,
countIf(properties.$ai_evaluation_result IS NOT NULL AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as applicable,
- countIf(${hogql.raw(EVALUATION_PASSED_HOGQL)} AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as passed
+ countIf(${hogql.raw(EVALUATION_RESULT_TRUE_HOGQL)} AND ${hogql.raw(EVALUATION_NOT_SKIPPED_HOGQL)}) as true_count
FROM events
WHERE
event = '$ai_evaluation'
@@ -1338,12 +1338,12 @@ export async function queryEvaluationRunsStats(params: {
const row = response.results?.[0]
if (!row) {
- return { total: 0, applicable: 0, passed: 0 }
+ return { total: 0, applicable: 0, trueCount: 0 }
}
return {
total: Number(row[0]) || 0,
applicable: Number(row[1]) || 0,
- passed: Number(row[2]) || 0,
+ trueCount: Number(row[2]) || 0,
}
}
diff --git a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2 b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
index ab504b0a92ef..188239be955b 100644
--- a/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
+++ b/products/ai_observability/skills/creating-online-evaluations/references/evaluation-payload.md.j2
@@ -12,7 +12,7 @@ schemas below are rendered from the backend Pydantic models at build time, so th
| `evaluation_type` | yes | `"hog"`, `"llm_judge"`, or `"sentiment"`. |
| `evaluation_config` | yes | Shape depends on `evaluation_type` (below). |
| `output_type` | yes | `"boolean"` for `hog`/`llm_judge`; `"sentiment"` for `sentiment`. |
-| `output_config` | no | `{ "allows_na": bool }` for boolean; `{}` for sentiment. |
+| `output_config` | no | `{ "allows_na": bool, "true_is_failure": bool }` for boolean; `{}` for sentiment. |
| `model_configuration` | llm_judge only | Provider + model; key ID optional. Rejected on `hog`/`sentiment`. |
| `target` | no | `"generation"` (default), `"trace"`, or `"session"`. Sentiment supports only `"generation"`. |
| `target_config` | trace/session only | Settle config discriminated on `strategy` (below); defaults to a 30-minute fixed window for `trace`, and to a 1-hour inactivity window for `session`. |
@@ -81,6 +81,8 @@ Valid `(evaluation_type, output_type)` pairs: `(hog, boolean)`, `(llm_judge, boo
```
`allows_na: true` lets the evaluator return N/A (skip) in addition to pass/fail.
+`true_is_failure: true` treats a raw `true` result as a failure and a raw `false` result as a pass.
+Leave it `false` for the default mapping.
### sentiment output
diff --git a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
index eaef6f08884f..4d342a2312fa 100644
--- a/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
+++ b/products/ai_observability/skills/exploring-llm-evaluations/SKILL.md
@@ -60,21 +60,23 @@ All `llma-evaluation-*` tools are defined in `products/ai_observability/mcp/tool
Every run of an evaluation emits an `$ai_evaluation` event. Key properties:
-| Property | Meaning |
-| ---------------------------- | --------------------------------------------------------------- |
-| `$ai_evaluation_id` | UUID of the evaluation config |
-| `$ai_evaluation_name` | Human-readable name |
-| `$ai_target_event_id` | UUID of the `$ai_generation` event being scored |
-| `$ai_trace_id` | Parent trace ID (for jumping to the trace UI) |
-| `$ai_evaluation_result_type` | Result kind: `boolean` or `sentiment` |
-| `$ai_evaluation_result` | For boolean evaluations: `true` = pass, `false` = fail |
-| `$ai_evaluation_reasoning` | Free-text explanation (set by the LLM judge or Hog code) |
-| `$ai_evaluation_applicable` | `false` when the evaluator decided the generation is N/A |
-| `$ai_sentiment_label` | For sentiment evaluations: `positive`, `neutral`, or `negative` |
-| `$ai_sentiment_score` | Confidence score for the winning sentiment label |
+| Property | Meaning |
+| ---------------------------- | -------------------------------------------------------------------------------- |
+| `$ai_evaluation_id` | UUID of the evaluation config |
+| `$ai_evaluation_name` | Human-readable name |
+| `$ai_target_event_id` | UUID of the `$ai_generation` event being scored |
+| `$ai_trace_id` | Parent trace ID (for jumping to the trace UI) |
+| `$ai_evaluation_result_type` | Result kind: `boolean` or `sentiment` |
+| `$ai_evaluation_result` | Raw boolean result. Use the evaluation's output config to map it to pass or fail |
+| `$ai_evaluation_reasoning` | Free-text explanation (set by the LLM judge or Hog code) |
+| `$ai_evaluation_applicable` | `false` when the evaluator decided the generation is N/A |
+| `$ai_sentiment_label` | For sentiment evaluations: `positive`, `neutral`, or `negative` |
+| `$ai_sentiment_score` | Confidence score for the winning sentiment label |
When `$ai_evaluation_applicable = false`, the run counts as N/A regardless of `$ai_evaluation_result`.
For evaluations that don't support N/A, this property may be `null` — treat null as "applicable".
+For boolean evaluations, `output_config.true_is_failure: false` maps `true` to pass and `false` to fail.
+Set it to `true` for detector-style evaluations where `true` means the evaluator found a problem.
## Workflow: investigate why an evaluation is failing
@@ -270,6 +272,7 @@ LLM judges require organisation AI data processing approval. Hog evaluators do n
| Add an LLM-judge evaluator | `llma-evaluation-create` with `evaluation_type: "llm_judge"`, `evaluation_config.prompt`, and a `model_configuration` |
| Tweak the source or prompt | `llma-evaluation-update` (edits `evaluation_config.source` for Hog, `evaluation_config.prompt` for LLM judge) |
| Toggle N/A handling | `llma-evaluation-update` with `output_config.allows_na` |
+| Set failure polarity | `llma-evaluation-update` with `output_config.true_is_failure` |
| Disable temporarily | `llma-evaluation-update` with `enabled: false` |
| Remove | `llma-evaluation-delete` (soft-delete via PATCH `{deleted: true}`) |
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 97ee5bb5c938..70760e9c60e2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -33009,7 +33009,7 @@ export namespace Schemas {
prompt: string;
} | {
/**
- * Hog source code. Must return true (pass), false (fail), or null for N/A.
+ * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string;
@@ -33019,11 +33019,13 @@ export namespace Schemas {
};
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem.
*/
export type EvaluationOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
+ /** Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ true_is_failure?: boolean;
};
/**
@@ -33237,7 +33239,7 @@ export namespace Schemas {
* * `boolean` - Boolean (Pass/Fail)
* * `sentiment` - Sentiment */
output_type: OutputTypeEnum;
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. */
output_config?: EvaluationOutputConfig;
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationCondition[];
@@ -62753,7 +62755,7 @@ export namespace Schemas {
prompt: string;
} | {
/**
- * Hog source code. Must return true (pass), false (fail), or null for N/A.
+ * Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string;
@@ -62763,11 +62765,13 @@ export namespace Schemas {
};
/**
- * Output config. For 'boolean' output_type: {allows_na} to permit N/A results.
+ * Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem.
*/
export type PatchedEvaluationOutputConfig = {
/** Whether the evaluation can return N/A for non-applicable generations. */
allows_na?: boolean;
+ /** Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail. */
+ true_is_failure?: boolean;
};
/**
@@ -62838,7 +62842,7 @@ export namespace Schemas {
* * `boolean` - Boolean (Pass/Fail)
* * `sentiment` - Sentiment */
output_type?: OutputTypeEnum;
- /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results. */
+ /** Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem. */
output_config?: PatchedEvaluationOutputConfig;
/** Trigger conditions that filter which events are evaluated. OR between condition sets, AND within each. Each set is {id, rollout_percentage, properties[]} — `rollout_percentage` (0-100, defaults to 100) is the sampling field the dispatcher reads. */
conditions?: EvaluationCondition[];
@@ -86886,7 +86890,7 @@ export namespace Schemas {
export interface TestHogRequest {
/**
- * Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.
+ * Hog source code to test. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.
* @minLength 1
*/
source: string;
@@ -86934,7 +86938,7 @@ export namespace Schemas {
/** First 200 characters of output from the sampled unit. */
output_preview: string;
/**
- * True = pass, False = fail, null = N/A or error.
+ * Raw boolean result, or null when the evaluation returns N/A or raises an error.
* @nullable
*/
result: boolean | null;
diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.ts
index 5b75d73b0928..d73232360995 100644
--- a/services/mcp/src/generated/ai_observability/api.ts
+++ b/services/mcp/src/generated/ai_observability/api.ts
@@ -562,6 +562,7 @@ export const evaluationsCreateBodyNameMax = 400
export const evaluationsCreateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsCreateBodyOutputConfigAllowsNaDefault = false
+export const evaluationsCreateBodyOutputConfigTrueIsFailureDefault = false
export const evaluationsCreateBodyConditionsItemIdMax = 100
export const evaluationsCreateBodyConditionsItemRolloutPercentageDefault = 100
@@ -609,7 +610,9 @@ export const EvaluationsCreateBody = () => zod
source: zod
.string()
.min(1)
- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
+ .describe(
+ 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
}),
zod.object({
source: zod
@@ -636,9 +639,17 @@ export const EvaluationsCreateBody = () => zod
.boolean()
.default(evaluationsCreateBodyOutputConfigAllowsNaDefault)
.describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: zod
+ .boolean()
+ .default(evaluationsCreateBodyOutputConfigTrueIsFailureDefault)
+ .describe(
+ 'Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ ),
})
.optional()
- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),
+ .describe(
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem."
+ ),
conditions: zod
.array(
zod
@@ -777,6 +788,7 @@ export const evaluationsPartialUpdateBodyNameMax = 400
export const evaluationsPartialUpdateBodyEvaluationConfigThreeSourceDefault = `user_messages`
export const evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault = false
+export const evaluationsPartialUpdateBodyOutputConfigTrueIsFailureDefault = false
export const evaluationsPartialUpdateBodyConditionsItemIdMax = 100
export const evaluationsPartialUpdateBodyConditionsItemRolloutPercentageDefault = 100
@@ -825,7 +837,9 @@ export const EvaluationsPartialUpdateBody = () => zod
source: zod
.string()
.min(1)
- .describe('Hog source code. Must return true (pass), false (fail), or null for N\/A.'),
+ .describe(
+ 'Hog source code. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
}),
zod.object({
source: zod
@@ -853,9 +867,17 @@ export const EvaluationsPartialUpdateBody = () => zod
.boolean()
.default(evaluationsPartialUpdateBodyOutputConfigAllowsNaDefault)
.describe('Whether the evaluation can return N\/A for non-applicable generations.'),
+ true_is_failure: zod
+ .boolean()
+ .default(evaluationsPartialUpdateBodyOutputConfigTrueIsFailureDefault)
+ .describe(
+ 'Whether a true result means the evaluation found a problem. False (the default) suits pass\/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.'
+ ),
})
.optional()
- .describe("Output config. For 'boolean' output_type: {allows_na} to permit N\/A results."),
+ .describe(
+ "Output config. For 'boolean' output_type: {allows_na} to permit N\/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem."
+ ),
conditions: zod
.array(
zod
@@ -1012,7 +1034,9 @@ export const EvaluationsTestHogCreateBody = () => zod.object({
source: zod
.string()
.min(1)
- .describe('Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N\/A.'),
+ .describe(
+ 'Hog source code to test. Must return true or false, or null for N\/A. Output settings determine which boolean counts as a failure.'
+ ),
sample_count: zod
.number()
.min(1)
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
index b0c4e6283648..b0a6ad9eec86 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-create.json
@@ -75,7 +75,7 @@
{
"properties": {
"source": {
- "description": "Hog source code. Must return true (pass), false (fail), or null for N/A.",
+ "description": "Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
"type": "string"
}
@@ -163,12 +163,17 @@
"type": "string"
},
"output_config": {
- "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results.",
+ "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem.",
"properties": {
"allows_na": {
"default": false,
"description": "Whether the evaluation can return N/A for non-applicable generations.",
"type": "boolean"
+ },
+ "true_is_failure": {
+ "default": false,
+ "description": "Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
+ "type": "boolean"
}
},
"type": "object"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
index 9f9acc0f3ab9..44f5ccaee00d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-test-hog.json
@@ -25,7 +25,7 @@
"type": "number"
},
"source": {
- "description": "Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.",
+ "description": "Hog source code to test. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
"type": "string"
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
index f23350b88904..6c897ddb84d7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-evaluation-update.json
@@ -74,7 +74,7 @@
{
"properties": {
"source": {
- "description": "Hog source code. Must return true (pass), false (fail), or null for N/A.",
+ "description": "Hog source code. Must return true or false, or null for N/A. Output settings determine which boolean counts as a failure.",
"minLength": 1,
"type": "string"
}
@@ -166,12 +166,17 @@
"type": "string"
},
"output_config": {
- "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results.",
+ "description": "Output config. For 'boolean' output_type: {allows_na} to permit N/A results, and {true_is_failure} to declare that a true result means the evaluation found a problem.",
"properties": {
"allows_na": {
"default": false,
"description": "Whether the evaluation can return N/A for non-applicable generations.",
"type": "boolean"
+ },
+ "true_is_failure": {
+ "default": false,
+ "description": "Whether a true result means the evaluation found a problem. False (the default) suits pass/fail evaluations, where a true result satisfied the criteria. Set it to true for detector-style evaluations, so a true result is counted and labeled as a fail.",
+ "type": "boolean"
}
},
"type": "object"