: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): skip trace evals whose transcript has nothing to grade (#104903)
posthog[bot]1b8e82c16e66
diff --git a/docs/internal/ai-observability-judge-inputs.md b/docs/internal/ai-observability-judge-inputs.mdindex b82963635f73..e844d3647a68 100644--- a/docs/internal/ai-observability-judge-inputs.md+++ b/docs/internal/ai-observability-judge-inputs.md@@ -12,6 +12,11 @@ They do not change with the selected judge model.## Trace and session formatting+Trace evaluations skip the LLM judge when a trace has no child events and no readable trace-level input or output.+Message role headers, empty OpenTelemetry parts, and whitespace-only message bodies do not count as readable content.+Tool calls embedded in output content count as readable content, even when the adjacent text is whitespace.+Root-only traces with readable state still reach the judge, and Hog evaluations can grade root-only traces from their metadata.+Trace and session evaluations first render a text representation with message truncation and line sampling disabled.This attempt stops when the text exceeds the budget, before assembling the complete oversized transcript in memory.If the complete rendered transcript fits its budget, the evaluation uses that text.diff --git a/posthog/temporal/ai_observability/message_utils.py b/posthog/temporal/ai_observability/message_utils.pyindex 73cea019ca02..177216c8c255 100644--- a/posthog/temporal/ai_observability/message_utils.py+++ b/posthog/temporal/ai_observability/message_utils.py@@ -3,6 +3,8 @@import jsonfrom typing import Any, Union+from products.ai_observability.backend.text_repr.formatters.otel_parts import flatten_parts_message+def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:"""@@ -33,7 +35,7 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:formatted_parts = []for msg in messages:if isinstance(msg, dict):- for flattened in _flatten_parts_message(msg):+ for flattened in flatten_parts_message(msg):rendered_msg = _render_message(flattened)if rendered_msg is not None:formatted_parts.append(rendered_msg)@@ -45,121 +47,10 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:# Handle single dict message — render it the same way as a one-element# list so that role prefixes and tool_call_id correlation are surfaced# consistently regardless of the wrapper shape.- rendered_messages = [_render_message(flattened) for flattened in _flatten_parts_message(messages)]+ rendered_messages = [_render_message(flattened) for flattened in flatten_parts_message(messages)]return "\n".join(rendered for rendered in rendered_messages if rendered is not None)-def _flatten_parts_message(msg: dict) -> list[dict]:- """Convert an OTel GenAI semconv parts-shaped message into flat chat message(s).-- `/i/v0/ai/otel` stores `gen_ai.input.messages` / `gen_ai.output.messages` verbatim,- so messages arrive as `{"role": ..., "parts": [...]}` with the text inside typed- parts instead of a flat `content` key. `_render_message` only reads `content` and- `tool_calls`, which made these messages render as a bare `role:` line and left the- LLM judge grading an empty conversation.-- Mirrors the trace UI's `otel.yaml` normalizer recipe so the judge sees the same- conversation the trace view renders:- - `{"type": "text", "content": ...}` parts join into the message's `content`- - `{"type": "tool_call", "id", "name", "arguments"}` parts become `tool_calls`,- and so do `server_tool_call` parts (provider-executed tools like web_search),- with the polymorphic `server_tool_call` payload as the arguments- - each `{"type": "tool_call_response", "id", "response"}` part becomes its own- follow-up `role: "tool"` message so the existing `tool[<id>]:` correlation applies.- `response` is the field the GenAI semconv schema requires. The spec's own example- showed `result` for its first ten months, so producers that followed the example- are in the wild too, and all of `response`/`result`/`server_tool_call_response`- are read in that order, which also folds `server_tool_call_response` parts in- - `reasoning` parts become follow-up `role: "thinking"` messages- - `blob`/`uri`/`file` parts become bracketed text markers (`[image]`,- `[image: <uri>]`, `[file: <id>]`). The trace view renders image blobs and uris- as actual images; the judge gets markers instead because base64 payloads are- token noise to an LLM- - `compaction` parts become follow-up messages carrying the compacted summary,- or a `[conversation compacted]` marker when the summary is absent-- Like the recipe, this only applies to dicts with a string `role` alongside the- `parts` list, so a structured-output payload that happens to have its own `parts`- array still reaches the JSON-stringify fallback in `_render_message`.-- Messages that already carry `content` or `tool_calls`, or have no `parts` list,- pass through unchanged.- """- parts = msg.get("parts")- if not isinstance(msg.get("role"), str) or not isinstance(parts, list):- return [msg]- if msg.get("content") or msg.get("tool_calls"):- return [msg]-- text_chunks: list[str] = []- tool_calls: list[dict] = []- followups: list[dict] = []- for part in parts:- if not isinstance(part, dict):- continue- part_type = part.get("type")- if part_type == "text":- content = part.get("content")- if isinstance(content, str) and content:- text_chunks.append(content)- elif part_type in ("tool_call", "server_tool_call"):- arguments_key = "arguments" if part_type == "tool_call" else "server_tool_call"- tool_calls.append(- {- "id": part.get("id"),- "function": {"name": part.get("name", ""), "arguments": part.get(arguments_key, "")},- }- )- elif part_type in ("tool_call_response", "server_tool_call_response"):- tool_response = next(- (part[key] for key in ("response", "result", "server_tool_call_response") if part.get(key) is not None),- "",- )- if not isinstance(tool_response, str):- tool_response = json.dumps(tool_response, default=str)- followups.append({"role": "tool", "content": tool_response, "tool_call_id": part.get("id")})- elif part_type == "reasoning":- reasoning = part.get("content")- if isinstance(reasoning, str) and reasoning:- followups.append({"role": "thinking", "content": reasoning})- elif part_type in ("blob", "uri", "file"):- followups.append({"role": msg["role"], "content": _media_part_marker(part_type, part)})- elif part_type == "compaction":- summary = part.get("content")- if not (isinstance(summary, str) and summary):- summary = "[conversation compacted]"- followups.append({"role": msg["role"], "content": summary})-- primary = {key: value for key, value in msg.items() if key != "parts"}- if text_chunks:- primary["content"] = " ".join(text_chunks)- if tool_calls:- primary["tool_calls"] = tool_calls-- # Keep an empty primary only when there are no follow-up messages, so a- # message whose parts produce nothing still holds its `role:` conversation slot- # (matching how empty flat messages render) without adding a stray blank line- # in front of every follow-up.- flattened: list[dict] = []- if text_chunks or tool_calls or not followups:- flattened.append(primary)- flattened.extend(followups)- return flattened---def _media_part_marker(part_type: str, part: dict) -> str:- modality = part.get("modality")- if not isinstance(modality, str) or not modality:- modality = "media"- if part_type == "blob":- return f"[{modality}]"- if part_type == "uri":- uri = part.get("uri")- return f"[{modality}: {uri}]" if isinstance(uri, str) and uri else f"[{modality}]"- file_id = part.get("file_id")- return f"[file: {file_id}]" if isinstance(file_id, str) and file_id else "[file]"--def _render_message(msg: dict) -> str | None:"""Render a single message dict into a `role: body` line.diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex cafa2f1d8a8f..0126eb3c1957 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -88,6 +88,7 @@ from products.ai_observability.backend.text_repr.formatters import (format_trace_text_repr,llm_trace_to_formatter_format,)+from products.ai_observability.backend.text_repr.formatters.message_formatter import has_message_contentif TYPE_CHECKING:from posthog.models import User@@ -108,19 +109,32 @@ MAX_TRACE_EVAL_EVENTS = 500# much, so we cap lower to bound cost. Over budget, the formatter uniformly samples lines.JUDGE_TRACE_MAX_CHARS = 150_000-# Written against ai_events; query_ai_events rewrites it for the events table when ai_events-# returns nothing. HAVING makes a zero count return no rows, which both triggers the events-table-# fallback and keeps "no events" distinguishable without a second query.-_TRACE_EVENT_COUNT_SQL = """+_TRACE_EVENT_NAMES = ("$ai_span", "$ai_generation", "$ai_embedding", "$ai_metric", "$ai_feedback", "$ai_trace")++# The runner drops the `$ai_trace` root row from `LLMTrace.events`, so it can never contribute a+# line to the judge transcript.+_RENDERABLE_TRACE_EVENT_NAMES = tuple(name for name in _TRACE_EVENT_NAMES if name != "$ai_trace")+++def _event_names_clause(event_names: tuple[str, ...]) -> str:+ return ", ".join(f"'{name}'" for name in event_names)+++def _trace_event_count_sql(event_names: tuple[str, ...]) -> str:+ """Count query written against ai_events; query_ai_events rewrites it for the events table when+ ai_events returns nothing. HAVING makes a zero count return no rows, which both triggers the+ events-table fallback and keeps "no events" distinguishable without a second query."""+ return f"""SELECT count() AS event_countFROM posthog.ai_events AS ai_events-WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')- AND trace_id = {trace_id}- AND timestamp >= {date_from}- AND timestamp <= {date_to}+WHERE event IN ({_event_names_clause(event_names)})+ AND trace_id = {{trace_id}}+ AND timestamp >= {{date_from}}+ AND timestamp <= {{date_to}}HAVING event_count > 0"""+_SKIP_REASONING = {"property_access_restricted": ("Default project permissions hide event properties, so this trace was not evaluated. "@@ -183,10 +197,16 @@ class TraceFetchOutcome:def _count_trace_events(- team: Team, trace_id: str, date_from: datetime, date_to: datetime, *, user: "User | None" = None+ team: Team,+ trace_id: str,+ date_from: datetime,+ date_to: datetime,+ *,+ event_names: tuple[str, ...] = _TRACE_EVENT_NAMES,+ user: "User | None" = None,) -> int:result = query_ai_events(- query=parse_select(_TRACE_EVENT_COUNT_SQL),+ query=parse_select(_trace_event_count_sql(event_names)),placeholders={"trace_id": ast.Constant(value=trace_id),"date_from": ast.Constant(value=date_from),@@ -205,7 +225,7 @@ def _count_trace_events(_TRACE_PAYLOAD_BYTES_SQL = f"""SELECT {PAYLOAD_BYTES_EXPR} AS payload_bytesFROM posthog.ai_events AS ai_events-WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')+WHERE event IN ({_event_names_clause(_TRACE_EVENT_NAMES)})AND trace_id = {{trace_id}}AND timestamp >= {{date_from}}AND timestamp <= {{date_to}}@@ -232,6 +252,21 @@ def _sum_trace_payload_bytes(return int(result.results[0][0] or 0)+def _read_missed_events(+ team: Team, trace: LLMTrace, date_from: datetime, date_to: datetime, *, user: "User | None" = None+) -> bool:+ """Decide whether a trace that came back with no events was read in full.++ A renderable event the fetch did not return means `ai_events` served a partial trace. This count+ falls back to the shared events table when `ai_events` holds no renderable row, so it finds the+ events the fetch did not see. Every evaluation would grade the wrong unit without them.+ """+ return (+ _count_trace_events(team, trace.id, date_from, date_to, event_names=_RENDERABLE_TRACE_EVENT_NAMES, user=user)+ > 0+ )++def _fetch_trace(team: Team,trace_id: str,@@ -280,10 +315,9 @@ def _fetch_trace(if not response.results:return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=event_count)trace = response.results[0]- if bound_to_date_to and not trace.events:- # The count preflight includes the `$ai_trace` root row, which never reaches `events`, so a- # non-zero count does not promise a transcript. Once the bound applies, an empty one must- # skip rather than let the judge grade nothing. A live run keeps its own handling of this.+ # The count preflight above includes the `$ai_trace` root row, which the runner drops from+ # `events`, so a non-zero count does not promise that the fetch saw the whole trace.+ if not trace.events and _read_missed_events(team, trace, date_from, date_to, user=user):return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=event_count)return TraceFetchOutcome(trace=trace, skip_reason=None, event_count=event_count)@@ -542,6 +576,29 @@ def format_trace_for_judge(trace: LLMTrace) -> str:return text+def _has_state_content(state: object, *, is_output: bool = False) -> bool:+ # Message headers and whitespace can render without any content for the judge to grade.+ if isinstance(state, list) and state and isinstance(state[0], dict):+ if "role" in state[0] or "content" in state[0]:+ return has_message_content(state, is_output=is_output)+ return bool(state.strip()) if isinstance(state, str) else bool(state)+++def _has_judge_transcript(trace: LLMTrace) -> bool:+ """Whether the trace formats into something the LLM judge can read.++ `format_trace_text_repr` renders the trace-level input and output only when the event hierarchy+ is empty, so a trace with neither formats down to its name alone and the judge grades nothing.+ A Hog eval has no such requirement: it reads trace-level cost and latency straight off the root+ event, so this gate belongs to the judge rather than to the fetch.+ """+ return (+ bool(trace.events)+ or _has_state_content(trace.inputState)+ or _has_state_content(trace.outputState, is_output=True)+ )++def build_trace_hog_globals(trace: LLMTrace, trace_id: str, *, bytecode: list[Any] | None = None) -> dict[str, Any]:"""Build Hog globals for a trace-level eval.@@ -630,6 +687,8 @@ def execute_trace_llm_judge_activity(inputs: ExecuteTraceEvaluationInputs) -> Ev)if outcome.skip_reason or outcome.trace is None:return _build_trace_skip_result(allows_na, outcome.skip_reason or "trace_not_found", output_type=output_type)+ if not _has_judge_transcript(outcome.trace):+ return _build_trace_skip_result(allows_na, "trace_not_found", output_type=output_type)return call_llm_judge(evaluation=evaluation,diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex 4bf4dcba2b73..fad7b07f2aec 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -216,11 +216,22 @@ class TestFormatTraceForJudge:@pytest.mark.parametrize("message_property", ["$ai_input", "$ai_output_choices"])@pytest.mark.parametrize("event_count,message_count", [(50, 1), (1, 50)])+ @pytest.mark.parametrize("message_format", ["content", "parts"])def test_oversized_messages_do_not_allocate_the_full_transcript(- self, message_property: str, event_count: int, message_count: int+ self, message_property: str, event_count: int, message_count: int, message_format: str) -> None:content = "start " + "x" * 500_000 + " end"- messages = [{"role": "user", "content": content} for _ in range(message_count)]+ message_content = (+ {"content": content}+ if message_format == "content"+ else {+ "parts": [+ {"type": "text", "content": content[:250_000]},+ {"type": "text", "content": content[250_000:]},+ ]+ }+ )+ messages = [{"role": "user", **message_content} for _ in range(message_count)]trace = create_trace([create_trace_event("$ai_generation", **{message_property: messages}) for _ in range(event_count)])@@ -439,27 +450,45 @@ class TestFetchTraceForEvaluation:assert outcome.trace is trace@pytest.mark.django_db(transaction=True)- @pytest.mark.parametrize(- "window_end,expected_skip",- [(FROZEN_NOW + timedelta(minutes=30), "trace_not_found"), (None, None)],- )- def test_a_backfilled_trace_left_with_no_events_is_skipped(self, setup_data, window_end, expected_skip):+ @pytest.mark.parametrize("window_end", [None, FROZEN_NOW + timedelta(minutes=30)])+ @pytest.mark.parametrize("trace_state", [{}, {"inputState": "what is the weather?"}])+ def test_an_event_less_trace_is_returned_when_the_read_saw_everything(self, setup_data, window_end, trace_state):team = setup_data["team"]- empty_trace = create_trace([])+ root_only_trace = create_trace([], **trace_state)# The count preflight sees the `$ai_trace` root row, which never reaches `events`, so the- # bounded runner can return a trace row with no transcript to grade. A live run keeps- # whatever it did with that row before, so only the backfilled run skips.+ # runner can return a trace with no events. Whether that is enough to grade depends on the+ # evaluation, so the fetch hands it back and lets each activity decide.with (time_machine.travel(FROZEN_NOW, tick=False),- patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", return_value=2),+ # The preflight count, then the renderable-event count.+ patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", side_effect=[1, 0]),patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,):- mock_runner.return_value.calculate.return_value = MagicMock(results=[empty_trace])+ mock_runner.return_value.calculate.return_value = MagicMock(results=[root_only_trace])outcome = fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW, window_end)- assert outcome.skip_reason == expected_skip- assert outcome.trace is (None if expected_skip else empty_trace)+ assert outcome.skip_reason is None+ assert outcome.trace is root_only_trace++ @pytest.mark.django_db(transaction=True)+ def test_a_partial_read_is_skipped_rather_than_graded(self, setup_data):+ team = setup_data["team"]+ root_only_trace = create_trace([], inputState="what is the weather?")++ # The count finds events the fetch did not return, so the read missed part of the trace.+ # Grading the remainder would hide those events from every evaluation.+ with (+ time_machine.travel(FROZEN_NOW, tick=False),+ # The preflight count, then the renderable-event count.+ patch("posthog.temporal.ai_observability.run_trace_evaluation._count_trace_events", side_effect=[1, 3]),+ patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,+ ):+ mock_runner.return_value.calculate.return_value = MagicMock(results=[root_only_trace])+ outcome = fetch_trace_for_evaluation(team.id, "trace-123", FROZEN_NOW)++ assert outcome.skip_reason == "trace_not_found"+ assert outcome.trace is Noneclass TestRunHogEvalOverRecentTraces:@@ -575,14 +604,60 @@ class TestRunHogEvalOverRecentTraces:class TestExecuteTraceLLMJudgeActivity:@pytest.mark.django_db(transaction=True)- def test_judges_full_trace_transcript(self, setup_data, active_key_config):- trace = create_trace(- [- create_trace_event("$ai_generation", **{"$ai_input": "What is 2+2?", "$ai_output": "4"}),- create_trace_event("$ai_generation", **{"$ai_input": "And times 3?", "$ai_output": "12"}),- ]- )-+ @pytest.mark.parametrize(+ "trace,expected_fragments",+ [+ (+ create_trace(+ [+ create_trace_event("$ai_generation", **{"$ai_input": "What is 2+2?", "$ai_output": "4"}),+ create_trace_event("$ai_generation", **{"$ai_input": "And times 3?", "$ai_output": "12"}),+ ]+ ),+ ["TRACE HIERARCHY", "What is 2+2?", "And times 3?"],+ ),+ (+ create_trace([], inputState=[{"role": "user", "content": ""}, {"role": "user", "content": "2+2?"}]),+ ["2+2?"],+ ),+ (+ create_trace(+ [],+ outputState=[+ {"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "arguments": {}}]}+ ],+ ),+ ["get_weather()"],+ ),+ (create_trace([], outputState={"score": 0}), ['"score": 0']),+ pytest.param(+ create_trace(+ [],+ outputState=[+ {+ "role": "assistant",+ "content": [+ {"type": "text", "text": "\n"},+ {+ "type": "function",+ "function": {"name": "get_weather", "arguments": {"city": "Paris"}},+ },+ ],+ }+ ],+ ),+ ['get_weather(city="Paris")'],+ id="root_tool_call_with_whitespace",+ ),+ ],+ )+ def test_judges_full_trace_transcript(+ self,+ setup_data: dict[str, Any],+ active_key_config: None,+ trace: LLMTrace,+ expected_fragments: list[str],+ ) -> None:with patch("posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=2),@@ -607,14 +682,60 @@ class TestExecuteTraceLLMJudgeActivity:request = mock_client.complete.call_args[0][0]content = request.messages[0]["content"]assert "AI trace" in request.system- assert "TRACE HIERARCHY" in content- assert content.count("[GEN]") == 2- assert "What is 2+2?" in content- assert "And times 3?" in content+ assert content.count("[GEN]") == len(trace.events)+ for fragment in expected_fragments:+ assert fragment in contentassert result["verdict"] is Trueassert result["reasoning"] == "Resolved both questions"+ @pytest.mark.parametrize(+ "trace_state",+ [+ {},+ {"inputState": ""},+ {"inputState": " ", "outputState": "\n"},+ {"inputState": [{"role": "user", "content": ""}]},+ {"outputState": [{"role": "assistant", "content": " \n "}]},+ {"inputState": [{"role": "user", "content": []}]},+ {"inputState": [{"role": "user", "parts": []}]},+ {"outputState": [{"role": "assistant", "parts": [{"type": "text", "content": " \n "}]}]},+ ],+ )+ @pytest.mark.parametrize("output_type", ["boolean", "numeric"])+ def test_skips_without_llm_call_when_the_trace_has_no_transcript(+ self, trace_state: dict[str, Any], output_type: str+ ) -> None:+ # With no events and no trace-level state the formatter emits the trace name alone, and the+ # judge would confidently report that there is nothing to grade. Whitespace state renders as+ # a heading above nothing, which reads the same way.+ root_only_trace = create_trace([], **trace_state)++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=root_only_trace, skip_reason=None, event_count=1),+ ):+ with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:+ result = execute_trace_llm_judge_activity(+ ExecuteTraceEvaluationInputs(+ evaluation={+ "evaluation_type": "llm_judge",+ "evaluation_config": {"prompt": "Is the response correct?"},+ "output_type": output_type,+ "output_config": {},+ "team_id": 1,+ },+ team_id=1,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ assert result["skipped"] is True+ assert result["skip_reason"] == "trace_not_found"+ assert result["result_type"] == output_type+ mock_client_class.assert_not_called()+@pytest.mark.parametrize("skip_reason", ["trace_not_found", "property_access_restricted"])def test_skips_without_llm_call(self, skip_reason: str) -> None:with patch(@@ -675,6 +796,35 @@ class TestExecuteTraceHogEvalActivity:assert result["verdict"] is True+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_grades_a_root_only_trace_on_trace_level_metadata(self, setup_data):+ # Hog needs no transcript: cost and latency come off the root event. A trace the judge+ # cannot read must still reach a latency evaluation.+ bytecode = compile_hog("return target.total_latency_seconds < 10", "destination")+ evaluation = evaluation_dict(+ setup_data,+ evaluation_type="hog",+ evaluation_config={"source": "...", "bytecode": bytecode},+ )+ root_only_trace = create_trace([], totalLatency=1.5)++ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",+ return_value=TraceFetchOutcome(trace=root_only_trace, skip_reason=None, event_count=1),+ ):+ result = await execute_trace_hog_eval_activity(+ ExecuteTraceEvaluationInputs(+ evaluation=evaluation,+ team_id=setup_data["team"].id,+ trace_id="trace-123",+ window_start=FROZEN_NOW.isoformat(),+ )+ )++ assert result["verdict"] is True+ assert not result.get("skipped")+@pytest.mark.asyncio@pytest.mark.parametrize("skip_reason", ["trace_too_large", "property_access_restricted"])async def test_skips_without_running_hog(self, skip_reason: str) -> None:diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.pyindex e31d21443f66..18af5519498e 100644--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py@@ -32,6 +32,7 @@ from .constants import (SAMPLING_REDUCTION_FACTOR,SPECIAL_BLOCK_TYPES,)+from .otel_parts import flatten_parts_messagefrom .tool_formatter import format_tools@@ -652,6 +653,81 @@ def _format_message_body(msg: dict[str, Any], options: FormatterOptions | None)return lines+def _flatten_parts_messages(messages: list[Any]) -> Iterable[Any]:+ for msg in messages:+ if isinstance(msg, dict):+ yield from flatten_parts_message(msg)+ else:+ yield msg+++def _safe_format_message_body(msg: dict[str, Any], options: FormatterOptions | None) -> list[str]:+ try:+ return _format_message_body(msg, options)+ except RenderBudgetExceeded:+ raise+ except Exception:+ # Customer payloads can break any shape assumption in the body formatters, so one+ # malformed message degrades to its own repr and the rest of the trace still renders.+ body_lines, _ = truncate_content(safe_extract_text(msg), options)+ return body_lines+++def _normalize_output_messages(choices: list[Any]) -> list[dict[str, Any]]:+ messages: list[dict[str, Any]] = []+ for choice in choices:+ if not isinstance(choice, dict):+ continue++ # The Responses API can send its items at the top level of the array, with no `role`+ # and no `content`. Pass those straight to `format_messages_array`, which knows their+ # shapes, rather than dropping them for failing the role check below.+ if _is_responses_item(choice):+ messages.append(choice)+ continue++ # Extract message from choice+ # Handle both OpenAI format (choice.message) and Anthropic format (choice is the message)+ message = choice.get("message")+ if not message or not isinstance(message, dict):+ # Anthropic/direct format - choice IS the message+ if "role" in choice or "content" in choice:+ message = choice+ else:+ continue++ # Normalize tool_calls - extract from content if present+ tool_calls = message.get("tool_calls", [])+ content = message.get("content", "")+ content_tool_calls = extract_tool_calls_from_content(content)+ if content_tool_calls:+ tool_calls = content_tool_calls++ # Create normalized message+ normalized_message = {+ "role": message.get("role", "assistant"),+ "content": content,+ "tool_calls": tool_calls,+ }+ # Defer parts expansion until the budgeted renderer consumes each message.+ if "parts" in message:+ normalized_message["parts"] = message["parts"]+ messages.append(normalized_message)++ return messages+++def has_message_content(messages: list[Any], *, is_output: bool = False) -> bool:+ if is_output:+ messages = _normalize_output_messages(messages)+ return any(+ line.strip()+ for msg in _flatten_parts_messages(messages)+ if isinstance(msg, dict)+ for line in _safe_format_message_body(msg, {"truncated": False, "include_markers": False})+ )++def format_messages_array(messages: list[Any], options: FormatterOptions | None = None) -> list[str]:"""Format an array of message objects without header.@@ -667,8 +743,14 @@ def format_messages_array(messages: list[Any], options: FormatterOptions | NoneList of formatted lines (no header, starts directly with messages)"""lines = FormatterLines(options)+ needs_separator = False- for i, msg in enumerate(messages):+ for i, msg in enumerate(_flatten_parts_messages(messages)):+ # Add separator between messages (but not after the last one)+ if needs_separator:+ lines.append("")+ lines.append("-" * 80)+ needs_separator = isinstance(msg, dict)if not isinstance(msg, dict):continue@@ -679,20 +761,7 @@ def format_messages_array(messages: list[Any], options: FormatterOptions | Nonelines.append(f"[{i + 1}] {role.upper()}")lines.append("")- try:- body_lines = _format_message_body(msg, options)- except RenderBudgetExceeded:- raise- except Exception:- # Customer payloads can break any shape assumption in the body formatters, so one- # malformed message degrades to its own repr and the rest of the trace still renders.- body_lines, _ = truncate_content(safe_extract_text(msg), options)- lines.extend(body_lines)-- # Add separator between messages (but not after the last one)- if i < len(messages) - 1:- lines.append("")- lines.append("-" * 80)+ lines.extend(_safe_format_message_body(msg, options))return lines@@ -762,44 +831,7 @@ def format_output_messages(# Output choices (most common format)if choices and isinstance(choices, list) and len(choices) > 0:- # Extract messages from choices- messages = []- for choice in choices:- if not isinstance(choice, dict):- continue-- # The Responses API can send its items at the top level of the array, with no `role`- # and no `content`. Pass those straight to `format_messages_array`, which knows their- # shapes, rather than dropping them for failing the role check below.- if _is_responses_item(choice):- messages.append(choice)- continue-- # Extract message from choice- # Handle both OpenAI format (choice.message) and Anthropic format (choice is the message)- message = choice.get("message")- if not message or not isinstance(message, dict):- # Anthropic/direct format - choice IS the message- if "role" in choice or "content" in choice:- message = choice- else:- continue-- # Normalize tool_calls - extract from content if present- tool_calls = message.get("tool_calls", [])- content = message.get("content", "")- content_tool_calls = extract_tool_calls_from_content(content)- if content_tool_calls:- tool_calls = content_tool_calls-- # Create normalized message- normalized_message = {- "role": message.get("role", "assistant"),- "content": content,- "tool_calls": tool_calls,- }- messages.append(normalized_message)-+ messages = _normalize_output_messages(choices)if messages:lines.append("")lines.append("OUTPUT:")diff --git a/products/ai_observability/backend/text_repr/formatters/otel_parts.py b/products/ai_observability/backend/text_repr/formatters/otel_parts.pynew file mode 100644index 000000000000..388e1162fcdd--- /dev/null+++ b/products/ai_observability/backend/text_repr/formatters/otel_parts.py@@ -0,0 +1,113 @@+import json+++def flatten_parts_message(msg: dict) -> list[dict]:+ """Convert an OTel GenAI semconv parts-shaped message into flat chat message(s).++ `/i/v0/ai/otel` stores `gen_ai.input.messages` / `gen_ai.output.messages` verbatim,+ so messages arrive as `{"role": ..., "parts": [...]}` with the text inside typed+ parts instead of a flat `content` key. The judge's `message_utils._render_message`+ and the trace text formatter only read `content` and `tool_calls`, so without this+ these messages render as a bare role line and the LLM judge grades an empty+ conversation.++ Mirrors the trace UI's `otel.yaml` normalizer recipe so the judge sees the same+ conversation the trace view renders:+ - `{"type": "text", "content": ...}` parts join into the message's `content`+ - `{"type": "tool_call", "id", "name", "arguments"}` parts become `tool_calls`,+ and so do `server_tool_call` parts (provider-executed tools like web_search),+ with the polymorphic `server_tool_call` payload as the arguments+ - each `{"type": "tool_call_response", "id", "response"}` part becomes its own+ follow-up `role: "tool"` message so the existing `tool[<id>]:` correlation applies.+ `response` is the field the GenAI semconv schema requires. The spec's own example+ showed `result` for its first ten months, so producers that followed the example+ are in the wild too, and all of `response`/`result`/`server_tool_call_response`+ are read in that order, which also folds `server_tool_call_response` parts in+ - `reasoning` parts become follow-up `role: "thinking"` messages+ - `blob`/`uri`/`file` parts become bracketed text markers (`[image]`,+ `[image: <uri>]`, `[file: <id>]`). The trace view renders image blobs and uris+ as actual images; the judge gets markers instead because base64 payloads are+ token noise to an LLM+ - `compaction` parts become follow-up messages carrying the compacted summary,+ or a `[conversation compacted]` marker when the summary is absent++ Like the recipe, this only applies to dicts with a string `role` alongside the+ `parts` list, so a structured-output payload that happens to have its own `parts`+ array still reaches the JSON-stringify fallback in `message_utils._render_message`.++ Messages that already carry `content` or `tool_calls`, or have no `parts` list,+ pass through unchanged.+ """+ parts = msg.get("parts")+ if not isinstance(msg.get("role"), str) or not isinstance(parts, list):+ return [msg]+ if msg.get("content") or msg.get("tool_calls"):+ return [msg]++ text_chunks: list[str] = []+ tool_calls: list[dict] = []+ followups: list[dict] = []+ for part in parts:+ if not isinstance(part, dict):+ continue+ part_type = part.get("type")+ if part_type == "text":+ content = part.get("content")+ if isinstance(content, str) and content:+ text_chunks.append(content)+ elif part_type in ("tool_call", "server_tool_call"):+ arguments_key = "arguments" if part_type == "tool_call" else "server_tool_call"+ tool_calls.append(+ {+ "id": part.get("id"),+ "function": {"name": part.get("name", ""), "arguments": part.get(arguments_key, "")},+ }+ )+ elif part_type in ("tool_call_response", "server_tool_call_response"):+ tool_response = next(+ (part[key] for key in ("response", "result", "server_tool_call_response") if part.get(key) is not None),+ "",+ )+ if not isinstance(tool_response, str):+ tool_response = json.dumps(tool_response, default=str)+ followups.append({"role": "tool", "content": tool_response, "tool_call_id": part.get("id")})+ elif part_type == "reasoning":+ reasoning = part.get("content")+ if isinstance(reasoning, str) and reasoning:+ followups.append({"role": "thinking", "content": reasoning})+ elif part_type in ("blob", "uri", "file"):+ followups.append({"role": msg["role"], "content": _media_part_marker(part_type, part)})+ elif part_type == "compaction":+ summary = part.get("content")+ if not (isinstance(summary, str) and summary):+ summary = "[conversation compacted]"+ followups.append({"role": msg["role"], "content": summary})++ primary = {key: value for key, value in msg.items() if key != "parts"}+ if text_chunks:+ primary["content"] = " ".join(text_chunks)+ if tool_calls:+ primary["tool_calls"] = tool_calls++ # Keep an empty primary only when there are no follow-up messages, so a+ # message whose parts produce nothing still holds its `role:` conversation slot+ # (matching how empty flat messages render) without adding a stray blank line+ # in front of every follow-up.+ flattened: list[dict] = []+ if text_chunks or tool_calls or not followups:+ flattened.append(primary)+ flattened.extend(followups)+ return flattened+++def _media_part_marker(part_type: str, part: dict) -> str:+ modality = part.get("modality")+ if not isinstance(modality, str) or not modality:+ modality = "media"+ if part_type == "blob":+ return f"[{modality}]"+ if part_type == "uri":+ uri = part.get("uri")+ return f"[{modality}: {uri}]" if isinstance(uri, str) and uri else f"[{modality}]"+ file_id = part.get("file_id")+ return f"[file: {file_id}]" if isinstance(file_id, str) and file_id else "[file]"diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.pyindex 6a1e49ddf286..0079a887a26c 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py@@ -16,6 +16,7 @@ from ..message_formatter import (format_output_messages,format_single_tool_call,format_tool_calls,+ has_message_content,safe_extract_text,sanitize_surrogates,truncate_content,@@ -760,6 +761,69 @@ class TestResponsesApiItems:assert "[INPUT_TEXT]" not in result+class TestMessageContent:+ @pytest.mark.parametrize(+ "messages,expected",+ [+ ([{"role": "user", "content": " " * 2000}], False),+ ([{"role": "user", "content": [{"type": "text", "text": "\n"}]}], False),+ ([{"role": "user", "parts": []}], False),+ ([{"role": "assistant", "parts": [{"type": "text", "content": " "}]}], False),+ ([{"role": "user", "content": ""}, {"role": "assistant", "content": "4"}], True),+ ([{"role": "assistant", "tool_calls": [{"function": {"name": "get_weather", "arguments": {}}}]}], True),+ ([{"role": "assistant", "parts": [{"type": "text", "content": "4"}]}], True),+ ([{"role": "assistant", "parts": [{"type": "tool_call", "name": "get_weather", "arguments": {}}]}], True),+ ([{"role": "tool", "parts": [{"type": "tool_call_response", "response": {"temp_c": 0}}]}], True),+ ([{"role": "user", "parts": [{"type": "blob", "modality": "image"}]}], True),+ ],+ )+ def test_ignores_empty_bodies_but_keeps_renderable_content(+ self, messages: list[dict[str, object]], expected: bool+ ) -> None:+ assert has_message_content(messages) is expected+++class TestOtelPartsMessages:+ @parameterized.expand(+ [+ (+ "input",+ format_input_messages,+ [+ {"role": "user", "parts": [{"type": "text", "content": "What is the weather in Paris?"}]},+ {+ "role": "assistant",+ "parts": [+ {"type": "tool_call", "id": "call_1", "name": "get_weather", "arguments": {"city": "Paris"}}+ ],+ },+ {+ "role": "tool",+ "parts": [{"type": "tool_call_response", "id": "call_1", "response": {"temp_c": 21}}],+ },+ ],+ ["What is the weather in Paris?", 'get_weather(city="Paris")', '"temp_c": 21'],+ ),+ (+ "output",+ lambda messages: format_output_messages(None, messages),+ [+ {+ "role": "assistant",+ "parts": [{"type": "text", "content": "It is 21C in Paris."}],+ "finish_reason": "stop",+ }+ ],+ ["[1] ASSISTANT", "It is 21C in Paris."],+ ),+ ]+ )+ def test_renders_text_held_in_parts(self, _name, render, messages, expected):+ result = "\n".join(render(messages))+ for fragment in expected:+ assert fragment in result++class TestSanitizeSurrogates:"""Test repair of unpaired UTF-16 surrogates."""