: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
feat(aio): enable trace-level evaluation reports (#71130)
Radu Raicea75a13b2b6784
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 7211e929ef10..c76393e5c21f 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -871,9 +871,19 @@ export const productUrls = {msg?: string}): string => {+ const encodePathSegment = (value: string): string => {+ const encodedValue = encodeURIComponent(value).replace(+ /[!'()*]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`+ )+ return encodeURIComponent(encodedValue).replace(+ /[!'()*]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`+ )+ }const queryParams = new URLSearchParams(params)const stringifiedParams = queryParams.toString()- return `/ai-observability/traces/${id}${stringifiedParams ? `?${stringifiedParams}` : ''}`+ return `/ai-observability/traces/${encodePathSegment(id)}${stringifiedParams ? `?${stringifiedParams}` : ''}`},aiObservabilityUsers: (): string => '/ai-observability/users',aiObservabilityErrors: (): string => '/ai-observability/errors',diff --git a/posthog/temporal/ai_observability/eval_reports/activities.py b/posthog/temporal/ai_observability/eval_reports/activities.pyindex 3b9fd2d78f8f..810ab96ba8ea 100644--- a/posthog/temporal/ai_observability/eval_reports/activities.py+++ b/posthog/temporal/ai_observability/eval_reports/activities.py@@ -13,6 +13,11 @@ from posthog.hogql import astfrom posthog.clickhouse.client.connection import Workloadfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition+from posthog.temporal.ai_observability.eval_reports.targets import (+ GENERATION_TARGET,+ resolve_evaluation_target,+ target_event_predicate,+)from posthog.temporal.ai_observability.eval_reports.types import (CheckCountTriggeredEvalReportInput,CheckCountTriggeredEvalReportOutput,@@ -167,6 +172,7 @@ def _count_eval_results_for_report(report: "EvaluationReport", since: dt.datetim# would be coerced in the team's timezone and silently shift the comparison# by the team's offset.outcome_definition = get_outcome_definition(report.evaluation.output_type)+ evaluation_target_predicate = target_event_predicate(report.evaluation.target)# nosemgrep: hogql-fstring-audit (the predicate comes from fixed internal output-type definitions)query = parse_select(f"""@@ -175,6 +181,7 @@ def _count_eval_results_for_report(report: "EvaluationReport", since: dt.datetimWHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {outcome_definition.event_predicate}+ AND {evaluation_target_predicate}AND timestamp >= {{since}}""",placeholders={@@ -198,6 +205,7 @@ def _find_nth_eval_timestamp(n: int,before: dt.datetime,output_type: str = "boolean",+ evaluation_target: str = "generation",) -> dt.datetime:"""Find the timestamp of the Nth-most-recent eval result.@@ -214,6 +222,7 @@ def _find_nth_eval_timestamp(# Pass `before` as a datetime so HogQL serializes it as toDateTime64(..., 6, <team_tz>)# instead of a bare string that would be coerced in the team's timezone.outcome_definition = get_outcome_definition(output_type)+ evaluation_target_predicate = target_event_predicate(evaluation_target)# nosemgrep: hogql-fstring-audit (the predicate comes from fixed internal output-type definitions)query = parse_select(f"""@@ -223,6 +232,7 @@ def _find_nth_eval_timestamp(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {outcome_definition.event_predicate}+ AND {evaluation_target_predicate}AND timestamp <= {{before}}ORDER BY timestamp DESCLIMIT {{limit}}@@ -312,6 +322,7 @@ async def prepare_report_context_activity(n=report.trigger_threshold or 100,before=now,output_type=evaluation.output_type,+ evaluation_target=evaluation.target,)else:period_start = now - _period_for_scheduled_report(report, now)@@ -367,21 +378,27 @@ async def run_eval_report_agent_activity(def run_agent():from posthog.temporal.ai_observability.eval_reports.report_agent import run_eval_report_agent- return run_eval_report_agent(- team_id=inputs.team_id,- evaluation_id=inputs.evaluation_id,- evaluation_name=inputs.evaluation_name,- evaluation_description=inputs.evaluation_description,- evaluation_prompt=inputs.evaluation_prompt,- evaluation_type=inputs.evaluation_type,- output_type=inputs.output_type,- period_start=inputs.period_start,- period_end=inputs.period_end,- previous_period_start=inputs.previous_period_start,- report_prompt_guidance=inputs.report_prompt_guidance,+ evaluation_target = _load_evaluation_target(inputs.team_id, inputs.evaluation_id)+ return (+ run_eval_report_agent(+ team_id=inputs.team_id,+ evaluation_id=inputs.evaluation_id,+ evaluation_name=inputs.evaluation_name,+ evaluation_description=inputs.evaluation_description,+ evaluation_prompt=inputs.evaluation_prompt,+ evaluation_type=inputs.evaluation_type,+ evaluation_target=evaluation_target,+ output_type=inputs.output_type,+ period_start=inputs.period_start,+ period_end=inputs.period_end,+ previous_period_start=inputs.previous_period_start,+ report_prompt_guidance=inputs.report_prompt_guidance,+ ),+ evaluation_target,)- content = await run_agent()+ content, evaluation_target = await run_agent()+ content.evaluation_target = evaluation_targetreturn RunEvalReportAgentOutput(report_id=inputs.report_id,@@ -391,6 +408,14 @@ async def run_eval_report_agent_activity()+def _load_evaluation_target(team_id: int, evaluation_id: str) -> str:+ from products.ai_observability.backend.models.evaluations import ( # noqa: PLC0415 -- keep Django model loading inside activity execution+ Evaluation,+ )++ return Evaluation.objects.values_list("target", flat=True).get(id=evaluation_id, team_id=team_id)++@temporalio.activity.defnasync def store_report_run_activity(inputs: StoreReportRunInput,@@ -412,6 +437,7 @@ async def store_report_run_activity(# Mirror content.metrics into the legacy `metadata` JSONField for consumers that still read it.content = normalize_report_content_payload(inputs.content or {})+ evaluation_target = resolve_evaluation_target(content.get("evaluation_target", GENERATION_TARGET))metrics = content.get("metrics", {}) or {}parsed_metrics = EvalReportMetrics.from_dict(metrics)@@ -429,6 +455,7 @@ async def store_report_run_activity(# Collect citations from structured content (v2), not from per-section listscitations = content.get("citations", []) or []all_referenced_ids = [c.get("generation_id", "") for c in citations if c.get("generation_id")]+ all_referenced_trace_ids = [c.get("trace_id", "") for c in citations if c.get("trace_id")]properties: dict = {"$ai_evaluation_id": inputs.evaluation_id,@@ -438,6 +465,7 @@ async def store_report_run_activity("$ai_report_period_start": inputs.period_start,"$ai_report_period_end": inputs.period_end,"$ai_report_output_type": parsed_metrics.output_type,+ "$ai_report_evaluation_target": evaluation_target,"$ai_report_result_counts": parsed_metrics.result_counts,"$ai_report_result_rates": parsed_metrics.result_rates,"$ai_report_previous_result_counts": parsed_metrics.previous_result_counts,@@ -448,6 +476,7 @@ async def store_report_run_activity("$ai_report_content": content,"$ai_report_citations": citations,"$ai_report_referenced_generation_ids": all_referenced_ids,+ "$ai_report_referenced_trace_ids": all_referenced_trace_ids,"$ai_report_section_count": len(content.get("sections", [])),}if parsed_metrics.output_type == "boolean":diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.pyindex f02f9138cfd7..cdde7dfdf0c7 100644--- a/posthog/temporal/ai_observability/eval_reports/delivery.py+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py@@ -7,12 +7,17 @@ email HTML body and Slack Block Kit payloads from that shape.import refrom datetime import UTC, datetime+from urllib.parse import quote, urlencodeimport structlogfrom markdown_it import MarkdownItfrom markdown_to_mrkdwn import SlackMarkdownConverter-from posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent, EvalReportMetrics+from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (+ Citation,+ EvalReportContent,+ EvalReportMetrics,+)logger = structlog.get_logger(__name__)@@ -39,6 +44,9 @@ _OUTCOME_LABELS = {"sentiment": (("positive", "Positive"), ("neutral", "Neutral"), ("negative", "Negative")),}+type CitationMap = dict[str, tuple[str, str | None]]+_SAFE_CITATION_LABEL_RE = re.compile(r"^[A-Za-z0-9._~-]{1,8}$")+def _inline_email_styles(html: str) -> str:"""Add inline styles to HTML elements for email client compatibility."""@@ -61,47 +69,69 @@ def _format_period_for_display(iso_str: str) -> str:return dt.strftime("%b %d, %Y %H:%M UTC")-def _build_citation_map(citations: list) -> dict[str, str]:- """Build a generation_id → trace_id lookup from structured citations."""- return {c.generation_id: c.trace_id for c in citations if c.generation_id and c.trace_id}+def _build_citation_map(citations: list[Citation]) -> CitationMap:+ """Map each cited ID to its trace and optional focused generation."""+ citation_map: CitationMap = {}+ for citation in citations:+ if citation.generation_id and citation.trace_id:+ citation_map[citation.generation_id] = (citation.trace_id, citation.generation_id)+ elif citation.trace_id:+ citation_map[citation.trace_id] = (citation.trace_id, None)+ return citation_map-def _make_trace_link(project_id: int, generation_id: str, trace_id: str) -> str:- """Build the trace URL for a cited generation."""+def _make_trace_link(project_id: int, trace_id: str, generation_id: str | None) -> str:+ """Build a trace URL, optionally focused on a cited generation."""from posthog.utils import absolute_uri- return absolute_uri(f"/project/{project_id}/ai-observability/traces/{trace_id}?event={generation_id}")+ # kea-router decodes the pathname once before matching, so preserve an encoded layer for the scene.+ encoded_trace_id = quote(quote(trace_id, safe=""), safe="")+ path = f"/project/{project_id}/ai-observability/traces/{encoded_trace_id}"+ if generation_id:+ path = f"{path}?{urlencode({'event': generation_id})}"+ return absolute_uri(path)+++def _citation_link_label(cited_id: str, generation_id: str | None) -> str:+ """Keep arbitrary IDs from breaking the generated Markdown link label."""+ preview = cited_id[:8]+ if _SAFE_CITATION_LABEL_RE.fullmatch(preview):+ return f"{preview}..."+ return "generation" if generation_id else "trace"-def _linkify_citations(text: str, project_id: int, citation_map: dict[str, str]) -> str:- """Replace cited generation IDs with clickable markdown links.+def _linkify_citations(text: str, project_id: int, citation_map: CitationMap) -> str:+ """Replace cited generation or trace IDs with clickable markdown links.Uses the structured citation map (from add_citation calls) rather thanscanning for UUID patterns. Only IDs the agent explicitly cited get linked.Handles common LLM formatting wrappers (backticks, angle brackets).Two-phase approach avoids double-replacement: first swap every occurrence- of each gen_id to a unique placeholder, then replace placeholders with the- actual markdown links. This prevents gen_ids inside URLs from being matched.+ of each cited ID to a unique placeholder, then replace placeholders with the+ actual markdown links. This prevents cited IDs inside URLs from being matched."""if not citation_map:return text- # Phase 1: replace all occurrences of each gen_id with a placeholder.+ # Phase 1: replace all occurrences of each cited ID with a placeholder.placeholders: dict[str, str] = {}- for i, gen_id in enumerate(citation_map):+ for i, cited_id in enumerate(citation_map):placeholder = f"\x00CITE{i}\x00"- placeholders[placeholder] = gen_id+ placeholders[placeholder] = cited_id+ _, generation_id = citation_map[cited_id]- for wrapper in [f"`` `{gen_id}` ``", f"`{gen_id}`", f"<{gen_id}>"]:+ for wrapper in [f"`` `{cited_id}` ``", f"`{cited_id}`", f"<{cited_id}>"]:text = text.replace(wrapper, placeholder)- text = text.replace(gen_id, placeholder)+ if generation_id:+ text = text.replace(cited_id, placeholder)# Phase 2: replace placeholders with markdown links.- for placeholder, gen_id in placeholders.items():- trace_id = citation_map[gen_id]- link = _make_trace_link(project_id, gen_id, trace_id)- text = text.replace(placeholder, f"[{gen_id[:8]}...]({link})")+ for placeholder, cited_id in placeholders.items():+ trace_id, generation_id = citation_map[cited_id]+ link = _make_trace_link(project_id, trace_id, generation_id)+ label = _citation_link_label(cited_id, generation_id)+ text = text.replace(placeholder, f"[{label}]({link})")return text@@ -191,7 +221,7 @@ def _render_metrics_slack_blocks(metrics: EvalReportMetrics) -> list[dict]:return blocks-def _render_section_html(title: str, content: str, project_id: int, citation_map: dict[str, str]) -> str:+def _render_section_html(title: str, content: str, project_id: int, citation_map: CitationMap) -> str:"""Render a titled markdown section as HTML with clickable trace links."""content = _strip_redundant_leading_heading(content, title)content_with_links = _linkify_citations(content, project_id, citation_map)@@ -200,7 +230,7 @@ def _render_section_html(title: str, content: str, project_id: int, citation_mapreturn f"<h2>{title}</h2>\n{html_content}\n"-def _render_section_mrkdwn(title: str, content: str, project_id: int, citation_map: dict[str, str]) -> str:+def _render_section_mrkdwn(title: str, content: str, project_id: int, citation_map: CitationMap) -> str:"""Render a titled markdown section as Slack mrkdwn with clickable trace links."""content = _strip_redundant_leading_heading(content, title)content = _linkify_citations(content, project_id, citation_map)diff --git a/posthog/temporal/ai_observability/eval_reports/emit_signal.py b/posthog/temporal/ai_observability/eval_reports/emit_signal.pyindex 203cb870e5c4..8e0a495a14aa 100644--- a/posthog/temporal/ai_observability/eval_reports/emit_signal.py+++ b/posthog/temporal/ai_observability/eval_reports/emit_signal.py@@ -70,7 +70,7 @@ class EvalReportSignalSummary(BaseModel):SUMMARIZE_REPORT_SYSTEM_PROMPT = """You are a concise technical writer. Your job is to produce a short signal description from a PostHog LLM evaluation REPORT.-Unlike a per-result signal (one judge verdict), a report is an analytical narrative over many evaluation results in a time window. It already contains a title, several titled sections, metrics, and citations to specific generations. Your output should distill that narrative into a signal that fits alongside signals from other observability tools.+Unlike a per-result signal (one judge verdict), a report is an analytical narrative over many evaluation results in a time window. It already contains a title, several titled sections, metrics, and citations to specific traces. Your output should distill that narrative into a signal that fits alongside signals from other observability tools.You will be given:- Evaluation context: name, optional description, and evaluation criteria when applicable@@ -99,7 +99,7 @@ Produce:- 0.8-0.9 = high, should be prioritized- 1.0 = critical, act immediately-Base significance on: the magnitude of the outcome-distribution change, the prevalence of concerning outcomes in the evaluation's own semantics, breadth across generations (citation count as proxy), and how actionable the finding is from the report's prose. A sentiment label describes the user's message, not whether the AI response was good or bad.+Base significance on: the magnitude of the outcome-distribution change, the prevalence of concerning outcomes in the evaluation's own semantics, breadth across cited traces, and how actionable the finding is from the report's prose. A sentiment label describes the user's message, not whether the AI response was good or bad.The output will be fed into a signal grouping and investigation system that groups related findings across observability tools. Write for an engineer who hasn't seen this evaluation before.diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.pyindex df0759a4732b..87f0410e82c8 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py@@ -23,10 +23,11 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import ()from posthog.temporal.ai_observability.eval_reports.report_agent.state import EvalReportAgentStatefrom posthog.temporal.ai_observability.eval_reports.report_agent.tools import (- EVAL_REPORT_TOOLS,_ch_ts,_fetch_period_summary,+ get_eval_report_tools,)+from posthog.temporal.ai_observability.eval_reports.targets import GENERATION_TARGETfrom posthog.temporal.ai_observability.llm_endpoint import build_langchain_chat_clientlogger = structlog.get_logger(__name__)@@ -39,6 +40,7 @@ def _compute_metrics(period_end: str,previous_period_start: str,output_type: str = "boolean",+ evaluation_target: str = GENERATION_TARGET,) -> EvalReportMetrics:"""Compute report metrics directly via HogQL (independent of agent state).@@ -54,9 +56,11 @@ def _compute_metrics(ts_prev_start = _ch_ts(previous_period_start)definition = get_outcome_definition(output_type)- result_counts, total = _fetch_period_summary(team_id, evaluation_id, ts_start, ts_end, definition)+ result_counts, total = _fetch_period_summary(+ team_id, evaluation_id, ts_start, ts_end, definition, evaluation_target+ )previous_result_counts, previous_total = _fetch_period_summary(- team_id, evaluation_id, ts_prev_start, ts_start, definition+ team_id, evaluation_id, ts_prev_start, ts_start, definition, evaluation_target)return EvalReportMetrics(@@ -73,7 +77,12 @@ def _compute_metrics(return empty-def _fallback_content(evaluation_name: str, metrics: EvalReportMetrics, reason: str) -> EvalReportContent:+def _fallback_content(+ evaluation_name: str,+ metrics: EvalReportMetrics,+ reason: str,+ evaluation_target: str = "generation",+) -> EvalReportContent:"""Produce a minimal valid EvalReportContent when the agent fails or validates out.The metrics are always populated (we compute them independently), so even@@ -81,10 +90,14 @@ def _fallback_content(evaluation_name: str, metrics: EvalReportMetrics, reason:went wrong at the agent level so the user isn't left staring at an empty UI."""if metrics.total_runs == 0:+ ingestion_hint = (+ "trace evaluation results are being ingested"+ if evaluation_target == "trace"+ else "`$ai_generation` events are being ingested"+ )summary = (f"No evaluation runs recorded for **{evaluation_name}** in this period. "- f"Check that the evaluation is enabled and that `$ai_generation` events "- f"are being ingested."+ f"Check that the evaluation is enabled and that {ingestion_hint}.")elif metrics.output_type == "boolean":trend = ""@@ -124,6 +137,7 @@ def _fallback_content(evaluation_name: str, metrics: EvalReportMetrics, reason:summary = f"**Outcome distribution:** {distribution}{trend}, across {metrics.total_runs} runs."return EvalReportContent(+ evaluation_target=evaluation_target,title=f"Automated fallback report for {evaluation_name}",sections=[ReportSection(@@ -146,7 +160,7 @@ def _append_references_section(content: EvalReportContent) -> None:"""if not content.citations:return- refs_lines = [f"{i}. `{c.generation_id}` — {c.reason}" for i, c in enumerate(content.citations, 1)]+ refs_lines = [f"{i}. `{c.generation_id or c.trace_id}` — {c.reason}" for i, c in enumerate(content.citations, 1)]content.sections.append(ReportSection(title="References", content="\n".join(refs_lines)))@@ -184,6 +198,7 @@ def run_eval_report_agent(previous_period_start: str,report_prompt_guidance: str = "",output_type: str = "boolean",+ evaluation_target: str = "generation",) -> EvalReportContent:"""Run the evaluation report agent and return the generated content.@@ -206,6 +221,7 @@ def run_eval_report_agent(period_end,previous_period_start,output_type=output_type,+ evaluation_target=evaluation_target,)llm = build_langchain_chat_client(EVAL_REPORT_AGENT_MODEL, EVAL_REPORT_AGENT_TIMEOUT, ai_product="aio_eval_reports")@@ -214,6 +230,7 @@ def run_eval_report_agent(evaluation_name=evaluation_name,evaluation_description=evaluation_description,evaluation_type=evaluation_type,+ evaluation_target=evaluation_target,evaluation_prompt=evaluation_prompt,output_type=output_type,period_start=period_start,@@ -223,7 +240,7 @@ def run_eval_report_agent(agent = create_react_agent(model=llm,- tools=EVAL_REPORT_TOOLS,+ tools=get_eval_report_tools(evaluation_target),prompt=system_prompt,state_schema=EvalReportAgentState,)@@ -239,12 +256,14 @@ def run_eval_report_agent("evaluation_description": evaluation_description,"evaluation_prompt": evaluation_prompt,"evaluation_type": evaluation_type,+ "evaluation_target": evaluation_target,"output_type": output_type,"period_start": period_start,"period_end": period_end,"previous_period_start": previous_period_start,"report_prompt_guidance": report_prompt_guidance,- "report": EvalReportContent(metrics=metrics),+ "report": EvalReportContent(evaluation_target=evaluation_target, metrics=metrics),+ "trace_id_allowlist": [],}from posthog.temporal.ai_observability.eval_reports.metrics import increment_errors, increment_report_generated@@ -273,9 +292,12 @@ def run_eval_report_agent(try:result = agent.invoke(initial_state, config)- content: EvalReportContent = result.get("report", EvalReportContent(metrics=metrics))+ content: EvalReportContent = result.get(+ "report", EvalReportContent(evaluation_target=evaluation_target, metrics=metrics)+ )# Always overwrite metrics with the trusted computation — the agent cannot# fabricate numbers by mutating state["report"].metrics.+ content.evaluation_target = evaluation_targetcontent.metrics = metricsvalidation_error = _validate_agent_output(content)@@ -290,7 +312,7 @@ def run_eval_report_agent(title=content.title,section_count=len(content.sections),)- return _fallback_content(evaluation_name, metrics, validation_error)+ return _fallback_content(evaluation_name, metrics, validation_error, evaluation_target)_append_references_section(content)@@ -318,4 +340,9 @@ def run_eval_report_agent(team_id=team_id,evaluation_id=evaluation_id,)- return _fallback_content(evaluation_name, metrics, f"agent raised {type(e).__name__}")+ return _fallback_content(+ evaluation_name,+ metrics,+ f"agent raised {type(e).__name__}",+ evaluation_target,+ )diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.pyindex 4b86fccedaeb..f83943c553e4 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py@@ -9,6 +9,7 @@ EVAL_REPORT_SYSTEM_PROMPT = """You are an evaluation report agent for PostHog'sEvaluation: **{evaluation_name}**{evaluation_description_section}Evaluation type: {evaluation_type}+Evaluation target: {evaluation_target}{evaluation_prompt_section}**Result semantics:** {result_semantics}@@ -20,7 +21,7 @@ You build the report incrementally by calling three output tools:1. **`set_title(title)`**: call exactly once. Write one specific, scannable headline that tells the reader the main finding at a glance.2. **`add_section(title, content)`**: call 1 to {max_sections} times. The first section is the TL;DR. Prefer fewer substantive sections over filler.-3. **`add_citation(generation_id, trace_id, reason)`**: call for every example you discuss. Always call `sample_generation_details` first to verify the generation and get its `trace_id`.+3. **`add_citation(generation_id, trace_id, reason)`**: {citation_tool_instruction}## What not to do@@ -34,32 +35,24 @@ You build the report incrementally by calling three output tools:- **`get_summary_metrics()`**: outcome counts and rates for the current and previous periods. Call this first.- **`get_result_distribution_over_time(bucket="hour"|"day")`**: time-series outcome distributions. Use it to spot trends and anomalies.- **`get_top_outcome_reasons(outcome, limit)`**: grouped reasoning strings for one outcome. If omitted, outcome defaults to `{analysis_outcome}`.-- **`list_all_eval_results(max_reasoning_length=80)`**: compact overview of all results, with outcome, generation ID, score when available, and truncated reasoning.+- **`list_all_eval_results(max_reasoning_length=80)`**: compact overview of all results, with outcome, target ID, score when available, and truncated reasoning.- **`sample_eval_results(outcome="all"|{outcome_options}, limit)`**: sample evaluation rows with their full reasoning.-- **`sample_generation_details(generation_ids)`**: generation data including input, output, model, tokens, and trace ID. Call this before citing.-- **`get_generation_detail(generation_id)`**: complete data for one generation and its evaluation results.+{detail_tools_section}- **`list_recent_report_runs(since_days, limit)`**: compact index of prior runs with title, period, total runs, and result rates.- **`get_report_run(run_id)`**: full content for a prior report run.## Grounding rule-For every recurring outcome pattern or quality issue you describe:--1. Call `sample_eval_results(outcome="{analysis_outcome}")` to find candidate generation IDs. Sample `{primary_outcome}` as contrast when useful.-2. Call `sample_generation_details(generation_ids)` to inspect the actual input and output and obtain each trace ID.-3. Call `add_citation(generation_id, trace_id, reason)` for each example you use.-4. Reference the generation ID inline with single backticks so the renderer can link it.--If a generation cannot be resolved, try another example. If none resolve, report the data-quality limitation.+{grounding_rule}## Suggested workflow1. Call `get_summary_metrics()` and `list_all_eval_results()`.2. Call `get_result_distribution_over_time(bucket="hour")` or `"day"`.3. Inspect grouped reasons and sample relevant outcomes, using `{analysis_outcome}` and `{primary_outcome}` as starting points.-4. Call `sample_generation_details(...)` on 3-5 useful examples.+4. {detail_step}5. Optionally inspect recent report runs for continuity.-6. Set one title, add 1 to {max_sections} sections, and cite every discussed trace.+6. Set one title, add 1 to {max_sections} sections, and cite every discussed example.7. Return. The graph attaches the trusted metrics automatically.{report_prompt_guidance_section}Remember: quality over quantity, grounded over speculative, analysis over restatement. The reader should understand what happened and what, if anything, to do about it."""@@ -74,6 +67,7 @@ def build_eval_report_system_prompt(output_type: str,period_start: str,period_end: str,+ evaluation_target: str = "generation",report_prompt_guidance: str = "",) -> str:definition = get_outcome_definition(output_type)@@ -96,8 +90,9 @@ def build_eval_report_system_prompt(analysis_outcome = "negative"primary_outcome = "positive"elif output_type == "boolean":+ evaluated_unit = "trace" if evaluation_target == "trace" else "generation"result_semantics = (- "The evaluation returns a boolean. True means the generation satisfied the configured criteria and false "+ f"The evaluation returns a boolean. True means the {evaluated_unit} satisfied the configured criteria and false ""means it did not. A fail is not inherently bad: always interpret pass and fail through the evaluation's ""specific criteria rather than treating them as generic quality verdicts.")@@ -106,11 +101,55 @@ def build_eval_report_system_prompt(else:raise ValueError(f"Unsupported evaluation report output type: {output_type}")+ if evaluation_target == "trace":+ citation_tool_instruction = (+ "call for every trace you discuss, with an empty `generation_id`. "+ "Always call `sample_trace_details` first to verify the trace."+ )+ detail_tools_section = (+ "- **`sample_trace_details(trace_ids)`**: canonical, bounded renderings for up to 10 traces. "+ "Call this before citing.\n"+ "- **`get_trace_detail(trace_id)`**: a longer canonical rendering for one trace."+ )+ grounding_rule = f"""For every recurring outcome pattern or quality issue you describe:++1. Call `sample_eval_results(outcome=\"{analysis_outcome}\")` to find candidate trace IDs. Sample `{primary_outcome}` as contrast when useful.+2. Call `sample_trace_details(trace_ids)` to inspect the actual traces.+3. Call `add_citation(generation_id=\"\", trace_id=trace_id, reason=reason)` for each example you use.+4. Reference the trace ID inline with single backticks so the renderer can link it.++If a trace cannot be resolved, try another example. If none resolve, report the data-quality limitation."""+ detail_step = "Call `sample_trace_details(...)` on 3-5 useful examples."+ elif evaluation_target == "generation":+ citation_tool_instruction = (+ "call for every example you discuss. Always call `sample_generation_details` first to verify the "+ "generation and get its `trace_id`."+ )+ detail_tools_section = (+ "- **`sample_generation_details(generation_ids)`**: generation data including input, output, model, "+ "tokens, and trace ID. Call this before citing.\n"+ "- **`get_generation_detail(generation_id)`**: complete data for one generation and its evaluation "+ "results.\n"+ "- **`get_generation_text_repr(generation_id)`**: canonical rendering for a generation."+ )+ grounding_rule = f"""For every recurring outcome pattern or quality issue you describe:++1. Call `sample_eval_results(outcome=\"{analysis_outcome}\")` to find candidate generation IDs. Sample `{primary_outcome}` as contrast when useful.+2. Call `sample_generation_details(generation_ids)` to inspect the actual input and output and obtain each trace ID.+3. Call `add_citation(generation_id, trace_id, reason)` for each example you use.+4. Reference the generation ID inline with single backticks so the renderer can link it.++If a generation cannot be resolved, try another example. If none resolve, report the data-quality limitation."""+ detail_step = "Call `sample_generation_details(...)` on 3-5 useful examples."+ else:+ raise ValueError(f"Unsupported evaluation target: {evaluation_target}")+outcome_options = "|".join(f'"{outcome}"' for outcome in definition.outcomes)return EVAL_REPORT_SYSTEM_PROMPT.format(evaluation_name=evaluation_name,evaluation_description_section=description_section,evaluation_type=evaluation_type,+ evaluation_target=evaluation_target,evaluation_prompt_section=prompt_section,result_semantics=result_semantics,period_start=period_start,@@ -120,4 +159,8 @@ def build_eval_report_system_prompt(outcome_options=outcome_options,analysis_outcome=analysis_outcome,primary_outcome=primary_outcome,+ citation_tool_instruction=citation_tool_instruction,+ detail_tools_section=detail_tools_section,+ grounding_rule=grounding_rule,+ detail_step=detail_step,)diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.pyindex 7096c102a0c5..6251dddd187c 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py@@ -1,11 +1,12 @@"""Dataclasses for evaluation report content, metrics, and citations.The v2 schema splits the report into:+- `evaluation_target`: the evaluated unit (`generation` or `trace`)- `metrics`: structured numeric data computed mechanically from ClickHouse,the agent cannot fabricate these- `title`: the agent's punchline headline (required, one line)- `sections`: 1-6 agent-chosen titled markdown sections-- `citations`: structured trace references (generation_id + trace_id + reason)+- `citations`: structured target references (generation_id + trace_id + reason)This separation lets downstream consumers (signals, inbox, coding agents) query`metrics` and `citations` without parsing prose, and lets the agent focus on@@ -16,6 +17,7 @@ from dataclasses import dataclass, fieldfrom typing import Literal, overloadfrom posthog.temporal.ai_observability.eval_reports.output_types import get_outcome_definition+from posthog.temporal.ai_observability.eval_reports.targets import GENERATION_TARGET, resolve_evaluation_target# Hard cap on the number of agent-chosen sections. Prevents section sprawl and# keeps reports scannable. The agent is also instructed to lean lean — quality@@ -65,12 +67,12 @@ def calculate_boolean_pass_rate(counts: dict[str, int], *, empty_as_none: bool =@dataclassclass Citation:- """A trace reference cited by the agent to ground a specific finding.+ """An inspected example cited by the agent to ground a specific finding.- Stores both generation_id and trace_id up front so the viewer can construct- correct trace URLs without a runtime lookup. `reason` is short free-form- text (e.g. "high_cost", "refusal", "regression_14:00") the agent uses to- categorize why the trace is interesting.+ Generation reports store both IDs so viewers can link to the generation+ without a runtime lookup. Trace reports leave `generation_id` empty and use+ `trace_id` as the reference. `reason` is a short free-form category for why+ the example is interesting."""generation_id: str@@ -285,13 +287,18 @@ def normalize_report_content_payload(data: dict) -> dict:class EvalReportContent:"""Top-level report content. Stored in EvaluationReportRun.content JSONField."""+ evaluation_target: str = GENERATION_TARGETtitle: str = ""sections: list[ReportSection] = field(default_factory=list)citations: list[Citation] = field(default_factory=list)metrics: EvalReportMetrics = field(default_factory=EvalReportMetrics)+ def __post_init__(self) -> None:+ self.evaluation_target = resolve_evaluation_target(self.evaluation_target)+def to_dict(self) -> dict:return {+ "evaluation_target": self.evaluation_target,"title": self.title,"sections": [s.to_dict() for s in self.sections],"citations": [c.to_dict() for c in self.citations],@@ -301,6 +308,7 @@ class EvalReportContent:@staticmethoddef from_dict(data: dict) -> "EvalReportContent":return EvalReportContent(+ evaluation_target=data.get("evaluation_target", GENERATION_TARGET),title=data.get("title", ""),sections=[ReportSection.from_dict(s) for s in data.get("sections", [])],citations=[Citation.from_dict(c) for c in data.get("citations", [])],diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py b/posthog/temporal/ai_observability/eval_reports/report_agent/state.pyindex 8a02b1cfea41..3949187ee9af 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py@@ -28,6 +28,7 @@ class EvalReportAgentState(TypedDict):evaluation_description: strevaluation_prompt: strevaluation_type: str+ evaluation_target: stroutput_type: strperiod_start: strperiod_end: str@@ -36,3 +37,4 @@ class EvalReportAgentState(TypedDict):# Working state — the agent builds this up via tool callsreport: EvalReportContent+ trace_id_allowlist: list[str]diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.pyindex 4a661f6feefc..782541b1968a 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_graph.py@@ -23,12 +23,15 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (class TestSystemPromptFormat(SimpleTestCase):- def _build_prompt(self, output_type: str = "boolean", guidance: str = "") -> str:+ def _build_prompt(+ self, output_type: str = "boolean", guidance: str = "", evaluation_target: str = "generation"+ ) -> str:return build_eval_report_system_prompt(evaluation_name="Test Eval",evaluation_description="foo",evaluation_type="llm_judge",evaluation_prompt="criteria",+ evaluation_target=evaluation_target,output_type=output_type,period_start="2026-04-08T14:00:00+00:00",period_end="2026-04-08T15:00:00+00:00",@@ -54,6 +57,16 @@ class TestSystemPromptFormat(SimpleTestCase):self.assertIn('outcome="all"|"positive"|"neutral"|"negative"', formatted)self.assertNotIn("pass rate", formatted.lower())+ def test_trace_prompt_uses_only_trace_detail_workflow(self):+ formatted = self._build_prompt(evaluation_target="trace")++ self.assertIn("Evaluation target: trace", formatted)+ self.assertIn("sample_trace_details", formatted)+ self.assertIn("get_trace_detail", formatted)+ self.assertIn('generation_id=""', formatted)+ self.assertNotIn("sample_generation_details", formatted)+ self.assertIn("trace satisfied the configured criteria", formatted)+class TestComputeMetrics(SimpleTestCase):@patch.object(graph, "_fetch_period_summary")@@ -91,6 +104,15 @@ class TestFallbackContent(SimpleTestCase):self.assertIn("agent timed out", content.sections[0].content)self.assertEqual(content.metrics, metrics)+ def test_trace_zero_runs_uses_trace_specific_ingestion_hint(self):+ metrics = EvalReportMetrics(total_runs=0)++ content = _fallback_content("Trace quality", metrics, "agent timed out", evaluation_target="trace")++ self.assertIn("trace evaluation results", content.sections[0].content)+ self.assertNotIn("$ai_generation", content.sections[0].content)+ self.assertEqual(content.evaluation_target, "trace")+def test_populated_metrics_stable_trend(self):metrics = EvalReportMetrics(total_runs=100,@@ -229,6 +251,17 @@ class TestAppendReferencesSection(SimpleTestCase):self.assertEqual(content.sections[-1].title, "References")self.assertIn("g1", content.sections[-1].content)+ def test_trace_reference_uses_trace_id_when_generation_id_is_empty(self):+ content = EvalReportContent(+ title="t",+ sections=[ReportSection(title="S1", content="c1")],+ citations=[Citation(generation_id="", trace_id="customer-trace/42", reason="r1")],+ )++ _append_references_section(content)++ self.assertIn("customer-trace/42", content.sections[-1].content)+def test_references_does_not_displace_content_at_max_sections(self):# Regression: previously the auto-appended References section replaced# the agent's final section when agent produced MAX_REPORT_SECTIONS.diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.pyindex faa7f7ad5ceb..c2211aa672f0 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_schema.py@@ -218,6 +218,7 @@ class TestEvalReportContent(SimpleTestCase):def test_roundtrip(self):original = EvalReportContent(+ evaluation_target="trace",title="T",sections=[ReportSection(title="S", content="C")],citations=[Citation(generation_id="g", trace_id="t", reason="r")],@@ -229,6 +230,7 @@ class TestEvalReportContent(SimpleTestCase):self.assertEqual(roundtripped.sections[0], original.sections[0])self.assertEqual(roundtripped.citations[0], original.citations[0])self.assertEqual(roundtripped.metrics, original.metrics)+ self.assertEqual(roundtripped.evaluation_target, "trace")class TestSectionBounds(SimpleTestCase):diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.pyindex 973e432ea067..65dbc07098cc 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py@@ -2,9 +2,10 @@import jsonimport datetime as dt+from typing import NotRequired, TypedDictfrom posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCasefrom django.utils import timezone@@ -23,9 +24,14 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (_widened_ts_window,add_citation,add_section,+ get_eval_report_tools,get_report_run,get_summary_metrics,+ get_trace_detail,+ list_all_eval_results,list_recent_report_runs,+ sample_eval_results,+ sample_trace_details,set_title,)@@ -39,11 +45,41 @@ _add_citation_fn = add_citation.func # type: ignore[attr-defined]_list_recent_report_runs_fn = list_recent_report_runs.func # type: ignore[attr-defined]_get_report_run_fn = get_report_run.func # type: ignore[attr-defined]_get_summary_metrics_fn = get_summary_metrics.func # type: ignore[attr-defined]---def _state_with_empty_report() -> dict:- """Build a minimal state dict with an empty EvalReportContent (matches runtime)."""- return {"report": EvalReportContent()}+_list_all_eval_results_fn = list_all_eval_results.func # type: ignore[attr-defined]+_sample_eval_results_fn = sample_eval_results.func # type: ignore[attr-defined]+_sample_trace_details_fn = sample_trace_details.func # type: ignore[attr-defined]+_get_trace_detail_fn = get_trace_detail.func # type: ignore[attr-defined]+++class _ReportToolState(TypedDict):+ report: EvalReportContent+ trace_id_allowlist: list[str]+ evaluation_target: NotRequired[str]+ team_id: NotRequired[int]+ evaluation_id: NotRequired[str]+ output_type: NotRequired[str]+ period_start: NotRequired[str]+ period_end: NotRequired[str]+++def _state_with_empty_report(*, evaluation_target: str | None = None) -> _ReportToolState:+ state: _ReportToolState = {"report": EvalReportContent(), "trace_id_allowlist": []}+ if evaluation_target is not None:+ state["evaluation_target"] = evaluation_target+ return state+++def _trace_report_tool_state() -> _ReportToolState:+ return {+ "report": EvalReportContent(),+ "trace_id_allowlist": [],+ "evaluation_target": "trace",+ "team_id": 7,+ "evaluation_id": "eval-id",+ "output_type": "boolean",+ "period_start": "2026-04-08T14:00:00+00:00",+ "period_end": "2026-04-08T15:00:00+00:00",+ }class TestChTs(SimpleTestCase):@@ -101,6 +137,7 @@ class TestSummaryMetrics(SimpleTestCase):state = {"team_id": 1,"evaluation_id": "eval-id",+ "evaluation_target": "trace","output_type": "boolean","period_start": "2026-04-08T14:00:00+00:00","period_end": "2026-04-08T15:00:00+00:00",@@ -114,6 +151,8 @@ class TestSummaryMetrics(SimpleTestCase):{"pass": 80.0, "fail": 18.0, "na": 2.0},)self.assertEqual(result["current_period"]["pass_rate"], 81.63)+ for call in mock_execute_hogql.call_args_list:+ self.assertIn("properties.$ai_target_type = 'trace_id'", call.args[1])@patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")def test_boolean_current_period_preserves_zero_pass_rate_when_no_results_are_applicable(self, mock_execute_hogql):@@ -167,6 +206,158 @@ class TestSummaryMetrics(SimpleTestCase):self.assertNotIn("properties.$ai_evaluation_result = true", current_query)+class TestTargetAwareEvalResults(SimpleTestCase):+ def _state(self, evaluation_target: str) -> dict:+ return {+ "team_id": 1,+ "evaluation_id": "eval-id",+ "evaluation_target": evaluation_target,+ "output_type": "boolean",+ "period_start": "2026-04-08T14:00:00+00:00",+ "period_end": "2026-04-08T15:00:00+00:00",+ "trace_id_allowlist": [],+ }++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ def test_sample_uses_new_target_id_with_legacy_fallback_and_target_specific_key(self, mock_execute_hogql):+ mock_execute_hogql.side_effect = [+ [[_VALID_GEN_ID, True, "useful", True, None]],+ [["customer-trace/42", False, "failed", True, None]],+ ]++ generation_state = self._state("generation")+ trace_state = self._state("trace")+ generation_result = json.loads(_sample_eval_results_fn(state=generation_state))+ trace_result = json.loads(_sample_eval_results_fn(state=trace_state))++ self.assertEqual(generation_result[0]["generation_id"], _VALID_GEN_ID)+ self.assertNotIn("trace_id", generation_result[0])+ self.assertEqual(trace_result[0]["trace_id"], "customer-trace/42")+ self.assertNotIn("generation_id", trace_result[0])+ self.assertEqual(generation_state["trace_id_allowlist"], [])+ self.assertEqual(trace_state["trace_id_allowlist"], ["customer-trace/42"])+ for call in mock_execute_hogql.call_args_list:+ query = call.args[1]+ self.assertIn("properties.$ai_target_id", query)+ self.assertIn("properties.$ai_target_event_id", query)+ generation_query = mock_execute_hogql.call_args_list[0].args[1]+ trace_query = mock_execute_hogql.call_args_list[1].args[1]+ self.assertIn("isNull(properties.$ai_target_type)", generation_query)+ self.assertIn("properties.$ai_target_type = 'trace_id'", trace_query)++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ def test_list_uses_unified_target_id_for_trace_results(self, mock_execute_hogql):+ mock_execute_hogql.side_effect = [+ [[1]],+ [["customer-trace/42", False, True, None, "failed criteria"]],+ ]++ state = self._state("trace")+ result = _list_all_eval_results_fn(state=state)++ self.assertIn("customer-trace/42", result)+ self.assertEqual(state["trace_id_allowlist"], ["customer-trace/42"])+ query = mock_execute_hogql.call_args_list[1].args[1]+ self.assertIn("properties.$ai_target_id", query)+ self.assertIn("properties.$ai_target_event_id", query)+++class TestTraceDetailTools(SimpleTestCase):+ def _state(self) -> dict:+ return {+ "team_id": 7,+ "evaluation_id": "eval-id",+ "evaluation_target": "trace",+ "output_type": "boolean",+ "period_start": "2026-04-08T14:00:00+00:00",+ "period_end": "2026-04-08T15:00:00+00:00",+ "trace_id_allowlist": [],+ }++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._fetch_and_format_trace")+ def test_sample_accepts_evaluated_opaque_trace_ids_and_bounds_each_rendering(+ self, mock_fetch: MagicMock, mock_execute_hogql: MagicMock+ ) -> None:+ mock_fetch.return_value = MagicMock(text_repr="x" * 5_000, event_count=4)+ trace_id = " customer/trace:alpha 42 "+ mock_execute_hogql.return_value = [[trace_id, True, "matched", True, None]]+ state = self._state()+ _sample_eval_results_fn(state=state)++ result = json.loads(_sample_trace_details_fn(state=state, trace_ids=[trace_id]))++ self.assertEqual(result[0]["trace_id"], trace_id)+ self.assertEqual(len(result[0]["text"]), 3_000)+ self.assertEqual(mock_fetch.call_args.kwargs["trace_id"], trace_id)+ self.assertEqual(mock_fetch.call_args.kwargs["max_length"], 3_000)+ self.assertEqual(mock_fetch.call_args.kwargs["max_trace_events"], 50)+ self.assertEqual(mock_fetch.call_args.kwargs["max_raw_trace_size"], 2_000_000)+ self.assertEqual(mock_fetch.call_args.kwargs["window_start"], "2020-01-01T00:00:00+00:00")+ self.assertEqual(mock_fetch.call_args.kwargs["window_end"], "2099-01-01T00:00:00+00:00")+ mock_execute_hogql.assert_called_once()++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools.logger")+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._fetch_and_format_trace")+ def test_sample_continues_after_one_trace_fails(self, mock_fetch: MagicMock, _mock_logger: MagicMock) -> None:+ state = self._state()+ state["trace_id_allowlist"] = ["failing-trace", "healthy-trace"]+ mock_fetch.side_effect = [+ RuntimeError("trace query exceeded backend limits"),+ MagicMock(text_repr="healthy trace", event_count=2),+ ]++ result = json.loads(_sample_trace_details_fn(state=state, trace_ids=["failing-trace", "healthy-trace"]))++ self.assertEqual(+ result,+ [+ {"trace_id": "failing-trace", "error": "Trace could not be inspected"},+ {"trace_id": "healthy-trace", "event_count": 2, "text": "healthy trace"},+ ],+ )++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._fetch_and_format_trace")+ def test_deep_dive_rejects_trace_not_returned_by_evaluation_query(+ self, mock_fetch: MagicMock, mock_execute_hogql: MagicMock+ ) -> None:+ state = self._state()+ mock_execute_hogql.return_value = [["allowed-trace", True, "matched", True, None]]+ _sample_eval_results_fn(state=state)+ mock_execute_hogql.reset_mock()++ result = json.loads(_get_trace_detail_fn(state=state, trace_id="unrelated-trace"))++ self.assertEqual(+ result,+ {"trace_id": "unrelated-trace", "error": "Trace ID is not available for this evaluation report"},+ )+ mock_fetch.assert_not_called()+ mock_execute_hogql.assert_not_called()++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._fetch_and_format_trace")+ def test_deep_dive_rejects_oversized_trace_id_without_querying(+ self, mock_fetch: MagicMock, mock_execute_hogql: MagicMock+ ) -> None:+ result = json.loads(_get_trace_detail_fn(state=self._state(), trace_id="x" * 256))++ self.assertEqual(result, {"error": "Invalid trace ID"})+ mock_fetch.assert_not_called()+ mock_execute_hogql.assert_not_called()++ def test_target_specific_tool_sets_do_not_expose_irrelevant_detail_tools(self):+ generation_tools = {tool.name for tool in get_eval_report_tools("generation")}+ trace_tools = {tool.name for tool in get_eval_report_tools("trace")}++ self.assertIn("sample_generation_details", generation_tools)+ self.assertNotIn("sample_trace_details", generation_tools)+ self.assertIn("sample_trace_details", trace_tools)+ self.assertIn("get_trace_detail", trace_tools)+ self.assertNotIn("sample_generation_details", trace_tools)++class TestUuidRegex(SimpleTestCase):def test_matches_canonical_uuid(self):self.assertIsNotNone(_UUID_RE.fullmatch("12345678-1234-1234-1234-123456789abc"))@@ -290,7 +481,7 @@ class TestAddCitation(SimpleTestCase):self.assertIn("Error", result)self.assertEqual(state["report"].citations, [])- def test_rejects_non_uuid_trace_id(self):+ def test_accepts_opaque_trace_id(self):state = _state_with_empty_report()result = _add_citation_fn(state=state,@@ -298,6 +489,66 @@ class TestAddCitation(SimpleTestCase):trace_id="also-not-a-uuid",reason="r",)+ self.assertNotIn("Error", result)+ self.assertEqual(state["report"].citations[0].trace_id, "also-not-a-uuid")++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ def test_trace_target_allows_evaluated_trace_with_empty_generation_id(self, mock_execute_hogql: MagicMock) -> None:+ state = _trace_report_tool_state()+ mock_execute_hogql.return_value = [["customer/trace:42", True, "matched", True, None]]+ _sample_eval_results_fn(state=state)+ mock_execute_hogql.reset_mock()+ result = _add_citation_fn(+ state=state,+ generation_id="",+ trace_id="customer/trace:42",+ reason="failed criteria",+ )++ self.assertNotIn("Error", result)+ self.assertEqual(+ state["report"].citations[0],+ Citation(generation_id="", trace_id="customer/trace:42", reason="failed criteria"),+ )+ mock_execute_hogql.assert_not_called()++ @patch("posthog.temporal.ai_observability.eval_reports.report_agent.tools._execute_hogql")+ def test_trace_target_rejects_citation_not_returned_by_evaluation_query(+ self, mock_execute_hogql: MagicMock+ ) -> None:+ state = _trace_report_tool_state()+ mock_execute_hogql.return_value = [["allowed-trace", True, "matched", True, None]]+ _sample_eval_results_fn(state=state)+ mock_execute_hogql.reset_mock()++ result = _add_citation_fn(+ state=state,+ generation_id="",+ trace_id="unrelated-trace",+ reason="failed criteria",+ )++ self.assertIn("Error", result)+ self.assertEqual(state["report"].citations, [])+ mock_execute_hogql.assert_not_called()++ def test_trace_target_rejects_generation_id(self):+ state = _state_with_empty_report(evaluation_target="trace")++ result = _add_citation_fn(+ state=state,+ generation_id=_VALID_GEN_ID,+ trace_id="customer/trace:42",+ reason="failed criteria",+ )++ self.assertIn("Error", result)+ self.assertEqual(state["report"].citations, [])++ def test_rejects_trace_id_with_control_characters(self):+ state = _state_with_empty_report(evaluation_target="trace")+ result = _add_citation_fn(state=state, generation_id="", trace_id="trace\nother", reason="r")+self.assertIn("Error", result)self.assertEqual(state["report"].citations, [])@@ -407,6 +658,28 @@ class TestListAndGetReportRun(BaseTest):self.assertNotIn("result_counts", result["metadata"])self.assertNotIn("result_rates", result["metadata"])+ def test_history_is_scoped_to_the_current_evaluation_target(self):+ now = timezone.now()+ trace_run = self.EvaluationReportRun.objects.create(+ report=self.report,+ content={"evaluation_target": "trace", "title": "Trace report", "sections": []},+ metadata={"pass_rate": 50.0, "total_runs": 2},+ period_start=now - dt.timedelta(hours=2),+ period_end=now - dt.timedelta(hours=1),+ )++ generation_runs = json.loads(_list_recent_report_runs_fn(state=self.state))+ trace_state = {**self.state, "evaluation_target": "trace"}+ trace_runs = json.loads(_list_recent_report_runs_fn(state=trace_state))++ self.assertNotIn(str(trace_run.id), {run["run_id"] for run in generation_runs})+ self.assertEqual([run["run_id"] for run in trace_runs], [str(trace_run.id)])+ self.assertIn("error", json.loads(_get_report_run_fn(state=self.state, run_id=str(trace_run.id))))+ self.assertEqual(+ json.loads(_get_report_run_fn(state=trace_state, run_id=str(trace_run.id)))["content"]["title"],+ "Trace report",+ )+def test_list_includes_back_to_back_previous_run(self):# Regression: period_end exactly equal to the current period_start used to be# excluded by a strict `lt` filter, dropping the immediately previous report —diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.pyindex 613297b92fcf..49f2febf08b7 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py@@ -12,7 +12,10 @@ import jsonfrom datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING, Annotated-from langchain_core.tools import tool+from django.db.models import Q++import structlog+from langchain_core.tools import BaseTool, toolfrom langgraph.prebuilt import InjectedStatefrom posthog.hogql import ast@@ -30,16 +33,75 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (normalize_metrics_payload,normalize_report_content_payload,)+from posthog.temporal.ai_observability.eval_reports.targets import (+ GENERATION_TARGET,+ TRACE_TARGET,+ resolve_evaluation_target,+ target_event_predicate,+)+from posthog.temporal.ai_observability.trace_summarization.constants import (+ MAX_TRACE_EVENTS_LIMIT,+ MAX_TRACE_PROPERTIES_SIZE,+)+from posthog.temporal.ai_observability.trace_summarization.fetch_and_format import _fetch_and_format_traceif TYPE_CHECKING:from posthog.models import Team-# Strict UUID match for validating IDs before string-interpolating into HogQL-# and before storing in Citation. Generation IDs reach this code from the LLM,-# which can relay arbitrary `$ai_target_event_id` property values set by user-# instrumentation. Trace IDs have the same trust boundary.+logger = structlog.get_logger(__name__)++# Strict UUID match for generation IDs relayed by the LLM. Trace IDs are opaque,+# so they use bounded validation and always flow through AST constants instead._UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")+_TARGET_ID_EXPRESSION = "coalesce(nullIf(properties.$ai_target_id, ''), properties.$ai_target_event_id)"+_MAX_TRACE_ID_LENGTH = 255+_MAX_TRACE_SAMPLE_IDS = 10+_MAX_TRACE_SAMPLE_CHARS = 3_000+_MAX_TRACE_DETAIL_CHARS = 12_000+++def _target_id_key(state: dict) -> str:+ return "trace_id" if resolve_evaluation_target(state.get("evaluation_target")) == TRACE_TARGET else "generation_id"+++def _normalize_trace_id(trace_id: object) -> str | None:+ """Validate an opaque trace ID without assuming it is a UUID."""+ if not isinstance(trace_id, str):+ return None+ if not trace_id.strip() or len(trace_id) > _MAX_TRACE_ID_LENGTH:+ return None+ if any(ord(character) < 32 or ord(character) == 127 for character in trace_id):+ return None+ return trace_id+++def _remember_returned_trace_ids(state: dict, target_ids: list[object]) -> None:+ if resolve_evaluation_target(state.get("evaluation_target")) != TRACE_TARGET:+ return++ allowlist = state.get("trace_id_allowlist")+ if not isinstance(allowlist, list):+ return++ known_trace_ids = set(allowlist)+ for target_id in target_ids:+ trace_id = _normalize_trace_id(target_id)+ if trace_id is not None and trace_id not in known_trace_ids:+ allowlist.append(trace_id)+ known_trace_ids.add(trace_id)+++def _is_returned_trace_id(state: dict, trace_id: str) -> bool:+ allowlist = state.get("trace_id_allowlist")+ return isinstance(allowlist, list) and trace_id in allowlist+++def _report_run_target_filter(evaluation_target: str) -> Q:+ if resolve_evaluation_target(evaluation_target) == TRACE_TARGET:+ return Q(content__evaluation_target=TRACE_TARGET)+ return Q(content__evaluation_target=GENERATION_TARGET) | Q(content__evaluation_target__isnull=True)+def _ch_ts(iso_str: str) -> datetime:"""Parse an ISO-8601 timestamp and return a UTC-aware datetime.@@ -57,8 +119,8 @@ def _ch_ts(iso_str: str) -> datetime:return dt.astimezone(UTC)-_WIDENED_TS_START_SENTINEL = "2020-01-01T00:00:00+00:00"-_WIDENED_TS_END_SENTINEL = "2099-01-01T00:00:00+00:00"+_TARGET_LOOKUP_TS_START_SENTINEL = "2020-01-01T00:00:00+00:00"+_TARGET_LOOKUP_TS_END_SENTINEL = "2099-01-01T00:00:00+00:00"def _resolve_output_type(output_type: str | None) -> tuple[str, EvaluationReportOutcomeDefinition]:@@ -104,21 +166,20 @@ def _outcome_for_result(output_type: str, result: object, applicable: object = Ndef _widened_ts_window(state: dict) -> tuple[datetime, datetime]:- """Return (ts_start, ts_end) datetimes widened for generation-event lookups.+ """Return (ts_start, ts_end) datetimes widened for target lookups.- Generations predate their evals, so widen the start by 7 days to catch the- generating event. End is period_end + 1 day buffer for eval lag. Falls back- to wide sentinel bounds if state has malformed/missing timestamps so- partition pruning still has a usable range.+ Target events can predate their evaluations, so widen the start by 7 days.+ End is period_end + 1 day for evaluation lag. Falls back to wide sentinel+ bounds if state has malformed or missing timestamps."""try:ts_start = _ch_ts((datetime.fromisoformat(state["period_start"]) - timedelta(days=7)).isoformat())except (ValueError, TypeError, KeyError):- ts_start = _ch_ts(_WIDENED_TS_START_SENTINEL)+ ts_start = _ch_ts(_TARGET_LOOKUP_TS_START_SENTINEL)try:ts_end = _ch_ts((datetime.fromisoformat(state["period_end"]) + timedelta(days=1)).isoformat())except (ValueError, TypeError, KeyError):- ts_end = _ch_ts(_WIDENED_TS_END_SENTINEL)+ ts_end = _ch_ts(_TARGET_LOOKUP_TS_END_SENTINEL)return ts_start, ts_end@@ -186,6 +247,7 @@ def _fetch_period_summary(ts_start: datetime,ts_end: datetime,definition: EvaluationReportOutcomeDefinition,+ evaluation_target: str = GENERATION_TARGET,) -> tuple[dict[str, int], int]:"""Fetch trusted outcome counts and total runs for one time window."""rows = _execute_hogql(@@ -197,6 +259,7 @@ def _fetch_period_summary(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {definition.event_predicate}+ AND {target_event_predicate(evaluation_target)}AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}""",@@ -244,10 +307,13 @@ def get_summary_metrics(ts_end = _ch_ts(state["period_end"])ts_prev_start = _ch_ts(state["previous_period_start"])output_type, definition = _resolve_output_type(state.get("output_type"))+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))- result_counts, total = _fetch_period_summary(team_id, evaluation_id, ts_start, ts_end, definition)+ result_counts, total = _fetch_period_summary(+ team_id, evaluation_id, ts_start, ts_end, definition, evaluation_target+ )previous_result_counts, previous_total = _fetch_period_summary(- team_id, evaluation_id, ts_prev_start, ts_start, definition+ team_id, evaluation_id, ts_prev_start, ts_start, definition, evaluation_target)result = {@@ -277,6 +343,7 @@ def get_result_distribution_over_time(ts_start = _ch_ts(state["period_start"])ts_end = _ch_ts(state["period_end"])output_type, definition = _resolve_output_type(state.get("output_type"))+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))# Whitelisted truncation function — `bucket` is an LLM-controlled arg, so pick# from a fixed set rather than interpolating arbitrary identifiers into SQL.@@ -292,6 +359,7 @@ def get_result_distribution_over_time(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {definition.event_predicate}+ AND {target_event_predicate(evaluation_target)}AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}GROUP BY bucket@@ -322,10 +390,10 @@ def list_all_eval_results() -> str:"""Get a compact overview of evaluation results in the period.- Returns up to 500 results as condensed rows: outcome, generation_id, and+ Returns up to 500 results as condensed rows: outcome, target ID, andtruncated reasoning. When there are more than 500 results, returns a randomsample. Use this as your first scan to spot patterns before drilling into- specific examples with sample_generation_details.+ specific examples with the target-specific detail tool.Args:max_reasoning_length: Truncate reasoning strings to this many characters (default 80)@@ -335,6 +403,7 @@ def list_all_eval_results(ts_start = _ch_ts(state["period_start"])ts_end = _ch_ts(state["period_end"])output_type, definition = _resolve_output_type(state.get("output_type"))+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))shared_placeholders = {"evaluation_id": ast.Constant(value=evaluation_id),@@ -351,6 +420,7 @@ def list_all_eval_results(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {definition.event_predicate}+ AND {target_event_predicate(evaluation_target)}AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}""",@@ -367,7 +437,7 @@ def list_all_eval_results(team_id,f"""SELECT- properties.$ai_target_event_id as generation_id,+ {_TARGET_ID_EXPRESSION} as target_id,{definition.result_expression} as result,{definition.applicable_expression} as applicable,{definition.score_expression} as score,@@ -376,6 +446,7 @@ def list_all_eval_results(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {definition.event_predicate}+ AND {target_event_predicate(evaluation_target)}AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}{order_clause}@@ -383,17 +454,18 @@ def list_all_eval_results(""",placeholders=shared_placeholders,)+ _remember_returned_trace_ids(state, [row[0] for row in rows if row])max_reasoning_length = min(max(20, max_reasoning_length), 200)lines = []for row in rows:- gen_id = str(row[0]) if row[0] else "?"+ target_id = str(row[0]) if row[0] else "?"outcome = _outcome_for_result(output_type, row[1], row[2]) or "?"score = f" ({row[3]:.2f})" if isinstance(row[3], int | float) else ""reasoning = (row[4] or "")[:max_reasoning_length]if row[4] and len(row[4]) > max_reasoning_length:reasoning += "..."- lines.append(f"{outcome}{score} | {gen_id} | {reasoning}")+ lines.append(f"{outcome}{score} | {target_id} | {reasoning}")if is_sampled:header = f"Total: {total_count} results (showing random sample of {len(lines)})\n"@@ -408,7 +480,7 @@ def sample_eval_results(outcome: str = "all",limit: int = 50,) -> str:- """Sample evaluation runs with generation ID, outcome, score, and reasoning.+ """Sample evaluation runs with target ID, outcome, score, and reasoning.Call multiple times with different filters to understand patterns.@@ -422,6 +494,7 @@ def sample_eval_results(ts_start = _ch_ts(state["period_start"])ts_end = _ch_ts(state["period_end"])output_type, definition = _resolve_output_type(state.get("output_type"))+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))# Whitelisted filter fragment: outcome predicates come only from the trusted# outcome definition, never directly from the LLM-controlled argument.@@ -436,7 +509,7 @@ def sample_eval_results(team_id,f"""SELECT- properties.$ai_target_event_id as generation_id,+ {_TARGET_ID_EXPRESSION} as target_id,{definition.result_expression} as result,properties.$ai_evaluation_reasoning as reasoning,{definition.applicable_expression} as applicable,@@ -445,6 +518,7 @@ def sample_eval_results(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {definition.event_predicate}+ AND {target_event_predicate(evaluation_target)}AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}{filter_clause}@@ -458,11 +532,13 @@ def sample_eval_results("limit": ast.Constant(value=limit),},)+ _remember_returned_trace_ids(state, [row[0] for row in rows if row])+ target_id_key = _target_id_key(state)result = []for row in rows:entry = {- "generation_id": str(row[0]) if row[0] else "",+ target_id_key: str(row[0]) if row[0] else "","outcome": _outcome_for_result(output_type, row[1], row[3]),"reasoning": row[2] or "",}@@ -833,6 +909,96 @@ def get_generation_text_repr(return text_repr+def _fetch_trace_detail(state: dict, trace_id: object, max_length: int) -> dict:+ normalized_trace_id = _normalize_trace_id(trace_id)+ if normalized_trace_id is None:+ return {"error": "Invalid trace ID"}++ if not _is_returned_trace_id(state, normalized_trace_id):+ return {+ "trace_id": normalized_trace_id,+ "error": "Trace ID is not available for this evaluation report",+ }++ # The report period locates evaluation events, not the boundaries of their target traces.+ # Trace IDs are indexed, so fetch the complete trace instead of silently clipping long traces.+ try:+ result = _fetch_and_format_trace(+ trace_id=normalized_trace_id,+ team_id=state["team_id"],+ window_start=_TARGET_LOOKUP_TS_START_SENTINEL,+ window_end=_TARGET_LOOKUP_TS_END_SENTINEL,+ max_length=max_length,+ max_trace_events=MAX_TRACE_EVENTS_LIMIT,+ max_raw_trace_size=MAX_TRACE_PROPERTIES_SIZE,+ )+ except Exception as error:+ logger.exception(+ "llma_eval_reports_trace_detail_failed",+ trace_id=normalized_trace_id,+ team_id=state["team_id"],+ error_type=type(error).__name__,+ )+ return {"trace_id": normalized_trace_id, "error": "Trace could not be inspected"}++ if result is None:+ return {"trace_id": normalized_trace_id, "error": "Trace not found"}+ if result.text_repr is None:+ return {+ "trace_id": normalized_trace_id,+ "event_count": result.event_count,+ "error": "Trace is too large to inspect",+ }+ return {+ "trace_id": normalized_trace_id,+ "event_count": result.event_count,+ "text": result.text_repr[:max_length],+ }+++@tool+def sample_trace_details(+ state: Annotated[dict, InjectedState],+ trace_ids: list[str],+) -> str:+ """Inspect a small set of trace evaluation targets using the canonical trace rendering.++ Each trace is capped at 3,000 characters and at most 10 unique trace IDs are+ fetched. Trace IDs are opaque strings and do not need to be UUIDs.++ Args:+ trace_ids: Trace IDs returned by sample_eval_results (max 10)+ """+ details: list[dict] = []+ seen: set[str] = set()+ for trace_id in trace_ids[:_MAX_TRACE_SAMPLE_IDS]:+ normalized_trace_id = _normalize_trace_id(trace_id)+ if normalized_trace_id is None:+ details.append({"error": "Invalid trace ID"})+ continue+ if normalized_trace_id in seen:+ continue+ seen.add(normalized_trace_id)+ details.append(_fetch_trace_detail(state, normalized_trace_id, _MAX_TRACE_SAMPLE_CHARS))+ return json.dumps(details, indent=2)+++@tool+def get_trace_detail(+ state: Annotated[dict, InjectedState],+ trace_id: str,+) -> str:+ """Deep-dive into one trace using the canonical, line-numbered trace rendering.++ The returned trace text is capped at 12,000 characters. Trace IDs are opaque+ strings and do not need to be UUIDs.++ Args:+ trace_id: Trace ID returned by sample_eval_results+ """+ return json.dumps(_fetch_trace_detail(state, trace_id, _MAX_TRACE_DETAIL_CHARS), indent=2)++@tooldef list_recent_report_runs(state: Annotated[dict, InjectedState],@@ -856,6 +1022,7 @@ def list_recent_report_runs(since_days = min(max(1, since_days), 365)limit = min(max(1, limit), 200)evaluation_id = state["evaluation_id"]+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))try:period_start = datetime.fromisoformat(state["period_start"])@@ -871,7 +1038,9 @@ def list_recent_report_runs(# stored yet at tool-call time, so this can't accidentally pull it in.period_end__lte=period_start,period_end__gte=since,- ).order_by("-period_end")[:limit]+ )+ runs = runs.filter(_report_run_target_filter(evaluation_target))+ runs = runs.order_by("-period_end")[:limit]result = []for run in runs:@@ -922,8 +1091,11 @@ def get_report_run(# Scope to the current evaluation so the agent can't read runs from another eval.evaluation_id = state["evaluation_id"]+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))+ runs = EvaluationReportRun.objects.filter(id=run_id, report__evaluation_id=evaluation_id)+ runs = runs.filter(_report_run_target_filter(evaluation_target))try:- run = EvaluationReportRun.objects.get(id=run_id, report__evaluation_id=evaluation_id)+ run = runs.get()except EvaluationReportRun.DoesNotExist:return json.dumps({"error": f"Run {run_id} not found for this evaluation"})@@ -962,6 +1134,7 @@ def get_top_outcome_reasons(ts_start = _ch_ts(state["period_start"])ts_end = _ch_ts(state["period_end"])output_type, definition = _resolve_output_type(state.get("output_type"))+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))selected_outcome = outcome or ("negative" if output_type == "sentiment" else "fail")outcome_predicate = definition.outcome_predicates.get(selected_outcome)if outcome_predicate is None:@@ -977,6 +1150,7 @@ def get_top_outcome_reasons(WHERE event = '$ai_evaluation'AND properties.$ai_evaluation_id = {{evaluation_id}}AND {definition.event_predicate}+ AND {target_event_predicate(evaluation_target)}AND {outcome_predicate}AND timestamp >= {{ts_start}}AND timestamp < {{ts_end}}@@ -1050,8 +1224,8 @@ def add_section(a separate metrics block. Focus on analysis, comparisons,hypotheses, and concrete recommendations.- Reference specific traces by calling add_citation separately with the- generation_id + trace_id from sample_generation_details.+ Reference specific examples by calling add_citation separately with the IDs+ returned by the target-specific detail tool.Args:title: Short title for this section (e.g. "Summary", "Volume drop at 14:00").@@ -1088,39 +1262,61 @@ def add_citation("""Cite a specific trace that supports a finding in the report.Citations are structured references that downstream consumers (signals, inbox,- coding agents) can filter on without parsing prose. Always call- sample_generation_details first to verify the generation exists and to get- its trace_id.+ coding agents) can filter on without parsing prose. Verify the target with the+ target-specific detail tool before citing it. Trace-level citations leave+ generation_id empty.Args:- generation_id: UUID of the $ai_generation event.- trace_id: UUID of the trace that contains the generation.+ generation_id: UUID of the $ai_generation event, or empty for a trace target.+ trace_id: Opaque ID of the cited trace.reason: Short free-form reason for the citation, e.g. "high_cost","refusal", "regression_at_14:00", "empty_output"."""- if not _UUID_RE.fullmatch(generation_id or ""):+ evaluation_target = resolve_evaluation_target(state.get("evaluation_target"))+ if evaluation_target == TRACE_TARGET and generation_id:+ return "Error: generation_id must be empty for trace-target citations"+ if evaluation_target == GENERATION_TARGET and not _UUID_RE.fullmatch(generation_id or ""):return f"Error: generation_id {generation_id!r} is not a canonical UUID"- if not _UUID_RE.fullmatch(trace_id or ""):- return f"Error: trace_id {trace_id!r} is not a canonical UUID"+ normalized_trace_id = _normalize_trace_id(trace_id)+ if normalized_trace_id is None:+ return "Error: trace_id is empty, too long, or contains control characters"+ if evaluation_target == TRACE_TARGET and not _is_returned_trace_id(state, normalized_trace_id):+ return "Error: trace_id was not returned by an evaluation query for this report"clean_reason = (reason or "").strip()[:200]- state["report"].citations.append(Citation(generation_id=generation_id, trace_id=trace_id, reason=clean_reason))- return f"Citation {len(state['report'].citations)} added: {generation_id[:8]}... ({clean_reason!r})"+ state["report"].citations.append(+ Citation(generation_id=generation_id, trace_id=normalized_trace_id, reason=clean_reason)+ )+ cited_id = generation_id or normalized_trace_id+ return f"Citation {len(state['report'].citations)} added: {cited_id[:32]} ({clean_reason!r})"-EVAL_REPORT_TOOLS = [- # Query tools (read-only, agent calls as needed)+_COMMON_OVERVIEW_TOOLS: list[BaseTool] = [get_summary_metrics,get_result_distribution_over_time,list_all_eval_results,sample_eval_results,- sample_generation_details,- get_generation_detail,- get_generation_text_repr,+]+_COMMON_FOLLOWUP_TOOLS: list[BaseTool] = [list_recent_report_runs,get_report_run,get_top_outcome_reasons,- # Output tools (mutate state["report"])+]++_GENERATION_DETAIL_TOOLS: list[BaseTool] = [sample_generation_details, get_generation_detail, get_generation_text_repr]+_TRACE_DETAIL_TOOLS: list[BaseTool] = [sample_trace_details, get_trace_detail]+_OUTPUT_TOOLS: list[BaseTool] = [set_title,add_section,add_citation,]+++def get_eval_report_tools(evaluation_target: str) -> list[BaseTool]:+ """Return the shared report tools plus only the details relevant to this target."""+ target = resolve_evaluation_target(evaluation_target)+ detail_tools = _TRACE_DETAIL_TOOLS if target == TRACE_TARGET else _GENERATION_DETAIL_TOOLS+ return [*_COMMON_OVERVIEW_TOOLS, *detail_tools, *_COMMON_FOLLOWUP_TOOLS, *_OUTPUT_TOOLS]+++# Preserve the original export for callers that build generation report agents directly.+EVAL_REPORT_TOOLS = get_eval_report_tools(GENERATION_TARGET)diff --git a/posthog/temporal/ai_observability/eval_reports/targets.py b/posthog/temporal/ai_observability/eval_reports/targets.pynew file mode 100644index 000000000000..0e57d72867fe--- /dev/null+++ b/posthog/temporal/ai_observability/eval_reports/targets.py@@ -0,0 +1,18 @@+"""Evaluation-target helpers shared by report queries and activities."""++GENERATION_TARGET = "generation"+TRACE_TARGET = "trace"+++def resolve_evaluation_target(target: str | None) -> str:+ normalized_target = target or GENERATION_TARGET+ if normalized_target not in (GENERATION_TARGET, TRACE_TARGET):+ raise ValueError(f"Unsupported evaluation target: {normalized_target}")+ return normalized_target+++def target_event_predicate(target: str | None) -> str:+ """Return a fixed SQL predicate for the evaluation event's target ID space."""+ if resolve_evaluation_target(target) == TRACE_TARGET:+ return "properties.$ai_target_type = 'trace_id'"+ return "(properties.$ai_target_type = 'generation_uuid' OR isNull(properties.$ai_target_type))"diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py b/posthog/temporal/ai_observability/eval_reports/test/test_activities.pyindex dbef28332841..526404ff3fb4 100644--- a/posthog/temporal/ai_observability/eval_reports/test/test_activities.py+++ b/posthog/temporal/ai_observability/eval_reports/test/test_activities.py@@ -12,6 +12,7 @@ from posthog.temporal.ai_observability.eval_reports.activities import (_count_eval_results_for_report,_fetch_count_triggered_eval_report_candidate_ids,_find_nth_eval_timestamp,+ _load_evaluation_target,_period_for_scheduled_report,run_eval_report_agent_activity,store_report_run_activity,@@ -23,13 +24,39 @@ from products.ai_observability.backend.models.evaluation_reports import Evaluatifrom products.ai_observability.backend.models.evaluations import Evaluation+class TestEvaluationTargetLoading(BaseTest):+ def test_loads_target_without_deferred_model_fields(self) -> None:+ evaluation = Evaluation.objects.create(+ team=self.team,+ name="Trace evaluation",+ evaluation_type="llm_judge",+ evaluation_config={"prompt": "test prompt"},+ output_type="boolean",+ output_config={},+ target="trace",+ enabled=True,+ created_by=self.user,+ conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],+ )++ target = _load_evaluation_target(self.team.id, str(evaluation.id))++ self.assertEqual(target, "trace")+++ ("output_type", "evaluation_target"),+ [("sentiment", "generation"), ("boolean", "trace")],+)@pytest.mark.asyncio-async def test_run_agent_activity_forwards_sentiment_output_type() -> None:+async def test_run_agent_activity_loads_target_and_forwards_output_type(+ output_type: str, evaluation_target: str+) -> None:@asynccontextmanagerasync def noop_heartbeater():yield- content = EvalReportContent(metrics=EvalReportMetrics(output_type="sentiment"))+ content = EvalReportContent(metrics=EvalReportMetrics(output_type=output_type))inputs = RunEvalReportAgentInput(report_id="report-id",team_id=1,@@ -38,7 +65,7 @@ async def test_run_agent_activity_forwards_sentiment_output_type() -> None:evaluation_description="",evaluation_prompt="",evaluation_type="sentiment",- output_type="sentiment",+ output_type=output_type,period_start="2026-07-01T00:00:00+00:00",period_end="2026-07-02T00:00:00+00:00",previous_period_start="2026-06-30T00:00:00+00:00",@@ -53,11 +80,18 @@ async def test_run_agent_activity_forwards_sentiment_output_type() -> None:"posthog.temporal.ai_observability.eval_reports.report_agent.run_eval_report_agent",return_value=content,) as run_agent,+ patch(+ "posthog.temporal.ai_observability.eval_reports.activities._load_evaluation_target",+ return_value=evaluation_target,+ ) as load_target,):result = await run_eval_report_agent_activity(inputs)- assert result.content["metrics"]["output_type"] == "sentiment"- assert run_agent.call_args.kwargs["output_type"] == "sentiment"+ assert result.content["metrics"]["output_type"] == output_type+ assert result.content["evaluation_target"] == evaluation_target+ assert run_agent.call_args.kwargs["output_type"] == output_type+ assert run_agent.call_args.kwargs["evaluation_target"] == evaluation_target+ load_target.assert_called_once_with(inputs.team_id, inputs.evaluation_id)@pytest.mark.asyncio@@ -105,13 +139,20 @@ async def test_store_sentiment_report_emits_generic_metrics_only() -> None:async def test_store_legacy_boolean_report_emits_normalized_generic_metrics() -> None:report_run = MagicMock(id="run-id", report_id="report-id")content = {+ "citations": [+ {+ "generation_id": "generation-id",+ "trace_id": "customer/trace:42",+ "reason": "example",+ }+ ],"metrics": {"total_runs": 10,"pass_count": 6,"fail_count": 3,"na_count": 1,"pass_rate": 66.67,- }+ },}inputs = StoreReportRunInput(report_id="report-id",@@ -144,11 +185,15 @@ async def test_store_legacy_boolean_report_emits_normalized_generic_metrics() ->assert properties["$ai_report_result_counts"] == {"pass": 6, "fail": 3, "na": 1}assert properties["$ai_report_result_rates"] == {"pass": 60.0, "fail": 30.0, "na": 10.0}assert properties["$ai_report_pass_rate"] == 66.67+ assert properties["$ai_report_evaluation_target"] == "generation"+ assert properties["$ai_report_referenced_generation_ids"] == ["generation-id"]+ assert properties["$ai_report_referenced_trace_ids"] == ["customer/trace:42"]def test_count_trigger_uses_current_output_type() -> None:report = MagicMock(team_id=1, team=MagicMock(), evaluation_id="evaluation-id")report.evaluation.output_type = "sentiment"+ report.evaluation.target = "trace"with (patch("posthog.hogql.parser.parse_select", return_value=MagicMock()) as parse_select,@@ -158,6 +203,7 @@ def test_count_trigger_uses_current_output_type() -> None:assert result == 4assert "properties.$ai_evaluation_result_type = 'sentiment'" in parse_select.call_args.args[0]+ assert "properties.$ai_target_type = 'trace_id'" in parse_select.call_args.args[0]def test_manual_count_window_uses_current_output_type() -> None:@@ -173,6 +219,7 @@ def test_manual_count_window_uses_current_output_type() -> None:assert result == expectedassert "properties.$ai_evaluation_result_type = 'sentiment'" in parse_select.call_args.args[0]+ assert "isNull(properties.$ai_target_type)" in parse_select.call_args.args[0]def _prepare_sync(report_id: str, manual: bool = False):diff --git a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.pyindex ed6ece81e0df..27c651da3af8 100644--- a/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py+++ b/posthog/temporal/ai_observability/eval_reports/test/test_delivery.py@@ -5,6 +5,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom posthog.temporal.ai_observability.eval_reports.delivery import (+ _build_citation_map,_format_period_for_display,_inline_email_styles,_linkify_citations,@@ -23,10 +24,14 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import ()+def _generation_citation_map(generation_id: str, trace_id: str) -> dict[str, tuple[str, str | None]]:+ return _build_citation_map([Citation(generation_id=generation_id, trace_id=trace_id, reason="example")])++class TestLinkifyCitations(SimpleTestCase):def test_links_cited_generation_id_in_backticks(self):text = "See `12345678-1234-1234-1234-123456789abc` here."- citation_map = {"12345678-1234-1234-1234-123456789abc": "trace-abc"}+ citation_map = _generation_citation_map("12345678-1234-1234-1234-123456789abc", "trace-abc")result = _linkify_citations(text, project_id=42, citation_map=citation_map)self.assertIn("[12345678...]", result)self.assertIn(@@ -36,14 +41,14 @@ class TestLinkifyCitations(SimpleTestCase):def test_links_cited_generation_id_in_double_backticks(self):text = "See `` `12345678-1234-1234-1234-123456789abc` `` here."- citation_map = {"12345678-1234-1234-1234-123456789abc": "trace-abc"}+ citation_map = _generation_citation_map("12345678-1234-1234-1234-123456789abc", "trace-abc")result = _linkify_citations(text, project_id=1, citation_map=citation_map)self.assertIn("[12345678...]", result)self.assertNotIn("``", result)def test_links_cited_generation_id_bare(self):text = "See 12345678-1234-1234-1234-123456789abc here."- citation_map = {"12345678-1234-1234-1234-123456789abc": "trace-abc"}+ citation_map = _generation_citation_map("12345678-1234-1234-1234-123456789abc", "trace-abc")result = _linkify_citations(text, project_id=1, citation_map=citation_map)self.assertIn("[12345678...]", result)@@ -54,13 +59,13 @@ class TestLinkifyCitations(SimpleTestCase):def test_leaves_non_id_backticks_alone(self):text = "Use `some_function()` here."- citation_map = {"12345678-1234-1234-1234-123456789abc": "trace-abc"}+ citation_map = _generation_citation_map("12345678-1234-1234-1234-123456789abc", "trace-abc")result = _linkify_citations(text, project_id=1, citation_map=citation_map)self.assertEqual(text, result)def test_no_double_replacement_when_id_appears_multiple_times(self):gen_id = "639a38ba-6cc6-4e0c-b5ff-ad269f6f9cf6"- citation_map = {gen_id: "trace-abc"}+ citation_map = _generation_citation_map(gen_id, "trace-abc")text = f"- `{gen_id}`: satisfied\n1. {gen_id} — reason"result = _linkify_citations(text, project_id=1, citation_map=citation_map)self.assertNotIn(f"?event=[", result)@@ -69,8 +74,8 @@ class TestLinkifyCitations(SimpleTestCase):def test_multiple_citations_no_cross_contamination(self):citation_map = {- "aaaa1111-1111-1111-1111-111111111111": "trace-a",- "bbbb2222-2222-2222-2222-222222222222": "trace-b",+ **_generation_citation_map("aaaa1111-1111-1111-1111-111111111111", "trace-a"),+ **_generation_citation_map("bbbb2222-2222-2222-2222-222222222222", "trace-b"),}text = "First: `aaaa1111-1111-1111-1111-111111111111`, second: `bbbb2222-2222-2222-2222-222222222222`."result = _linkify_citations(text, project_id=1, citation_map=citation_map)@@ -80,10 +85,69 @@ class TestLinkifyCitations(SimpleTestCase):def test_handles_non_uuid_trace_id(self):text = "See `gen-123` here."- citation_map = {"gen-123": "my-custom-trace-id"}+ citation_map = _generation_citation_map("gen-123", "my-custom-trace-id")result = _linkify_citations(text, project_id=1, citation_map=citation_map)self.assertIn("/traces/my-custom-trace-id?event=gen-123", result)+ @parameterized.expand(+ [+ (+ "generation",+ Citation(generation_id="generation/id ?#", trace_id="trace/id ?#", reason="example"),+ "generation/id ?#",+ "/traces/trace%252Fid%2520%253F%2523?event=generation%2Fid+%3F%23",+ True,+ ),+ (+ "trace",+ Citation(generation_id="", trace_id="trace/id ?#", reason="example"),+ "trace/id ?#",+ "/traces/trace%252Fid%2520%253F%2523",+ False,+ ),+ ]+ )+ def test_links_structured_citation_for_target(+ self,+ _name: str,+ citation: Citation,+ cited_id: str,+ expected_url: str,+ expects_event_focus: bool,+ ) -> None:+ result = _linkify_citations(+ f"See `{cited_id}` here.",+ project_id=1,+ citation_map=_build_citation_map([citation]),+ )++ self.assertIn(expected_url, result)+ self.assertEqual("?event=" in result, expects_event_focus)++ def test_trace_citation_does_not_link_bare_common_id(self) -> None:+ citation = Citation(generation_id="", trace_id="foo", reason="example")++ result = _linkify_citations(+ "See `foo`, but foobar and foo stay plain.",+ project_id=1,+ citation_map=_build_citation_map([citation]),+ )++ self.assertEqual(result.count("[foo...]"), 1)+ self.assertIn("foobar and foo stay plain", result)++ def test_opaque_trace_id_cannot_break_markdown_link(self) -> None:+ citation = Citation(generation_id="", trace_id="trace](id", reason="example")++ result = _linkify_citations(+ "See `trace](id`.",+ project_id=1,+ citation_map=_build_citation_map([citation]),+ )++ self.assertIn("[trace](", result)+ self.assertIn("/traces/trace%255D%2528id", result)+class TestRenderSectionHtml(SimpleTestCase):"""v2: renderer takes a title directly, no more SECTION_TITLES lookup."""@@ -101,7 +165,7 @@ class TestRenderSectionHtml(SimpleTestCase):self.assertIn("<strong>Pass rate</strong>", html)def test_converts_cited_id_to_link(self):- citation_map = {"12345678-1234-1234-1234-123456789abc": "trace-abc"}+ citation_map = _generation_citation_map("12345678-1234-1234-1234-123456789abc", "trace-abc")html = _render_section_html("Failures","Failed: `12345678-1234-1234-1234-123456789abc`",diff --git a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.pyindex 9335f9ddec21..b1c19dc88304 100644--- a/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py+++ b/posthog/temporal/ai_observability/trace_summarization/fetch_and_format.py@@ -34,7 +34,14 @@ logger = structlog.get_logger(__name__)def _fetch_and_format_trace(- trace_id: str, team_id: int, window_start: str, window_end: str, max_length: int | None = None+ trace_id: str,+ team_id: int,+ window_start: str,+ window_end: str,+ max_length: int | None = None,+ *,+ max_trace_events: int | None = None,+ max_raw_trace_size: int | None = None,) -> FetchResult | None:"""Fetch trace data and format text representation.@@ -46,18 +53,29 @@ def _fetch_and_format_trace(if llm_trace is None:return None+ event_count = len(llm_trace.events)+ if max_trace_events is not None and event_count > max_trace_events:+ logger.warning(+ "Skipping trace with too many events",+ trace_id=trace_id,+ team_id=team_id,+ event_count=event_count,+ max_trace_events=max_trace_events,+ )+ return FetchResult(text_repr=None, event_count=event_count)+raw_size = sum(len(str(e.properties)) for e in llm_trace.events)- if raw_size > MAX_RAW_TRACE_SIZE:+ raw_size_limit = max_raw_trace_size if max_raw_trace_size is not None else MAX_RAW_TRACE_SIZE+ if raw_size > raw_size_limit:logger.warning("Skipping oversized trace",trace_id=trace_id,team_id=team_id,- event_count=len(llm_trace.events),+ event_count=event_count,raw_size=raw_size,- max_raw_size=MAX_RAW_TRACE_SIZE,+ max_raw_size=raw_size_limit,)- _trace_dict, hierarchy = llm_trace_to_formatter_format(llm_trace)- return FetchResult(text_repr=None, event_count=len(hierarchy))+ return FetchResult(text_repr=None, event_count=event_count)trace_dict, hierarchy = llm_trace_to_formatter_format(llm_trace)diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.pyindex 3baedeb9dbff..c7b5cc12e2e3 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_fetch_and_format.py@@ -5,9 +5,10 @@ from contextlib import asynccontextmanagerfrom datetime import UTC, datetimeimport pytest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom posthog.temporal.ai_observability.trace_summarization.fetch_and_format import (+ _fetch_and_format_trace,_format_generation_text_repr,fetch_and_format_activity,)@@ -67,6 +68,29 @@ class TestFormatGenerationTextRepr:assert "Tokens:" not in result+class TestFetchAndFormatTrace:+ @patch("posthog.temporal.ai_observability.trace_summarization.fetch_and_format.llm_trace_to_formatter_format")+ @patch("posthog.temporal.ai_observability.trace_summarization.fetch_and_format.fetch_trace")+ @patch("posthog.temporal.ai_observability.trace_summarization.fetch_and_format.Team.objects.get")+ def test_skips_trace_over_event_limit_before_formatting(+ self, _mock_get_team: MagicMock, mock_fetch: MagicMock, mock_format: MagicMock+ ) -> None:+ mock_fetch.return_value = MagicMock(events=[MagicMock(properties={}) for _ in range(51)])++ result = _fetch_and_format_trace(+ trace_id="oversized-trace",+ team_id=7,+ window_start="2026-04-08T14:00:00+00:00",+ window_end="2026-04-08T15:00:00+00:00",+ max_trace_events=50,+ )++ assert result is not None+ assert result.text_repr is None+ assert result.event_count == 51+ mock_format.assert_not_called()++@patch("posthog.temporal.ai_observability.trace_summarization.fetch_and_format.Heartbeater",_noop_heartbeater,diff --git a/products/ai_observability/backend/api/evaluation_reports.py b/products/ai_observability/backend/api/evaluation_reports.pyindex a249b44daa38..6379c55c3550 100644--- a/products/ai_observability/backend/api/evaluation_reports.py+++ b/products/ai_observability/backend/api/evaluation_reports.py@@ -32,6 +32,7 @@ from products.ai_observability.backend.models.evaluation_reports import (EvaluationReportQuerySet,EvaluationReportRun,)+from products.ai_observability.backend.models.evaluations import EvaluationTargetfrom products.workflows.backend.utils.rrule_utils import validate_rrulelogger = structlog.get_logger(__name__)@@ -371,15 +372,15 @@ class EvaluationReportSectionSerializer(serializers.Serializer):class EvaluationReportCitationSerializer(serializers.Serializer):generation_id = serializers.CharField(required=False,- help_text="Generation UUID referenced by this citation.",+ help_text="Optional generation UUID for generation-target report citations.",)trace_id = serializers.CharField(required=False,- help_text="Trace identifier containing the referenced generation.",+ help_text="Identifier of the trace cited by this report.",)reason = serializers.CharField(required=False,- help_text="Short explanation of why the generation is cited.",+ help_text="Short explanation of why this example is cited.",)@@ -440,6 +441,11 @@ class EvaluationReportMetricsSerializer(serializers.Serializer):class EvaluationReportRunContentSerializer(serializers.Serializer):+ evaluation_target = serializers.ChoiceField(+ choices=EvaluationTarget.choices,+ required=False,+ help_text="Evaluation target analyzed by this report run. Legacy runs without this field targeted generations.",+ )title = serializers.CharField(required=False,help_text="Agent-generated report headline.",@@ -452,7 +458,7 @@ class EvaluationReportRunContentSerializer(serializers.Serializer):citations = EvaluationReportCitationSerializer(many=True,required=False,- help_text="Trace references grounding findings in the report.",+ help_text="References grounding findings in the report.",)metrics = EvaluationReportMetricsSerializer(required=False,diff --git a/products/ai_observability/backend/api/test/test_evaluation_reports.py b/products/ai_observability/backend/api/test/test_evaluation_reports.pyindex 9513509ca2fd..695513033b95 100644--- a/products/ai_observability/backend/api/test/test_evaluation_reports.py+++ b/products/ai_observability/backend/api/test/test_evaluation_reports.py@@ -232,6 +232,15 @@ class TestEvaluationReportApi(APIBaseTest):conditions=[{"id": "c1", "rollout_percentage": 100, "properties": []}],)+ def _create_trace_sentiment_evaluation(self) -> Evaluation:+ evaluation = self._create_sentiment_evaluation()+ Evaluation.objects.filter(id=evaluation.id).update(+ target=EvaluationTarget.TRACE,+ target_config={"window_seconds": 60},+ )+ evaluation.refresh_from_db()+ return evaluation+def test_unauthenticated_user_cannot_access(self):self.client.logout()response = self.client.get(self.base_url)@@ -357,11 +366,29 @@ class TestEvaluationReportApi(APIBaseTest):report = EvaluationReport.objects.get(evaluation=sentiment_evaluation)self.assertEqual(response.json()["id"], str(report.id))- @parameterized.expand([("trace_target", "trace"), ("unsupported_output", "unsupported")])+ def test_create_accepts_trace_evaluation(self) -> None:+ trace_evaluation = self._create_trace_evaluation()++ response = self.client.post(+ self.base_url,+ {+ "evaluation": str(trace_evaluation.id),+ "frequency": "every_n",+ "trigger_threshold": 100,+ "delivery_targets": [],+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ report = EvaluationReport.objects.get(evaluation=trace_evaluation)+ self.assertEqual(response.json()["id"], str(report.id))++ @parameterized.expand([("trace_sentiment", "trace_sentiment"), ("unsupported_output", "unsupported")])def test_create_rejects_unreportable_evaluation(self, _name: str, evaluation_kind: str) -> None:evaluation = (- self._create_trace_evaluation()- if evaluation_kind == "trace"+ self._create_trace_sentiment_evaluation()+ if evaluation_kind == "trace_sentiment"else self._create_unsupported_output_evaluation())response = self.client.post(@@ -378,30 +405,46 @@ class TestEvaluationReportApi(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertEqual(response.json().get("attr"), "evaluation")- def test_deliverable_includes_reportable_generation_evaluations_only(self):+ def test_deliverable_includes_supported_generation_and_trace_evaluations(self):boolean_report = self._create_report()sentiment_report = self._create_report(evaluation=self._create_sentiment_evaluation())trace_report = self._create_report(evaluation=self._create_trace_evaluation())+ trace_sentiment_report = self._create_report(evaluation=self._create_trace_sentiment_evaluation())unsupported_report = self._create_report(evaluation=self._create_unsupported_output_evaluation())deliverable_ids = set(EvaluationReport.objects.deliverable().values_list("id", flat=True))- self.assertEqual(deliverable_ids, {boolean_report.id, sentiment_report.id})- self.assertNotIn(trace_report.id, deliverable_ids)+ self.assertEqual(deliverable_ids, {boolean_report.id, sentiment_report.id, trace_report.id})+ self.assertNotIn(trace_sentiment_report.id, deliverable_ids)self.assertNotIn(unsupported_report.id, deliverable_ids)- @parameterized.expand([("trace_target", "trace"), ("unsupported_output", "unsupported")])+ @patch("products.ai_observability.backend.api.evaluation_reports.async_to_sync")+ @patch("posthog.temporal.common.client.sync_connect")+ def test_generate_accepts_trace_evaluation(+ self,+ mock_sync_connect: MagicMock,+ mock_async_to_sync: MagicMock,+ ) -> None:+ mock_sync_connect.return_value = MagicMock()+ mock_async_to_sync.return_value = MagicMock()+ report = self._create_report(evaluation=self._create_trace_evaluation())++ response = self.client.post(f"{self.base_url}{report.id}/generate/")++ self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)++ @parameterized.expand([("trace_sentiment", "trace_sentiment"), ("unsupported_output", "unsupported")])def test_generate_rejects_unreportable_evaluation(self, _name: str, evaluation_kind: str) -> None:evaluation = (- self._create_trace_evaluation()- if evaluation_kind == "trace"+ self._create_trace_sentiment_evaluation()+ if evaluation_kind == "trace_sentiment"else self._create_unsupported_output_evaluation())report = self._create_report(evaluation=evaluation)response = self.client.post(f"{self.base_url}{report.id}/generate/")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- def test_list_includes_sentiment_and_excludes_unreportable_reports(self):+ def test_list_includes_supported_generation_and_trace_reports(self):sentiment_evaluation = self._create_sentiment_evaluation()sentiment_report = EvaluationReport.objects.create(team=self.team,@@ -410,13 +453,17 @@ class TestEvaluationReportApi(APIBaseTest):trigger_threshold=100,delivery_targets=[],)- self._create_report(evaluation=self._create_trace_evaluation())+ trace_report = self._create_report(evaluation=self._create_trace_evaluation())+ self._create_report(evaluation=self._create_trace_sentiment_evaluation())self._create_report(evaluation=self._create_unsupported_output_evaluation())response = self.client.get(self.base_url)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual([result["id"] for result in response.json()["results"]], [str(sentiment_report.id)])+ self.assertEqual(+ {result["id"] for result in response.json()["results"]},+ {str(sentiment_report.id), str(trace_report.id)},+ )def test_create_scheduled_sets_next_delivery_date(self):response = self.client.post(self.base_url, self._scheduled_payload(rrule="FREQ=WEEKLY;BYDAY=MO"), format="json")diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.pyindex 911c94042ed6..a6dbdc7387b9 100644--- a/products/ai_observability/backend/api/test/test_evaluations.py+++ b/products/ai_observability/backend/api/test/test_evaluations.py@@ -169,8 +169,7 @@ class TestEvaluationConfigsApi(APIBaseTest):evaluation = Evaluation.objects.get(name="Trace target")self.assertEqual(evaluation.target, "trace")self.assertEqual(evaluation.target_config, {"window_seconds": 30 * 60})- # Reports run a generation-oriented agent — a trace eval must not get an auto-created report.- self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 0)+ self.assertEqual(EvaluationReport.objects.filter(evaluation=evaluation).count(), 1)def test_trace_target_accepts_custom_window(self):response = self.client.post(diff --git a/products/ai_observability/backend/models/evaluation_configs.py b/products/ai_observability/backend/models/evaluation_configs.pyindex 87746742eb29..d180525971b1 100644--- a/products/ai_observability/backend/models/evaluation_configs.py+++ b/products/ai_observability/backend/models/evaluation_configs.py@@ -117,6 +117,10 @@ EVALUATION_CONFIG_CONTENT_KEYS: dict[str, str] = {}REPORTABLE_OUTPUT_TYPES: tuple[str, ...] = (OutputType.BOOLEAN.value, OutputType.SENTIMENT.value)+REPORTABLE_OUTPUT_TYPES_BY_TARGET: dict[str, tuple[str, ...]] = {+ "generation": REPORTABLE_OUTPUT_TYPES,+ "trace": (OutputType.BOOLEAN.value,),+}def evaluation_uses_model_configuration(evaluation_type: str | None) -> bool:@@ -124,7 +128,7 @@ def evaluation_uses_model_configuration(evaluation_type: str | None) -> bool:def evaluation_supports_reports(output_type: str | None, target: str | None) -> bool:- return output_type in REPORTABLE_OUTPUT_TYPES and target == "generation"+ return output_type in REPORTABLE_OUTPUT_TYPES_BY_TARGET.get(target or "", ())def get_evaluation_config_content_key(evaluation_type: str | None) -> str | None:diff --git a/products/ai_observability/backend/models/evaluation_reports.py b/products/ai_observability/backend/models/evaluation_reports.pyindex ad8d4c9f1e57..6faf5297eddc 100644--- a/products/ai_observability/backend/models/evaluation_reports.py+++ b/products/ai_observability/backend/models/evaluation_reports.py@@ -9,16 +9,18 @@ from posthog.models.utils import UUIDTModelfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule-from .evaluation_configs import REPORTABLE_OUTPUT_TYPES-from .evaluations import EvaluationTarget+from .evaluation_configs import REPORTABLE_OUTPUT_TYPES_BY_TARGETclass EvaluationReportQuerySet(models.QuerySet):def reportable(self) -> "EvaluationReportQuerySet":- return self.filter(- evaluation__output_type__in=REPORTABLE_OUTPUT_TYPES,- evaluation__target=EvaluationTarget.GENERATION,- )+ reportable_filter = models.Q()+ for target, output_types in REPORTABLE_OUTPUT_TYPES_BY_TARGET.items():+ reportable_filter |= models.Q(+ evaluation__target=target,+ evaluation__output_type__in=output_types,+ )+ return self.filter(reportable_filter)def deliverable(self) -> "EvaluationReportQuerySet":return self.reportable().filter(diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.test.tsindex 419e33f890fd..3bf7147f63fa 100644--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.test.ts@@ -10,7 +10,7 @@ import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { DisplayOption, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'+import { DisplayOption, TraceViewMode, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'const blankScene = (): any => ({ scene: { component: () => null, logic: null } })const scenes: any = { AIObservabilityTrace: blankScene }@@ -41,14 +41,28 @@ describe('aiObservabilityTraceLogic', () => {expect(logic.values.traceId).toBe(traceIdWithColon)})- it('properly loads trace scene when trace ID contains multiple colons', async () => {- const traceIdWithMultipleColons = 'namespace:trace:12345:abcdef:xyz'- const traceUrl = combineUrl(urls.aiObservabilityTrace(traceIdWithMultipleColons))+ it('preserves an opaque trace ID when trace URL state changes', async () => {+ const traceId = 'trace](id /?#'+ const traceUrl = combineUrl(urls.aiObservabilityTrace(traceId))router.actions.push(addProjectIdIfMissing(traceUrl.url, MOCK_TEAM_ID))await expectLogic(logic).toMatchValues({- traceId: traceIdWithMultipleColons,+ traceId,})++ logic.actions.setSearchQuery('needle')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.traceId).toBe(traceId)+ expect(router.values.searchParams).toMatchObject({ search: 'needle' })++ logic.actions.setViewMode(TraceViewMode.Raw)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.traceId).toBe(traceId)+ expect(router.values.location.pathname).toBe(+ addProjectIdIfMissing(urls.aiObservabilityTrace(traceId), MOCK_TEAM_ID)+ )})it('handles trace ID with event and timestamp parameters', async () => {diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.tsindex ea34d971a875..35328744b800 100644--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts@@ -11,6 +11,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { addProductIntent } from 'lib/utils/product-intents'+import { tryDecodeURIComponent } from 'lib/utils/url'import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'@@ -848,8 +849,11 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([})),urlToAction(({ actions, cache }) => ({- [urls.aiObservabilityTrace(':id')]: ({ id }, { event, timestamp, exception_ts, search, line, tab, msg }) => {- actions.setTraceId(id ?? '')+ [`${urls.aiObservabilityTraces()}/:id`]: (+ { id },+ { event, timestamp, exception_ts, search, line, tab, msg }+ ) => {+ actions.setTraceId(tryDecodeURIComponent(id ?? ''))void addProductIntent({product_type: ProductKey.AI_OBSERVABILITY,intent_context: ProductIntentContext.LLM_ANALYTICS_TRACE_VIEWED,diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsxindex 3121dd892e3f..fa47ec2509ba 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.test.tsx@@ -1,6 +1,6 @@import { cleanup, render, screen } from '@testing-library/react'-import type { EvaluationReportRun, EvaluationReportStoredMetrics } from '../types'+import type { EvaluationReportCitation, EvaluationReportRun, EvaluationReportStoredMetrics } from '../types'import { EvaluationReportViewer, summarizeEvaluationReportResults } from './EvaluationReportViewer'function buildMetrics(fields: EvaluationReportStoredMetrics): EvaluationReportStoredMetrics {@@ -110,4 +110,53 @@ describe('EvaluationReportViewer', () => {expect(markdown?.textContent).toContain('# Important context')expect(markdown?.textContent).toContain('Keep this detail.')})++ it.each<{+ name: string+ citedId: string+ citation: EvaluationReportCitation+ expectedUrl: string+ expectedLabel: string+ content?: string+ expectedPlainText?: string+ }>([+ {+ name: 'generation citation',+ citedId: 'generation/id ?',+ citation: { generation_id: 'generation/id ?', trace_id: 'trace/id ?', reason: 'example' },+ expectedUrl: '/ai-observability/traces/trace%252Fid%2520%253F?event=generation%2Fid+%3F',+ expectedLabel: 'generati...',+ },+ {+ name: 'trace citation',+ citedId: 'foo',+ citation: { trace_id: 'foo', reason: 'example' },+ expectedUrl: '/ai-observability/traces/foo',+ expectedLabel: 'foo...',+ content: 'See `foo`, but foobar and foo stay plain.',+ expectedPlainText: 'foobar and foo stay plain',+ },+ {+ name: 'opaque trace citation with Markdown delimiters',+ citedId: 'trace](id',+ citation: { trace_id: 'trace](id', reason: 'example' },+ expectedUrl: '/ai-observability/traces/trace%255D%2528id',+ expectedLabel: 'trace',+ },+ ])(+ 'links a $name to the correct trace view',+ ({ citedId, citation, expectedUrl, expectedLabel, content, expectedPlainText }) => {+ const reportRun = buildReportRun(buildMetrics({ pass_rate: 80 }))+ reportRun.content.sections = [{ title: 'Finding', content: content ?? `See \`${citedId}\`.` }]+ reportRun.content.citations = [citation]++ render(<EvaluationReportViewer reportRun={reportRun} compact />)++ const markdown = document.querySelector('[data-testid="react-markdown"]')+ expect(markdown?.textContent).toContain(`[\`${expectedLabel}\`](${expectedUrl})`)+ if (expectedPlainText) {+ expect(markdown?.textContent).toContain(expectedPlainText)+ }+ }+ )})diff --git a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsxindex a07cc10b793a..1ff9f5c3524f 100644--- a/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx+++ b/products/ai_observability/frontend/evaluations/components/EvaluationReportViewer.tsx@@ -13,8 +13,8 @@ import type {EvaluationReportStoredMetrics,} from '../types'-// Rewrite each cited generation_id in the content into a markdown link to the-// trace viewer. Uses the structured citations list (not regex scanning) so:+// Rewrite each cited generation or trace ID in the content into a markdown link+// to the trace viewer. Uses the structured citations list (not regex scanning) so:// - only ids the agent explicitly cited get linked (no false positives)// - the trace_id for the correct URL is guaranteed available// - there's no ReDoS surface on arbitrary prose input@@ -24,6 +24,13 @@ import type {// by a later citation. Wrapper variants (`uuid`, <uuid>, bare) are collapsed// in descending specificity so the wrappers themselves get absorbed into the// replacement rather than surviving around a link.+const SAFE_CITATION_LABEL_RE = /^[A-Za-z0-9._~-]{1,8}$/++function citationLinkLabel(citedId: string, isGenerationCitation: boolean): string {+ const preview = citedId.slice(0, 8)+ return SAFE_CITATION_LABEL_RE.test(preview) ? `${preview}...` : isGenerationCitation ? 'generation' : 'trace'+}+function linkifyCitations(content: string, citations: EvaluationReportCitation[]): string {if (citations.length === 0) {return content@@ -31,18 +38,23 @@ function linkifyCitations(content: string, citations: EvaluationReportCitation[]const tokens: Array<{ token: string; link: string }> = []let out = contentcitations.forEach((c, idx) => {- if (!c.generation_id) {+ const citedId = c.generation_id || c.trace_id+ const traceId = c.trace_id || c.generation_id+ if (!citedId || !traceId) {return}const token = `\0CITE${idx}\0`- const url = c.trace_id- ? urls.aiObservabilityTrace(c.trace_id, { event: c.generation_id })- : urls.aiObservabilityTrace(c.generation_id)- const link = `[\`${c.generation_id.slice(0, 8)}...\`](${url})`+ const url = urls.aiObservabilityTrace(+ traceId,+ c.generation_id && c.trace_id ? { event: c.generation_id } : undefined+ )+ const link = `[\`${citationLinkLabel(citedId, Boolean(c.generation_id))}\`](${url})`const before = out- out = out.split(`\`${c.generation_id}\``).join(token)- out = out.split(`<${c.generation_id}>`).join(token)- out = out.split(c.generation_id).join(token)+ out = out.split(`\`${citedId}\``).join(token)+ out = out.split(`<${citedId}>`).join(token)+ if (c.generation_id) {+ out = out.split(citedId).join(token)+ }if (out !== before) {tokens.push({ token, link })}diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.tsindex 3ae2cf1ec61d..80036df8130b 100644--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.test.ts@@ -7,7 +7,7 @@ describe('evaluationCapabilities', () => {>([['boolean', 'generation', true, true],['sentiment', 'generation', true, false],- ['boolean', 'trace', false, false],+ ['boolean', 'trace', true, false],['sentiment', 'trace', false, false],])('supports the expected capabilities for %s %s evaluations',diff --git a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts b/products/ai_observability/frontend/evaluations/evaluationCapabilities.tsindex 8c714bc0654a..5ec76d45853f 100644--- a/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts+++ b/products/ai_observability/frontend/evaluations/evaluationCapabilities.ts@@ -9,13 +9,10 @@ export function isBooleanEvaluationOutput(outputType: EvaluationOutputType | nulexport function evaluationSupportsReports(evaluation: Pick<EvaluationConfig, 'output_type' | 'target'> | null | undefined): boolean {- // Trace-level evals aren't supported by the report agent yet — the backend rejects- // report creation for them, so hide the report UI rather than surface that error.- return (- evaluation?.target === 'generation' &&- evaluation.output_type != null &&- REPORTABLE_OUTPUT_TYPES.has(evaluation.output_type)- )+ if (evaluation?.output_type == null || !REPORTABLE_OUTPUT_TYPES.has(evaluation.output_type)) {+ return false+ }+ return evaluation.target === 'generation' || (evaluation.target === 'trace' && evaluation.output_type === 'boolean')}export function evaluationSupportsRunSummary(diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 7fa97a463074..9ab0f7b087cb 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -1233,11 +1233,11 @@ export interface EvaluationReportSectionApi {}export interface EvaluationReportCitationApi {- /** Generation UUID referenced by this citation. */+ /** Optional generation UUID for generation-target report citations. */generation_id?: string- /** Trace identifier containing the referenced generation. */+ /** Identifier of the trace cited by this report. */trace_id?: string- /** Short explanation of why the generation is cited. */+ /** Short explanation of why this example is cited. */reason?: string}@@ -1304,11 +1304,16 @@ export interface EvaluationReportMetricsApi {}export interface EvaluationReportRunContentApi {+ /** Evaluation target analyzed by this report run. Legacy runs without this field targeted generations.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ evaluation_target?: EvaluationTargetEnumApi/** Agent-generated report headline. */title?: string/** Ordered narrative sections in the report. */sections?: EvaluationReportSectionApi[]- /** Trace references grounding findings in the report. */+ /** References grounding findings in the report. */citations?: EvaluationReportCitationApi[]/** Structured metrics computed for the report period. */metrics?: EvaluationReportMetricsApi | nulldiff --git a/products/ai_observability/manifest.tsx b/products/ai_observability/manifest.tsxindex 107f963fbc9d..24b8162a91d8 100644--- a/products/ai_observability/manifest.tsx+++ b/products/ai_observability/manifest.tsx@@ -302,9 +302,20 @@ export const manifest: ProductManifest = {msg?: string}): string => {+ const encodePathSegment = (value: string): string => {+ // kea-router decodes the pathname before matching, so preserve an encoded layer for the trace scene.+ const encodedValue = encodeURIComponent(value).replace(+ /[!'()*]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`+ )+ return encodeURIComponent(encodedValue).replace(+ /[!'()*]/g,+ (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`+ )+ }const queryParams = new URLSearchParams(params)const stringifiedParams = queryParams.toString()- return `/ai-observability/traces/${id}${stringifiedParams ? `?${stringifiedParams}` : ''}`+ return `/ai-observability/traces/${encodePathSegment(id)}${stringifiedParams ? `?${stringifiedParams}` : ''}`},aiObservabilityUsers: (): string => '/ai-observability/users',aiObservabilityErrors: (): string => '/ai-observability/errors',diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f4c01669f2df..7b02a29738c8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23442,11 +23442,11 @@ export namespace Schemas {}export interface EvaluationReportCitation {- /** Generation UUID referenced by this citation. */+ /** Optional generation UUID for generation-target report citations. */generation_id?: string;- /** Trace identifier containing the referenced generation. */+ /** Identifier of the trace cited by this report. */trace_id?: string;- /** Short explanation of why the generation is cited. */+ /** Short explanation of why this example is cited. */reason?: string;}@@ -23520,11 +23520,16 @@ export namespace Schemas {}export interface EvaluationReportRunContent {+ /** Evaluation target analyzed by this report run. Legacy runs without this field targeted generations.+ *+ * * `generation` - Generation+ * * `trace` - Trace */+ evaluation_target?: EvaluationTargetEnum;/** Agent-generated report headline. */title?: string;/** Ordered narrative sections in the report. */sections?: EvaluationReportSection[];- /** Trace references grounding findings in the report. */+ /** References grounding findings in the report. */citations?: EvaluationReportCitation[];/** Structured metrics computed for the report period. */metrics?: EvaluationReportMetrics | null;