:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): make Hog eval test paths target-aware (#72905)
Radu Raicea1a801d648cba
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex 7d492f11e7d3..e4266d558012 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -39,6 +39,7 @@ from posthog.temporal.ai_observability.evaluation_errors import (require_user_error_spec,status_reason_detail_for_terminal_user_error,)+from posthog.temporal.ai_observability.evaluation_event_io import extract_event_iofrom posthog.temporal.ai_observability.evaluation_hog import (build_hog_event_global,execute_hog_eval_bytecode,@@ -57,6 +58,7 @@ from posthog.temporal.ai_observability.evaluation_workflow_activities import (emit_internal_telemetry_activity,fetch_evaluation_activity,)+from posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.metrics import increment_emit_event_outcome, increment_errorsfrom posthog.temporal.ai_observability.run_evaluation import (WorkflowResult,@@ -67,6 +69,7 @@ from posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.utils import close_db_connectionsfrom products.ai_observability.backend.models.evaluation_configs import (+ EVALUATION_TEST_LOOKBACK_DAYS,TRACE_EVAL_DEFAULT_WINDOW_SECONDS,TRACE_EVAL_MAX_WINDOW_SECONDS,)@@ -172,13 +175,9 @@ def _count_trace_events(team: Team, trace_id: str, date_from: datetime, date_to:return int(result.results[0][0])-def fetch_trace_for_evaluation(team_id: int, trace_id: str, window_start: datetime) -> TraceFetchOutcome:- """Fetch the full trace from ClickHouse, with a cheap count preflight so degenerate- traces are skipped before pulling their payload."""- team = Team.objects.get(id=team_id)- date_from = window_start - TRACE_EVENTS_LOOKBACK- date_to = datetime.now(UTC)-+def _fetch_trace(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> TraceFetchOutcome:+ """Fetch a single full trace from ClickHouse over an explicit window, with a cheap count+ preflight so degenerate traces are skipped before pulling their payload."""event_count = _count_trace_events(team, trace_id, date_from, date_to)if event_count == 0:return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=0)@@ -199,6 +198,183 @@ def fetch_trace_for_evaluation(team_id: int, trace_id: str, window_start: datetireturn TraceFetchOutcome(trace=response.results[0], skip_reason=None, event_count=event_count)+def fetch_trace_for_evaluation(team_id: int, trace_id: str, window_start: datetime) -> TraceFetchOutcome:+ """Fetch the full trace for an online evaluation run, looking back from the workflow start."""+ team = Team.objects.get(id=team_id)+ date_from = window_start - TRACE_EVENTS_LOOKBACK+ date_to = datetime.now(UTC)+ return _fetch_trace(team, trace_id, date_from, date_to)+++@dataclass+class TraceHogTestResult:+ """One trace's outcome from `run_hog_eval_over_recent_traces`, shaped for the editor test+ endpoint and Max's authoring tool rather than for online emission."""++ trace_id: str+ verdict: bool | None+ reasoning: str+ error: str | None+ input_preview: str+ output_preview: str+++@dataclass(frozen=True)+class TraceHogTestSample:+ trace_id: str+ trigger_timestamp: datetime+++def _coerce_trace_test_timestamp(value: Any) -> datetime:+ if isinstance(value, datetime):+ timestamp = value+ elif isinstance(value, str):+ timestamp = datetime.fromisoformat(value.replace("Z", "+00:00"))+ else:+ raise TypeError(f"Unexpected trace sample timestamp type: {type(value).__name__}")++ return timestamp if timestamp.tzinfo is not None else timestamp.replace(tzinfo=UTC)+++def _sample_recent_traces(+ team: Team,+ condition_filter: ast.Expr | None,+ sample_count: int,+ date_from: datetime,+ date_to: datetime,+) -> list[TraceHogTestSample]:+ """Pick the most recent distinct trace ids whose *triggering* generation matches the+ evaluation's conditions — mirroring the online scheduler, which starts a trace-eval run+ from the first matching `$ai_generation`. Historical previews use that event timestamp as+ the closest available proxy for the workflow start time."""+ where_exprs: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["event"]),+ right=ast.Constant(value=["$ai_generation"]),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.NotEq,+ left=ast.Field(chain=["trace_id"]),+ right=ast.Constant(value=""),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=date_from),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=date_to),+ ),+ ]+ if condition_filter is not None:+ where_exprs.append(condition_filter)++ query = ast.SelectQuery(+ select=[+ ast.Field(chain=["trace_id"]),+ ast.Alias(alias="trigger_timestamp", expr=ast.Call(name="min", args=[ast.Field(chain=["timestamp"])])),+ ast.Alias(alias="latest", expr=ast.Call(name="max", args=[ast.Field(chain=["timestamp"])])),+ ],+ select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "ai_events"]), alias="ai_events"),+ where=ast.Placeholder(expr=ast.Field(chain=["where_clause"])),+ group_by=[ast.Field(chain=["trace_id"])],+ order_by=[ast.OrderExpr(expr=ast.Field(chain=["latest"]), order="DESC")],+ limit=ast.Constant(value=sample_count),+ )+ response = query_ai_events(+ query=query,+ placeholders={"where_clause": ast.And(exprs=where_exprs)},+ team=team,+ query_type="EvaluationTestHogTraceSample",+ fall_back_to_events=True,+ )+ return [+ TraceHogTestSample(trace_id=str(row[0]), trigger_timestamp=_coerce_trace_test_timestamp(row[1]))+ for row in (response.results or [])+ ]+++def _trace_io_preview(trace: LLMTrace) -> tuple[str, str]:+ """First non-empty input and last non-empty output across the trace's events, for a compact+ preview. The Hog body still sees the full trace globals; this is only for display."""+ input_preview = ""+ output_preview = ""+ for event in trace.events or []:+ input_raw, output_raw = extract_event_io(event.event, event.properties)+ if not input_preview:+ input_preview = extract_text_from_messages(input_raw)[:200]+ output_text = extract_text_from_messages(output_raw)[:200]+ if output_text:+ output_preview = output_text+ return input_preview, output_preview+++def run_hog_eval_over_recent_traces(+ *,+ team: Team,+ bytecode: list[Any],+ condition_filter: ast.Expr | None,+ sample_count: int,+ allows_na: bool,+ window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ lookback_days: int = EVALUATION_TEST_LOOKBACK_DAYS,+) -> list[TraceHogTestResult]:+ """Sample recent traces matching the conditions and run trace-level Hog bytecode against each.++ Shared by the editor `test_hog` endpoint and Max's authoring tool so a trace-target eval is+ previewed the same way it runs online — whole trace, trace globals — instead of against a+ single generation.+ """+ now = datetime.now(UTC)+ window = timedelta(seconds=window_seconds)+ # Only sample triggers whose full aggregation window has elapsed.+ sample_date_to = now - window+ sample_date_from = sample_date_to - timedelta(days=lookback_days)+ trace_samples = _sample_recent_traces(+ team,+ condition_filter,+ sample_count,+ sample_date_from,+ sample_date_to,+ )++ results: list[TraceHogTestResult] = []+ for sample in trace_samples:+ trace_date_from = sample.trigger_timestamp - TRACE_EVENTS_LOOKBACK+ trace_date_to = sample.trigger_timestamp + window+ outcome = _fetch_trace(team, sample.trace_id, trace_date_from, trace_date_to)+ if outcome.skip_reason or outcome.trace is None:+ results.append(+ TraceHogTestResult(+ trace_id=sample.trace_id,+ verdict=None,+ reasoning="",+ error=_SKIP_REASONING.get(outcome.skip_reason or "trace_not_found", "Evaluation skipped."),+ input_preview="",+ output_preview="",+ )+ )+ continue++ globals_dict = build_trace_hog_globals(outcome.trace, sample.trace_id, bytecode=bytecode)+ result = execute_hog_eval_bytecode(bytecode, globals_dict, allows_na=allows_na)+ input_preview, output_preview = _trace_io_preview(outcome.trace)+ results.append(+ TraceHogTestResult(+ trace_id=sample.trace_id,+ verdict=result["verdict"],+ reasoning=result["reasoning"],+ error=result["error"],+ input_preview=input_preview,+ output_preview=output_preview,+ )+ )+ return results++def _build_trace_skip_result(allows_na: bool, skip_reason: str) -> EvaluationActivityResult:"""Mirror of `_build_errored_trace_result` for trace-level skips — no LLM call is made,so model/provider are omitted and downstream cost attribution stays clean."""diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex cd1e22b6f8fb..8c8839cfcbf5 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -1,13 +1,16 @@import jsonimport uuid-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyimport pytest+from freezegun import freeze_timefrom unittest.mock import MagicMock, patchfrom posthog.schema import LLMTrace, LLMTraceEvent+from posthog.hogql import ast+from posthog.cdp.validation import compile_hogfrom posthog.models import Organization, Team@@ -21,12 +24,15 @@ from .evaluation_types import EvaluationActivityResultfrom .run_trace_evaluation import (JUDGE_TRACE_MAX_CHARS,MAX_TRACE_EVAL_EVENTS,+ TRACE_EVENTS_LOOKBACK,EmitTraceEvaluationEventInputs,ExecuteTraceEvaluationInputs,RunTraceEvaluationInputs,RunTraceEvaluationWorkflow,TraceFetchOutcome,+ TraceHogTestSample,_build_trace_skip_result,+ _sample_recent_traces,build_trace_hog_globals,build_trace_system_prompt,emit_trace_evaluation_event_activity,@@ -34,6 +40,7 @@ from .run_trace_evaluation import (execute_trace_llm_judge_activity,fetch_trace_for_evaluation,format_trace_for_judge,+ run_hog_eval_over_recent_traces,)FROZEN_NOW = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)@@ -288,6 +295,100 @@ class TestFetchTraceForEvaluation:assert outcome.trace is trace+class TestRunHogEvalOverRecentTraces:+ @patch("posthog.temporal.ai_observability.run_trace_evaluation.query_ai_events")+ def test_samples_the_first_matching_generation_timestamp(self, mock_query):+ mock_query.return_value = MagicMock(results=[["trace-123", "2024-01-01T10:00:00Z", FROZEN_NOW]])++ samples = _sample_recent_traces(+ MagicMock(spec=Team),+ condition_filter=None,+ sample_count=1,+ date_from=FROZEN_NOW - timedelta(days=7),+ date_to=FROZEN_NOW,+ )++ trigger_timestamp_select = mock_query.call_args.kwargs["query"].select[1]+ assert trigger_timestamp_select.alias == "trigger_timestamp"+ assert trigger_timestamp_select.expr.name == "min"+ assert samples == [+ TraceHogTestSample(+ trace_id="trace-123",+ trigger_timestamp=datetime(2024, 1, 1, 10, 0, tzinfo=UTC),+ )+ ]++ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")+ def test_rewrites_promoted_ai_property_conditions(self, mock_execute_query):+ mock_execute_query.return_value = MagicMock(results=[["trace-123", FROZEN_NOW, FROZEN_NOW]])+ condition_filter = ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["properties", "$ai_input"]),+ right=ast.Constant(value="hello"),+ )++ _sample_recent_traces(+ MagicMock(spec=Team),+ condition_filter=condition_filter,+ sample_count=1,+ date_from=FROZEN_NOW - timedelta(days=7),+ date_to=FROZEN_NOW,+ )++ where_clause = mock_execute_query.call_args.kwargs["placeholders"]["where_clause"]+ rewritten_condition = where_clause.exprs[-1]+ assert rewritten_condition.left.chain == ["input"]++ @freeze_time(FROZEN_NOW)+ def test_uses_the_sampled_trigger_and_configured_aggregation_window(self):+ team = MagicMock(spec=Team)+ trigger_timestamp = FROZEN_NOW - timedelta(hours=2)+ trace = create_trace(+ [+ create_trace_event("$ai_generation", **{"$ai_input": "first", "$ai_output": "one"}),+ create_trace_event("$ai_generation", **{"$ai_input": "second", "$ai_output": "two"}),+ ]+ )+ bytecode = compile_hog(+ "return target.type == 'trace' and length(evaluation_events) == 2",+ "destination",+ )++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation._sample_recent_traces",+ return_value=[TraceHogTestSample(trace_id="trace-123", trigger_timestamp=trigger_timestamp)],+ ) as mock_sample:+ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation._fetch_trace",+ return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=2),+ ) as mock_fetch:+ results = run_hog_eval_over_recent_traces(+ team=team,+ bytecode=bytecode,+ condition_filter=None,+ sample_count=1,+ allows_na=False,+ window_seconds=120,+ )++ mock_sample.assert_called_once_with(+ team,+ None,+ 1,+ FROZEN_NOW - timedelta(seconds=120, days=7),+ FROZEN_NOW - timedelta(seconds=120),+ )+ mock_fetch.assert_called_once_with(+ team,+ "trace-123",+ trigger_timestamp - TRACE_EVENTS_LOOKBACK,+ trigger_timestamp + timedelta(seconds=120),+ )+ assert results[0].verdict is True+ assert results[0].input_preview == "first"+ assert results[0].output_preview == "two"++class TestExecuteTraceLLMJudgeActivity:@pytest.mark.django_db(transaction=True)def test_judges_full_trace_transcript(self, setup_data, active_key_config):diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.pyindex afd9eda4945c..ab56b8552462 100644--- a/products/ai_observability/backend/api/evaluations.py+++ b/products/ai_observability/backend/api/evaluations.py@@ -30,11 +30,13 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.model_resolution import active_key_fallbackfrom posthog.temporal.ai_observability.run_evaluation import extract_event_io, run_hog_eval+from posthog.temporal.ai_observability.run_trace_evaluation import run_hog_eval_over_recent_tracesfrom ..hog import compile_ai_observability_hogfrom ..llm import DEFAULT_MODEL_BY_PROVIDERfrom ..models.evaluation_config import EvaluationConfigfrom ..models.evaluation_configs import (+ EVALUATION_TEST_LOOKBACK_DAYS,TRACE_EVAL_DEFAULT_WINDOW_SECONDS,TRACE_EVAL_MAX_WINDOW_SECONDS,TRACE_EVAL_MIN_WINDOW_SECONDS,@@ -614,6 +616,16 @@ class EvaluationListSerializer(EvaluationSerializer):read_only_fields = [f for f in EvaluationSerializer.Meta.read_only_fields if f != "created_by"]+class TestHogTargetConfigSerializer(serializers.Serializer):+ window_seconds = serializers.IntegerField(+ required=False,+ default=TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ min_value=TRACE_EVAL_MIN_WINDOW_SECONDS,+ max_value=TRACE_EVAL_MAX_WINDOW_SECONDS,+ help_text="Aggregation window for trace samples, in seconds.",+ )++class TestHogRequestSerializer(serializers.Serializer):source = serializers.CharField(required=True,@@ -636,13 +648,39 @@ class TestHogRequestSerializer(serializers.Serializer):default=list,help_text="Optional trigger conditions to filter which events are sampled.",)+ target = serializers.ChoiceField(+ choices=EvaluationTarget.choices,+ required=False,+ default=EvaluationTarget.GENERATION,+ help_text=(+ "What the evaluation runs against: 'generation' samples individual generations, "+ "'trace' samples whole traces and runs against trace-level globals — matching how the "+ "evaluation runs online."+ ),+ )+ target_config = TestHogTargetConfigSerializer(+ required=False,+ default=dict,+ help_text=(+ "Target-specific preview settings. For a trace target, set window_seconds between "+ f"{TRACE_EVAL_MIN_WINDOW_SECONDS} and {TRACE_EVAL_MAX_WINDOW_SECONDS}."+ ),+ )class TestHogResultItemSerializer(serializers.Serializer):- event_uuid = serializers.CharField(help_text="UUID of the $ai_generation event.")- trace_id = serializers.CharField(allow_null=True, required=False, help_text="Trace ID if available.")- input_preview = serializers.CharField(help_text="First 200 chars of the generation input.")- output_preview = serializers.CharField(help_text="First 200 chars of the generation output.")+ sample_id = serializers.CharField(help_text="Stable identifier for the sampled generation or trace.")+ sample_type = serializers.ChoiceField(+ choices=EvaluationTarget.choices,+ help_text="Type of sampled unit: generation or trace.",+ )+ event_uuid = serializers.CharField(+ allow_null=True,+ help_text="UUID of the sampled $ai_generation event, or null for a trace sample.",+ )+ 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.")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.")@@ -655,6 +693,76 @@ class TestHogResponseSerializer(serializers.Serializer):)+def _test_hog_over_traces(+ *,+ request: Request,+ team: Team,+ bytecode: list[Any],+ condition_filter: ast.Expr | None,+ sample_count: int,+ allows_na: bool,+ conditions: list[dict[str, Any]],+ window_seconds: int,+) -> Response:+ """Trace-target variant of the `test_hog` action: sample recent whole traces and run the code+ against trace-level globals, so the editor preview matches how a trace eval runs online."""+ tag_queries(product=Product.LLM_ANALYTICS, feature=Feature.QUERY)+ try:+ trace_results = run_hog_eval_over_recent_traces(+ team=team,+ bytecode=bytecode,+ condition_filter=condition_filter,+ sample_count=sample_count,+ allows_na=allows_na,+ window_seconds=window_seconds,+ )+ except AIEventsUnavailableError:+ trace_results = []++ results = [+ {+ "sample_id": r.trace_id,+ "sample_type": EvaluationTarget.TRACE.value,+ "event_uuid": None,+ "trace_id": r.trace_id,+ "input_preview": r.input_preview,+ "output_preview": r.output_preview,+ "result": r.verdict,+ "reasoning": r.reasoning,+ "error": r.error,+ }+ for r in trace_results+ ]++ report_user_action(+ request.user,+ "llma evaluation hog code tested",+ {+ "sample_count": sample_count,+ "allows_na": allows_na,+ "condition_count": len(conditions),+ "result_count": len(results),+ "pass_count": sum(1 for r in results if r["result"] is True),+ "fail_count": sum(1 for r in results if r["result"] is False),+ "error_count": sum(1 for r in results if r["error"]),+ "na_count": sum(1 for r in results if r["result"] is None and not r["error"]),+ "no_events": not results,+ "target": EvaluationTarget.TRACE.value,+ },+ team=team,+ request=request,+ )++ if not results:+ return Response(+ {+ "results": [],+ "message": f"No recent AI traces found in the last {EVALUATION_TEST_LOOKBACK_DAYS} days",+ }+ )+ return Response({"results": results})++class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):scope_object = "evaluation"permission_classes = [IsAuthenticated, AccessControlPermission]@@ -855,6 +963,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbisample_count = serializer.validated_data["sample_count"]allows_na = serializer.validated_data["allows_na"]conditions = serializer.validated_data.get("conditions", [])+ target = serializer.validated_data["target"]+ target_config = serializer.validated_data["target_config"]try:bytecode = compile_ai_observability_hog(source, "destination")@@ -866,7 +976,31 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiteam = Team.objects.get(id=self.team_id)- # Build WHERE clause from trigger conditions (OR between condition sets, AND within each)+ # Build the trigger-condition filter once (OR between condition sets, AND within each).+ # Both targets reuse it — for traces it filters which triggering generation qualifies.+ condition_exprs: list[ast.Expr] = []+ for condition in conditions:+ props = condition.get("properties", [])+ if props:+ condition_exprs.append(property_to_expr(props, team))+ condition_filter: ast.Expr | None = None+ if len(condition_exprs) == 1:+ condition_filter = condition_exprs[0]+ elif condition_exprs:+ condition_filter = ast.Or(exprs=condition_exprs)++ if target == EvaluationTarget.TRACE.value:+ return _test_hog_over_traces(+ request=request,+ team=team,+ bytecode=bytecode,+ condition_filter=condition_filter,+ sample_count=sample_count,+ allows_na=allows_na,+ conditions=conditions,+ window_seconds=target_config.get("window_seconds", TRACE_EVAL_DEFAULT_WINDOW_SECONDS),+ )+where_exprs: list[ast.Expr] = [ast.CompareOperation(op=ast.CompareOperationOp.In,@@ -879,24 +1013,15 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiright=ast.ArithmeticOperation(op=ast.ArithmeticOperationOp.Sub,left=ast.Call(name="now", args=[]),- right=ast.Call(name="toIntervalDay", args=[ast.Constant(value=7)]),+ right=ast.Call(+ name="toIntervalDay",+ args=[ast.Constant(value=EVALUATION_TEST_LOOKBACK_DAYS)],+ ),),),]-- # Apply property filters from conditions- condition_exprs: list[ast.Expr] = []- for condition in conditions:- props = condition.get("properties", [])- if props:- expr = property_to_expr(props, team)- condition_exprs.append(expr)-- if condition_exprs:- if len(condition_exprs) == 1:- where_exprs.append(condition_exprs[0])- else:- where_exprs.append(ast.Or(exprs=condition_exprs))+ if condition_filter is not None:+ where_exprs.append(condition_filter)query = ast.SelectQuery(select=[@@ -941,11 +1066,17 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi"error_count": 0,"na_count": 0,"no_events": True,+ "target": target,},team=self.team,request=self.request,)- return Response({"results": [], "message": "No recent AI events found in the last 7 days"})+ return Response(+ {+ "results": [],+ "message": f"No recent AI events found in the last {EVALUATION_TEST_LOOKBACK_DAYS} days",+ }+ )results = []for row in query_results:@@ -973,6 +1104,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbiresults.append({+ "sample_id": event_uuid,+ "sample_type": EvaluationTarget.GENERATION.value,"event_uuid": event_uuid,"trace_id": properties.get("$ai_trace_id"),"input_preview": input_preview,@@ -995,6 +1128,8 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi"fail_count": sum(1 for r in results if r["result"] is False),"error_count": sum(1 for r in results if r["error"]),"na_count": sum(1 for r in results if r["result"] is None and not r["error"]),+ "no_events": False,+ "target": target,},team=self.team,request=self.request,diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 5d327e3f6392..9f0f0a5241a3 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -980,8 +980,9 @@ class TestTestHogEndpoint(APIBaseTest):columns=["uuid", "event", "properties", "distinct_id", "timestamp", *HEAVY_COLUMN_NAMES],)+ @patch("products.ai_observability.backend.api.evaluations.report_user_action")@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")- def test_test_hog_loads_ai_input_and_output(self, mock_query):+ def test_test_hog_loads_ai_input_and_output(self, mock_query, mock_report_user_action):mock_query.return_value = self._mock_hogql_response(2)response = self.client.post(@@ -999,6 +1000,8 @@ class TestTestHogEndpoint(APIBaseTest):self.assertEqual(len(results), 2)for r in results:self.assertIn("event_uuid", r)+ self.assertEqual(r["sample_id"], r["event_uuid"])+ self.assertEqual(r["sample_type"], "generation")self.assertIn("result", r)self.assertIn("reasoning", r)self.assertIn("error", r)@@ -1011,6 +1014,7 @@ class TestTestHogEndpoint(APIBaseTest):self.assertEqual(query.select_from.table.chain, ["posthog", "ai_events"])self.assertEqual(query.select[4].chain, ["timestamp"])self.assertEqual([field.chain for field in query.select[5:]], [[name] for name in HEAVY_COLUMN_NAMES])+ self.assertFalse(mock_report_user_action.call_args.args[2]["no_events"])def test_test_hog_compilation_error(self):response = self.client.post(@@ -1068,6 +1072,58 @@ class TestTestHogEndpoint(APIBaseTest):self.assertFalse(results[0]["result"])self.assertIsNone(results[0]["error"])+ @patch("products.ai_observability.backend.api.evaluations.run_hog_eval_over_recent_traces")+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")+ def test_test_hog_trace_target_evaluates_whole_traces(self, mock_query, mock_run_over_traces):+ # A trace-target request must run the trace path (whole-trace globals), not the+ # generation query — the gap this endpoint used to have.+ from posthog.temporal.ai_observability.run_trace_evaluation import TraceHogTestResult++ mock_run_over_traces.return_value = [+ TraceHogTestResult(+ trace_id="trace-1",+ verdict=True,+ reasoning="ok",+ error=None,+ input_preview="hello",+ output_preview="world",+ )+ ]++ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/test_hog/",+ {+ "source": "return target.type == 'trace'",+ "target": "trace",+ "target_config": {"window_seconds": 120},+ },+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(mock_run_over_traces.call_args.kwargs["window_seconds"], 120)+ # The generation query path must not run for a trace target.+ mock_query.assert_not_called()+ results = response.json()["results"]+ self.assertEqual(len(results), 1)+ self.assertEqual(results[0]["sample_id"], "trace-1")+ self.assertEqual(results[0]["sample_type"], "trace")+ self.assertIsNone(results[0]["event_uuid"])+ self.assertEqual(results[0]["trace_id"], "trace-1")+ self.assertTrue(results[0]["result"])++ @patch("products.ai_observability.backend.api.evaluations.run_hog_eval_over_recent_traces")+ def test_test_hog_trace_target_no_traces(self, mock_run_over_traces):+ mock_run_over_traces.return_value = []++ response = self.client.post(+ f"/api/environments/{self.team.id}/evaluations/test_hog/",+ {"source": "return true", "target": "trace"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["results"], [])+ self.assertIn("traces", response.json()["message"])+class TestEnableBlockingWhenKeyRequired(APIBaseTest):"""Enabling a keyless llm_judge eval must mirror the runtime provider-key gate: a config withdiff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.pyindex d180525971b1..3ea963b385ac 100644--- a/products/ai_observability/backend/models/evaluation_configs.py+++ b/products/ai_observability/backend/models/evaluation_configs.py@@ -73,6 +73,7 @@ class SentimentOutputConfig(BaseModel):TRACE_EVAL_DEFAULT_WINDOW_SECONDS = 30 * 60TRACE_EVAL_MIN_WINDOW_SECONDS = 10TRACE_EVAL_MAX_WINDOW_SECONDS = 2 * 60 * 60+EVALUATION_TEST_LOOKBACK_DAYS = 7class TraceTargetConfig(BaseModel):diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.pyindex 56a59908df78..49870b74f239 100644--- a/products/ai_observability/backend/tools/run_hog_eval.py+++ b/products/ai_observability/backend/tools/run_hog_eval.py@@ -1,4 +1,4 @@-from typing import Any+from typing import Any, Literalfrom pydantic import BaseModel, Field@@ -11,19 +11,30 @@ from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_propefrom posthog.sync import database_sync_to_asyncfrom products.ai_observability.backend.hog import compile_ai_observability_hog+from products.ai_observability.backend.models.evaluation_configs import (+ EVALUATION_TEST_LOOKBACK_DAYS,+ TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ TRACE_EVAL_MAX_WINDOW_SECONDS,+ TRACE_EVAL_MIN_WINDOW_SECONDS,+)from ee.hogai.tool import MaxTool-TOOL_DESCRIPTION = """Test Hog evaluation code against sample events from the last 7 days.+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 event.+Returns compilation errors if the code is invalid, or pass/fail/error results for each sample.++Set `target` to match how the evaluation will run: `generation` samples individual generations,+`trace` samples whole traces and exposes trace-level globals. For traces, set `window_seconds`+to the evaluation's aggregation window so the preview matches online behavior.Write new evaluations using these globals:-- `evaluation_events` (array): the sampled event. Each item has `uuid`, `event`, `timestamp`,+- `evaluation_events` (array): the events under evaluation — one generation for a generation+ target, all events of the trace for a trace target. Each item has `uuid`, `event`, `timestamp`,serialized `input` and `output`, readable `input_text` and `output_text`, and `properties`without large input, output, and tool payloads.-- `target` (object): the sampled generation's `type`, `id`, `total_cost_usd`, and- `total_latency_seconds`.+- `target` (object): the sampled unit's `type` ('generation' or 'trace'), `id`, `total_cost_usd`,+ and `total_latency_seconds`.Saved evaluations can still use the generation-only compatibility globals `input`, `output`,`properties`, and `event`, but do not use them in new source that should also work for traces.@@ -39,7 +50,17 @@ class RunHogEvalTestArgs(BaseModel):default=3,ge=1,le=5,- description="Number of recent events to test against (1-5)",+ description="Number of recent samples to test against (1-5)",+ )+ target: Literal["generation", "trace"] = Field(+ default="generation",+ description="What to sample: 'generation' (individual generations) or 'trace' (whole traces)",+ )+ window_seconds: int = Field(+ default=TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ ge=TRACE_EVAL_MIN_WINDOW_SECONDS,+ le=TRACE_EVAL_MAX_WINDOW_SECONDS,+ description="Aggregation window for trace samples, in seconds",)@@ -51,7 +72,13 @@ class RunHogEvalTestTool(MaxTool):def get_required_resource_access(self):return [("llm_analytics", "viewer")]- async def _arun_impl(self, source: str, sample_count: int = 3) -> tuple[str, Any]:+ async def _arun_impl(+ self,+ source: str,+ sample_count: int = 3,+ target: Literal["generation", "trace"] = "generation",+ window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS,+ ) -> tuple[str, Any]:from posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.run_evaluation import run_hog_eval@@ -62,6 +89,9 @@ class RunHogEvalTestTool(MaxTool):team = self._team+ if target == "trace":+ return await self._run_over_traces(bytecode, sample_count, window_seconds)+# Read from ai_events with native heavy columns so the Hog body still# sees `event.properties.$ai_input` etc. Falls back to the events table# when ai_events returns nothing (data beyond the retention window).@@ -88,7 +118,10 @@ class RunHogEvalTestTool(MaxTool):right=ast.ArithmeticOperation(op=ast.ArithmeticOperationOp.Sub,left=ast.Call(name="now", args=[]),- right=ast.Call(name="toIntervalDay", args=[ast.Constant(value=7)]),+ right=ast.Call(+ name="toIntervalDay",+ args=[ast.Constant(value=EVALUATION_TEST_LOOKBACK_DAYS)],+ ),),),]@@ -106,7 +139,8 @@ class RunHogEvalTestTool(MaxTool):)if not response.results:return (- "No recent AI events found in the last 7 days. Ingest some $ai_generation or $ai_metric events first.",+ f"No recent AI events found in the last {EVALUATION_TEST_LOOKBACK_DAYS} days. "+ "Ingest some $ai_generation or $ai_metric events first.",None,)@@ -192,3 +226,44 @@ class RunHogEvalTestTool(MaxTool):lines.append("")return ("\n".join(lines), None)++ async def _run_over_traces(self, bytecode: list[Any], sample_count: int, window_seconds: int) -> tuple[str, Any]:+ from posthog.temporal.ai_observability.run_trace_evaluation import run_hog_eval_over_recent_traces++ trace_results = await database_sync_to_async(run_hog_eval_over_recent_traces)(+ team=self._team,+ bytecode=bytecode,+ condition_filter=None,+ sample_count=sample_count,+ allows_na=True,+ window_seconds=window_seconds,+ )+ if not trace_results:+ return (+ f"No recent AI traces found in the last {EVALUATION_TEST_LOOKBACK_DAYS} days. "+ "Ingest some $ai_generation events first.",+ None,+ )++ lines: list[str] = [f"Sampled {len(trace_results)} trace(s). Ran against trace-level globals.", ""]+ for r in trace_results:+ if r.error:+ verdict_str = "ERROR"+ elif r.verdict is True:+ verdict_str = "PASS"+ elif r.verdict is False:+ verdict_str = "FAIL"+ else:+ verdict_str = "N/A"++ lines.append(f"Trace {r.trace_id}:")+ lines.append(f" Input: {r.input_preview}")+ lines.append(f" Output: {r.output_preview}")+ lines.append(f" Result: {verdict_str}")+ if r.reasoning:+ lines.append(f" Reasoning: {r.reasoning}")+ if r.error:+ lines.append(f" Error: {r.error}")+ lines.append("")++ return ("\n".join(lines), None)diff --git a/products/ai_observability/backend/tools/test_run_hog_eval.py b/products/ai_observability/backend/tools/test_run_hog_eval.pyindex 9f427d14098d..68b50b4031c8 100644--- a/products/ai_observability/backend/tools/test_run_hog_eval.py+++ b/products/ai_observability/backend/tools/test_run_hog_eval.py@@ -1,15 +1,17 @@import jsonimport uuid+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom asgiref.sync import async_to_syncfrom parameterized import parameterized+from pydantic import ValidationErrorfrom posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES-from products.ai_observability.backend.tools.run_hog_eval import RunHogEvalTestTool+from products.ai_observability.backend.tools.run_hog_eval import RunHogEvalTestArgs, RunHogEvalTestToolEVENT_TIMESTAMP = "2026-07-20T12:34:56Z"@@ -43,6 +45,11 @@ def _run_tool(tool, **kwargs):return async_to_sync(tool._arun_impl)(**kwargs)+def test_run_hog_eval_args_reject_unknown_target():+ with pytest.raises(ValidationError):+ RunHogEvalTestArgs(source="return true", target="traces")++class TestRunHogEvalTestTool(BaseTest):def _make_tool(self):return RunHogEvalTestTool(team=self.team, user=self.user)@@ -210,6 +217,35 @@ class TestRunHogEvalTestTool(BaseTest):assert "Result: PASS" in result, f"expected PASS 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):+ from posthog.temporal.ai_observability.run_trace_evaluation import TraceHogTestResult++ mock_run_over_traces.return_value = [+ TraceHogTestResult(+ trace_id="trace-1",+ verdict=True,+ reasoning="looks good",+ error=None,+ input_preview="hello",+ output_preview="world",+ )+ ]++ tool = self._make_tool()+ result, artifact = _run_tool(+ tool,+ source="return target.type == 'trace';",+ sample_count=2,+ target="trace",+ window_seconds=120,+ )++ 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+@patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")def test_query_targets_ai_events(self, mock_query):"""The constructed SelectQuery must target `posthog.ai_events` — otherwisediff --git a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsxindex f4a25177c44f..7aa96899e10f 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationCodeEditor.tsx@@ -9,9 +9,10 @@ import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'import { useOpenAi } from '~/scenes/max/useOpenAi'import { urls } from '~/scenes/urls'+import type { TestHogResultItemApi } from '../../generated/api.schemas'import { HOG_EVAL_EXAMPLES } from '../hogEvalExamples'import { llmEvaluationLogic } from '../llmEvaluationLogic'-import type { EvaluationTarget, HogTestResult } from '../types'+import type { EvaluationTarget } from '../types'const GLOBAL_NAME_CODE_CLASS = 'font-medium text-sm text-primary bg-fill-highlight-100 px-1.5 py-0.5 rounded'const PROPERTY_NAME_CODE_CLASS = 'font-medium text-xs text-primary bg-fill-highlight-100 px-1 py-0.5 rounded'@@ -217,7 +218,7 @@ function HogTestResultsPanel(): JSX.Element | null {Clear</LemonButton></div>- <LemonTable<HogTestResult>+ <LemonTable<TestHogResultItemApi>columns={[{title: 'Result',@@ -266,19 +267,25 @@ function HogTestResultsPanel(): JSX.Element | null {title: '',key: 'link',width: 32,- render: (_, row) =>- row.trace_id ? (- <Tooltip title="View generation">+ render: (_, row) => {+ if (!row.trace_id) {+ return null+ }+ const isTrace = row.sample_type === 'trace'+ return (+ <Tooltip title={isTrace ? 'View trace' : 'View generation'}><Link- to={urls.aiObservabilityTrace(row.trace_id, {- event: row.event_uuid,- })}+ to={urls.aiObservabilityTrace(+ row.trace_id,+ isTrace || !row.event_uuid ? undefined : { event: row.event_uuid }+ )}target="_blank"><IconExternal className="text-muted text-base" /></Link></Tooltip>- ) : null,+ )+ },},]}expandable={{@@ -291,7 +298,7 @@ function HogTestResultsPanel(): JSX.Element | null {}}dataSource={hogTestResults ?? []}loading={hogTestResultsLoading}- rowKey="event_uuid"+ rowKey="sample_id"size="small"/></div>@@ -334,7 +341,7 @@ export function EvaluationCodeEditor(): JSX.Element {<Tooltiptitle={evaluation.target === 'trace'- ? 'Preview this code against up to 5 recent generations. Online runs evaluate the whole trace.'+ ? 'Compile and run your code against up to 5 recent traces, the same way it runs online': 'Compile and run your code against up to 5 recent generations matching your trigger filters'}>@@ -343,7 +350,7 @@ export function EvaluationCodeEditor(): JSX.Element {size="xsmall"loading={hogTestResultsLoading}disabled={!source.trim()}- onClick={testHogOnSample}+ onClick={() => testHogOnSample()}data-attr="llma-evaluation-test-hog">Test on samplediff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.tsindex 444deb93735c..975013348a49 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts@@ -4,6 +4,7 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import type { TestHogResponseApi } from '../generated/api.schemas'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import { EVALUATION_SUMMARY_MAX_RUNS } from './constants'import { evaluationReportLogic } from './evaluationReportLogic'@@ -1281,6 +1282,96 @@ return result`,})})+ describe('Hog sample testing', () => {+ it('sends the trace aggregation window and clears completed results when it changes', async () => {+ let requestBody: Record<string, unknown> | undefined+ useMocks({+ post: {+ '/api/projects/:teamId/evaluations/test_hog/': async ({ request }) => {+ requestBody = (await request.json()) as Record<string, unknown>+ return {+ results: [+ {+ sample_id: 'trace-1',+ sample_type: 'trace',+ event_uuid: null,+ trace_id: 'trace-1',+ input_preview: 'hello',+ output_preview: 'world',+ result: true,+ reasoning: null,+ error: null,+ },+ ],+ }+ },+ },+ })+ logic = llmEvaluationLogic({ evaluationId: 'new' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.setEvaluationType('hog')+ logic.actions.setEvaluationTarget('trace')+ logic.actions.setTraceWindowSeconds(120)+ logic.actions.testHogOnSample()++ await expectLogic(logic)+ .toDispatchActions(['testHogOnSampleSuccess'])+ .toMatchValues({+ hogTestResults: [expect.objectContaining({ sample_id: 'trace-1', sample_type: 'trace' })],+ })+ expect(requestBody).toMatchObject({+ target: 'trace',+ target_config: { window_seconds: 120 },+ })++ logic.actions.setTraceWindowSeconds(240)+ await expectLogic(logic).toMatchValues({ hogTestResults: null })+ })++ it('does not restore results from a request whose target changed in flight', async () => {+ let resolveRequest: (value: TestHogResponseApi) => void = () => {}+ const pendingResponse = new Promise<TestHogResponseApi>((resolve) => {+ resolveRequest = resolve+ })+ useMocks({+ post: {+ '/api/projects/:teamId/evaluations/test_hog/': () => pendingResponse,+ },+ })+ logic = llmEvaluationLogic({ evaluationId: 'new' })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadEvaluationSuccess'])++ logic.actions.setEvaluationType('hog')+ logic.actions.testHogOnSample()+ await expectLogic(logic).toMatchValues({ hogTestResultsLoading: true })++ logic.actions.setEvaluationTarget('trace')+ await expectLogic(logic).toMatchValues({ hogTestResults: null })+ resolveRequest({+ results: [+ {+ sample_id: 'generation-1',+ sample_type: 'generation',+ event_uuid: 'generation-1',+ trace_id: 'trace-1',+ input_preview: 'hello',+ output_preview: 'world',+ result: true,+ reasoning: '',+ error: null,+ },+ ],+ })++ await expectLogic(logic)+ .toDispatchActions(['testHogOnSampleSuccess'])+ .toMatchValues({ hogTestResults: null })+ })+ })+describe('saveEvaluation report persistence', () => {it('does not create an evaluation when the report threshold is invalid', async () => {let evaluationCreateCount = 0diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.tsindex 44913f6e641c..b90222ed14d0 100644--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.ts@@ -16,6 +16,7 @@ import {evaluationsTestHogCreate,llmAnalyticsEvaluationSummaryCreate,} from '../generated/api'+import type { TestHogRequestApi, TestHogResultItemApi } from '../generated/api.schemas'import { parsePlaygroundProviderKeyId } from '../ModelPicker'import { LLMProviderKey, llmProviderKeysLogic } from '../settings/llmProviderKeysLogic'import type { EvaluationConfig as TeamEvaluationConfig } from '../settings/llmProviderKeysLogic'@@ -44,7 +45,6 @@ import type {EvaluationType,HogEvaluation,LLMJudgeEvaluation,- HogTestResult,ModelConfiguration,SentimentEvaluation,} from './types'@@ -128,6 +128,24 @@ function filterEvaluationRuns(runs: EvaluationRun[], filter: EvaluationSummaryFireturn completedRuns.filter((r) => r.sentiment_label?.toLowerCase() === filter)}+function buildHogTestRequest(evaluation: HogEvaluation): TestHogRequestApi {+ const request: TestHogRequestApi = {+ source: evaluation.evaluation_config.source,+ sample_count: 5,+ allows_na: evaluation.output_config?.allows_na ?? false,+ conditions: evaluation.conditions+ .filter((condition) => condition.properties && condition.properties.length > 0)+ .map((condition) => ({ properties: condition.properties })),+ target: evaluation.target,+ }+ if (evaluation.target === 'trace') {+ request.target_config = {+ window_seconds: evaluation.target_config.window_seconds ?? DEFAULT_TRACE_WINDOW_SECONDS,+ }+ }+ return request+}+export interface LLMEvaluationLogicProps {evaluationId: stringtemplateKey?: EvaluationTemplateKey@@ -158,7 +176,7 @@ export interface llmEvaluationLogicValues {filteredEvaluationRuns: EvaluationRun[]formValid: booleanhasUnsavedChanges: boolean- hogTestResults: HogTestResult[] | null+ hogTestResults: TestHogResultItemApi[] | nullhogTestResultsLoading: booleanisForceRefresh: booleanisNewEvaluation: boolean@@ -320,7 +338,7 @@ export interface llmEvaluationLogicActions {setTriggerConditions: (conditions: EvaluationConditionSet[]) => {conditions: EvaluationConditionSet[]}- testHogOnSample: () => any+ testHogOnSample: (_?: void) => voidtestHogOnSampleFailure: (error: string,errorObject?: any@@ -329,11 +347,11 @@ export interface llmEvaluationLogicActions {errorObject?: any}testHogOnSampleSuccess: (- hogTestResults: HogTestResult[] | null,- payload?: any+ hogTestResults: TestHogResultItemApi[] | null,+ payload?: void) => {- hogTestResults: HogTestResult[] | null- payload?: any+ hogTestResults: TestHogResultItemApi[] | null+ payload?: void}toggleSummaryExpanded: () => {value: true@@ -462,9 +480,9 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([loaders(({ props, values }) => ({hogTestResults: [- null as HogTestResult[] | null,+ null as TestHogResultItemApi[] | null,{- testHogOnSample: async (): Promise<HogTestResult[] | null> => {+ testHogOnSample: async (_?: void, breakpoint?: () => void): Promise<TestHogResultItemApi[] | null> => {const teamId = teamLogic.values.currentTeamIdif (!teamId) {return null@@ -473,25 +491,24 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([if (!evaluation || evaluation.evaluation_type !== 'hog') {return null}++ const request = buildHogTestRequest(evaluation)+ const requestFingerprint = JSON.stringify(request)+ let results: TestHogResultItemApi[]try {- const conditions = evaluation.conditions- .filter((c) => c.properties && c.properties.length > 0)- .map((c) => ({ properties: c.properties }))- const response = await evaluationsTestHogCreate(teamId.toString(), {- source: evaluation.evaluation_config.source,- sample_count: 5,- allows_na: evaluation.output_config?.allows_na ?? false,- conditions,- })- return response.results.map((result) => ({+ const response = await evaluationsTestHogCreate(teamId.toString(), request)+ results = response.results.map((result) => ({...result,reasoning: result.reasoning ?? '',}))} catch (e: unknown) {const message = e instanceof Error ? e.message : typeof e === 'string' ? e : 'Unknown error'- return [+ results = [{- event_uuid: 'error',+ sample_id: 'error',+ sample_type: evaluation.target,+ event_uuid: null,+ trace_id: null,input_preview: '',output_preview: '',result: null,@@ -500,6 +517,17 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([},]}++ breakpoint?.()+ const currentEvaluation = values.evaluation+ if (+ !currentEvaluation ||+ currentEvaluation.evaluation_type !== 'hog' ||+ JSON.stringify(buildHogTestRequest(currentEvaluation)) !== requestFingerprint+ ) {+ return null+ }+ return results},},],@@ -657,7 +685,12 @@ export const llmEvaluationLogic = kea<llmEvaluationLogicType>([],hogTestResults: {clearHogTestResults: () => null,+ setAllowsNA: () => null,+ setEvaluationTarget: () => null,+ setEvaluationType: () => null,setHogSource: () => null,+ setTraceWindowSeconds: () => null,+ setTriggerConditions: () => null,},selectedModel: ['' as string,diff --git a/products/ai_observability/frontend/evaluations/types.ts b/products/ai_observability/frontend/evaluations/types.tsindex 7d9eb2e5555b..7001811131fc 100644--- a/products/ai_observability/frontend/evaluations/types.ts+++ b/products/ai_observability/frontend/evaluations/types.ts@@ -125,16 +125,6 @@ export interface EvaluationRun {status: 'completed' | 'failed' | 'running'}-export interface HogTestResult {- event_uuid: string- trace_id?: string | null- input_preview: string- output_preview: string- result: boolean | null- reasoning: string- error: string | null-}-export type EvaluationReportFrequency = 'scheduled' | 'every_n'export interface EvaluationReportDeliveryTarget {diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex ff6fc2e31d67..c13c2d56bee4 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -700,6 +700,15 @@ export interface PatchedEvaluationApi {export type TestHogRequestApiConditionsItem = { [key: string]: unknown }+export interface TestHogTargetConfigApi {+ /**+ * Aggregation window for trace samples, in seconds.+ * @minimum 10+ * @maximum 7200+ */+ window_seconds?: number+}+export interface TestHogRequestApi {/*** Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.@@ -716,19 +725,36 @@ export interface TestHogRequestApi {allows_na?: boolean/** Optional trigger conditions to filter which events are sampled. */conditions?: TestHogRequestApiConditionsItem[]+ /** What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ target?: EvaluationTargetEnumApi+ /** Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200. */+ target_config?: TestHogTargetConfigApi}export interface TestHogResultItemApi {- /** UUID of the $ai_generation event. */- event_uuid: string+ /** Stable identifier for the sampled generation or trace. */+ sample_id: string+ /** Type of sampled unit: generation or trace.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ sample_type: EvaluationTargetEnumApi+ /**+ * UUID of the sampled $ai_generation event, or null for a trace sample.+ * @nullable+ */+ event_uuid: string | null/*** Trace ID if available.* @nullable*/- trace_id?: string | null- /** First 200 chars of the generation input. */+ trace_id: string | null+ /** First 200 characters of input from the sampled unit. */input_preview: string- /** First 200 chars of the generation output. */+ /** First 200 characters of output from the sampled unit. */output_preview: string/*** True = pass, False = fail, null = N/A or error.diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex c7705b1b53cd..495da05845ec 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -580,6 +580,10 @@ export const evaluationsTestHogCreateBodySampleCountDefault = 5export const evaluationsTestHogCreateBodySampleCountMax = 10export const evaluationsTestHogCreateBodyAllowsNaDefault = false+export const evaluationsTestHogCreateBodyTargetDefault = `generation`+export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault = 1800+export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMin = 10+export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax = 7200export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({source: zod@@ -600,6 +604,24 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({.array(zod.record(zod.string(), zod.unknown())).optional().describe('Optional trigger conditions to filter which events are sampled.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace')+ .default(evaluationsTestHogCreateBodyTargetDefault)+ .describe(+ "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.\n\n\* `generation` - Generation\n\* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax)+ .default(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault)+ .describe('Aggregation window for trace samples, in seconds.'),+ })+ .optional()+ .describe('Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200.'),})/**diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex 1d7e938d9741..0238cf4bebf5 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -433,9 +433,11 @@ tools:idempotent: falsetitle: Test Hog evaluation codedescription: >- Test Hog evaluation source code against a sample of recent $ai_generation events without saving. Returns- per-event results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code- before creating or updating a 'hog' type evaluation.+ Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the+ evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and+ runs against trace-level globals. For trace previews, pass target_config.window_seconds to match the saved+ evaluation's aggregation window. Returns per-sample results (pass/fail/N/A), reasoning, and input/output+ previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.llma-evaluation-update:operation: evaluations_partial_updateenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 526a5b8b2ad9..bf8cd7d691c2 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5517,7 +5517,7 @@"requires_ai_consent": true},"llma-evaluation-test-hog": {- "description": "Test Hog evaluation source code against a sample of recent $ai_generation events without saving. Returns per-event results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",+ "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.","category": "AI observability","feature": "llm_analytics","summary": "Test Hog evaluation code",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex d8195bae3f15..3bf0b2e19b61 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -3701,7 +3701,7 @@}},"evaluation-test-hog": {- "description": "Test Hog evaluation code against recent $ai_generation events without persisting results. Compiles the provided Hog source code and runs it against a sample of recent events (up to 10 from the last 7 days). Returns per-event results with input/output previews, pass/fail verdicts, and any errors. Use this to validate Hog evaluation logic before enabling it.",+ "description": "Test Hog evaluation code against recent data without persisting results. Compiles the provided Hog source code and runs it against a sample from the last 7 days — set target to 'generation' to sample individual $ai_generation events or 'trace' to sample whole traces and run against trace-level globals. Returns per-sample results with input/output previews, pass/fail verdicts, and any errors. Use this to validate Hog evaluation logic before enabling it.","category": "AI observability","feature": "llm_analytics","summary": "Dry-run Hog evaluation code against sample events.",@@ -5826,7 +5826,7 @@"requires_ai_consent": true},"llma-evaluation-test-hog": {- "description": "Test Hog evaluation source code against a sample of recent $ai_generation events without saving. Returns per-event results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.",+ "description": "Test Hog evaluation source code against a sample of recent data without saving. Set target to match how the evaluation runs: 'generation' samples individual $ai_generation events, 'trace' samples whole traces and runs against trace-level globals. For trace previews, pass target_config.window_seconds to match the saved evaluation's aggregation window. Returns per-sample results (pass/fail/N/A), reasoning, and input/output previews. Use this to validate Hog code before creating or updating a 'hog' type evaluation.","category": "AI observability","feature": "llm_analytics","summary": "Test Hog evaluation code",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex fbbda7c51a6f..dc6e4f3ae972 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -309,7 +309,7 @@}},"evaluation-test-hog": {- "description": "Test Hog evaluation code against recent $ai_generation events without persisting results. Compiles the provided Hog source code and runs it against a sample of recent events (up to 10 from the last 7 days). Returns per-event results with input/output previews, pass/fail verdicts, and any errors. Use this to validate Hog evaluation logic before enabling it.",+ "description": "Test Hog evaluation code against recent data without persisting results. Compiles the provided Hog source code and runs it against a sample from the last 7 days — set target to 'generation' to sample individual $ai_generation events or 'trace' to sample whole traces and run against trace-level globals. Returns per-sample results with input/output previews, pass/fail verdicts, and any errors. Use this to validate Hog evaluation logic before enabling it.","category": "AI observability","feature": "llm_analytics","summary": "Dry-run Hog evaluation code against sample events.",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a29a1505c716..2ad70bcfdd1f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -68066,6 +68066,15 @@ export namespace Schemas {export type TestHogRequestConditionsItem = { [key: string]: unknown };+ export interface TestHogTargetConfig {+ /**+ * Aggregation window for trace samples, in seconds.+ * @minimum 10+ * @maximum 7200+ */+ window_seconds?: number;+ }+export interface TestHogRequest {/*** Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.@@ -68082,19 +68091,36 @@ export namespace Schemas {allows_na?: boolean;/** Optional trigger conditions to filter which events are sampled. */conditions?: TestHogRequestConditionsItem[];+ /** What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ target?: EvaluationTargetEnum;+ /** Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200. */+ target_config?: TestHogTargetConfig;}export interface TestHogResultItem {- /** UUID of the $ai_generation event. */- event_uuid: string;+ /** Stable identifier for the sampled generation or trace. */+ sample_id: string;+ /** Type of sampled unit: generation or trace.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ sample_type: EvaluationTargetEnum;+ /**+ * UUID of the sampled $ai_generation event, or null for a trace sample.+ * @nullable+ */+ event_uuid: string | null;/*** Trace ID if available.* @nullable*/- trace_id?: string | null;- /** First 200 chars of the generation input. */+ trace_id: string | null;+ /** First 200 characters of input from the sampled unit. */input_preview: string;- /** First 200 chars of the generation output. */+ /** First 200 characters of output from the sampled unit. */output_preview: string;/*** True = pass, False = fail, null = N/A or error.diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex b2f5f3730bca..ee680994d2f5 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -488,6 +488,10 @@ export const evaluationsTestHogCreateBodySampleCountDefault = 5export const evaluationsTestHogCreateBodySampleCountMax = 10export const evaluationsTestHogCreateBodyAllowsNaDefault = false+export const evaluationsTestHogCreateBodyTargetDefault = `generation`+export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault = 1800+export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMin = 10+export const evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax = 7200export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({source: zod@@ -508,6 +512,24 @@ export const EvaluationsTestHogCreateBody = /* @__PURE__ */ zod.object({.array(zod.record(zod.string(), zod.unknown())).optional().describe('Optional trigger conditions to filter which events are sampled.'),+ target: zod+ .enum(['generation', 'trace'])+ .describe('\* `generation` - Generation\n\* `trace` - Trace')+ .default(evaluationsTestHogCreateBodyTargetDefault)+ .describe(+ "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.\n\n\* `generation` - Generation\n\* `trace` - Trace"+ ),+ target_config: zod+ .object({+ window_seconds: zod+ .number()+ .min(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMin)+ .max(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsMax)+ .default(evaluationsTestHogCreateBodyTargetConfigOneWindowSecondsDefault)+ .describe('Aggregation window for trace samples, in seconds.'),+ })+ .optional()+ .describe('Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200.'),})/**diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex e6554c360de3..baffa900e4ba 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -650,6 +650,12 @@ const llmaEvaluationTestHog = (): ToolBase<typeof LlmaEvaluationTestHogSchema, Sif (params.conditions !== undefined) {body['conditions'] = params.conditions}+ if (params.target !== undefined) {+ body['target'] = params.target+ }+ if (params.target_config !== undefined) {+ body['target_config'] = params.target_config+ }const result = await context.api.request<Schemas.TestHogResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/evaluations/test_hog/`,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.jsonindex db34062ad8bb..ed53768a1eb1 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@@ -28,6 +28,25 @@"description": "Hog source code to test. Must return a boolean (true = pass, false = fail) or null for N/A.","minLength": 1,"type": "string"+ },+ "target": {+ "default": "generation",+ "description": "What the evaluation runs against: 'generation' samples individual generations, 'trace' samples whole traces and runs against trace-level globals — matching how the evaluation runs online.\n\n* `generation` - Generation\n* `trace` - Trace",+ "enum": ["generation", "trace"],+ "type": "string"+ },+ "target_config": {+ "description": "Target-specific preview settings. For a trace target, set window_seconds between 10 and 7200.",+ "properties": {+ "window_seconds": {+ "default": 1800,+ "description": "Aggregation window for trace samples, in seconds.",+ "maximum": 7200,+ "minimum": 10,+ "type": "number"+ }+ },+ "type": "object"}},"required": ["source"],