:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): stop eval reports falling back over dead identifiers (#104030)
posthog[bot]c8a2c92603d0
diff --git a/posthog/temporal/ai_observability/eval_reports/delivery.py b/posthog/temporal/ai_observability/eval_reports/delivery.pyindex f2ff40c42fd6..df742bd34401 100644--- a/posthog/temporal/ai_observability/eval_reports/delivery.py+++ b/posthog/temporal/ai_observability/eval_reports/delivery.py@@ -19,6 +19,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (Citation,EvalReportContent,EvalReportMetrics,+ citation_wrappers,)logger = structlog.get_logger(__name__)@@ -147,7 +148,7 @@ def _linkify_citations(text: str, project_id: int, citation_map: CitationMap) ->placeholder = f"\x00CITE{i}\x00"placeholders[placeholder] = cited_id- for wrapper in [f"`` `{cited_id}` ``", f"`{cited_id}`", f"<{cited_id}>"]:+ for wrapper in citation_wrappers(cited_id):text = text.replace(wrapper, placeholder)if citation_map[cited_id].generation_id:text = text.replace(cited_id, placeholder)diff --git a/posthog/temporal/ai_observability/eval_reports/metrics.py b/posthog/temporal/ai_observability/eval_reports/metrics.pyindex 837c350ede65..ff1439698ad2 100644--- a/posthog/temporal/ai_observability/eval_reports/metrics.py+++ b/posthog/temporal/ai_observability/eval_reports/metrics.py@@ -106,6 +106,15 @@ def increment_report_generated(outcome: str) -> None:).add(1)+def increment_dead_ids_unwrapped(count: int) -> None:+ if not activity.in_activity() and not workflow.in_workflow():+ return+ get_metric_meter().create_counter(+ "llma_eval_reports_dead_ids_unwrapped",+ "Dead identifiers unwrapped before delivery",+ ).add(count)++def increment_delivery(delivery_type: str, status: str) -> None:if not activity.in_activity() and not workflow.in_workflow():returndiff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.pyindex 4aa9170f95b3..2f79275c92fe 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/graph.py@@ -16,12 +16,16 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.prompts importfrom posthog.temporal.ai_observability.eval_reports.report_agent.schema import (MAX_REPORT_SECTIONS,MIN_REPORT_SECTIONS,+ Citation,EvalReportContent,EvalReportGenerationStatus,EvalReportMetrics,ReportSection,)-from posthog.temporal.ai_observability.eval_reports.report_agent.state import EvalReportAgentState+from posthog.temporal.ai_observability.eval_reports.report_agent.state import (+ REPORT_RUN_HANDLE_KEY,+ EvalReportAgentState,+)from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (_ch_ts,_dead_backticked_ids_in_report,@@ -29,6 +33,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (_handled_ids,_is_retriable_ch_error,get_eval_report_tools,+ strip_dead_backticked_ids,)from posthog.temporal.ai_observability.eval_reports.targets import (GENERATION_TARGET,@@ -188,6 +193,26 @@ def _append_references_section(content: EvalReportContent) -> None:content.sections.append(ReportSection(title="References", content="\n".join(refs_lines)))+def _unwrap_dead_ids(content: EvalReportContent, handled_ids: set[str]) -> list[str]:+ """Take the backticks off every ID the renderers cannot link, and return those IDs.++ The agent is told in the tool errors to do this itself. Doing it here too means one+ stray identifier costs the reader a link, not the whole analysis.+ """+ titles = [content.title, *(section.title for section in content.sections)]+ bodies = [section.content for section in content.sections]+ dead = _dead_backticked_ids_in_report(titles, bodies, content.citations, handled_ids)+ if not dead:+ return []++ no_citations: list[Citation] = []+ content.title = strip_dead_backticked_ids(content.title, no_citations, handled_ids)+ for section in content.sections:+ section.title = strip_dead_backticked_ids(section.title, no_citations, handled_ids)+ section.content = strip_dead_backticked_ids(section.content, content.citations, handled_ids)+ return dead++def _validate_agent_output(content: EvalReportContent, handled_ids: set[str] | None = None) -> str | None:"""Return a reason string if content is invalid, else None.@@ -200,7 +225,8 @@ def _validate_agent_output(content: EvalReportContent, handled_ids: set[str] | Nbackticked ID is a dead identifierset_title and add_section run the same dead-ID check in the loop, so the agent can- correct a dead ID on its next call. This is the backstop for what reaches the end.+ correct a dead ID on its next call, and `_unwrap_dead_ids` strips whatever survives+ that. The dead-ID check here only fires if both of those missed something."""if not content.title.strip():return "agent did not call set_title"@@ -269,7 +295,11 @@ def run_eval_report_agent(evaluation_target=evaluation_target,)- from posthog.temporal.ai_observability.eval_reports.metrics import increment_errors, increment_report_generated+ from posthog.temporal.ai_observability.eval_reports.metrics import (+ increment_dead_ids_unwrapped,+ increment_errors,+ increment_report_generated,+ )# The agent's query tools would fail under the same sustained ClickHouse load,# which could produce a narrative built on missing data.@@ -343,6 +373,7 @@ def run_eval_report_agent("report": EvalReportContent(evaluation_target=evaluation_target, metrics=metrics),TRACE_ID_ALLOWLIST_KEY: [],SESSION_ID_ALLOWLIST_KEY: [],+ REPORT_RUN_HANDLE_KEY: {},}callbacks = build_langchain_callbacks(@@ -369,7 +400,20 @@ def run_eval_report_agent(content.evaluation_target = evaluation_targetcontent.metrics = metrics- validation_error = _validate_agent_output(content, _handled_ids(result))+ handled_ids = _handled_ids(result)+ unwrapped = _unwrap_dead_ids(content, handled_ids)+ if unwrapped:+ increment_dead_ids_unwrapped(len(unwrapped))+ logger.warning(+ "llma_eval_reports_agent_dead_ids_unwrapped",+ team_id=inputs.team_id,+ evaluation_id=inputs.evaluation_id,+ dead_id_count=len(unwrapped),+ trace_id=resolved_trace_id,+ session_id=resolved_session_id,+ )++ validation_error = _validate_agent_output(content, handled_ids)if validation_error:increment_report_generated("fallback_validation")diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.pyindex 1a8430701fd4..bfd5dbeaed6c 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/prompts.py@@ -35,7 +35,7 @@ You build the report incrementally by calling three output tools:- Don't invent sections just to fill space. One or two sections is enough for a routine report.- Don't speculate beyond the data. Every claim should be traceable to a tool result. State uncertainty clearly.- Don't emit emoji or marketing language. Be technical and factual.-- Don't put an ID in backticks unless you already called `add_citation` for it, and then wrap that exact ID in one pair of backticks. Cite an example before you write the section that mentions it, because `add_section` rejects a section that backticks an uncited ID. That includes a session or trace ID you read but did not cite, and a run_id from `list_recent_report_runs` or `get_report_run`, which can never be cited. Name a prior run by its period instead.+- Don't put an ID in backticks unless you already called `add_citation` for it, and then wrap that exact ID in one pair of backticks. Cite an example before you write the section that mentions it, because `add_section` rejects a section that backticks an uncited ID. That includes a session or trace ID you read but did not cite, and any ID quoted by a prior report, which belongs to another period. Name a prior run by its period, never by its handle.- Don't put an ID in the report title or in a section title. A title renders as plain text, so an ID there stays dead even after you cite it. `set_title` and `add_section` reject a title that backticks an ID. Mention the ID in the section body instead.## Query tools available@@ -46,7 +46,7 @@ You build the report incrementally by calling three output tools:- **`sample_eval_results(outcome="all"|{outcome_options}, limit{sample_ordering_signature})`**: sample evaluation rows. {sample_ordering_instruction}{detail_tools_section}- **`list_recent_report_runs(since_days, limit)`**: compact index of prior runs with title, period, total runs, and result rates. Call this on every report.-- **`get_report_run(run_id)`**: full content for a prior report run.+- **`get_report_run(run_id)`**: full content for a prior report run. `run_id` is the short handle from the index, e.g. `run_1`.## Grounding rulediff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.pyindex 40090eecc29b..041e5256e003 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/schema.py@@ -120,6 +120,15 @@ class Citation:)+def citation_wrappers(cited_id: str) -> tuple[str, ...]:+ """Every inline wrapper the delivery renderer turns into a citation link.++ The renderer and the dead-identifier guard must agree on this list. A guard that+ accepts fewer wrappers rejects prose the renderer would have linked correctly.+ """+ return (f"`` `{cited_id}` ``", f"`{cited_id}`", f"<{cited_id}>")++@dataclassclass ReportSection:"""A titled markdown section of the narrative. Title is agent-chosen."""diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py b/posthog/temporal/ai_observability/eval_reports/report_agent/state.pyindex 7aab5126ddf2..bf2fc9e5ef7f 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/state.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/state.py@@ -7,6 +7,8 @@ from langgraph.managed import RemainingStepsfrom posthog.temporal.ai_observability.eval_reports.report_agent.schema import EvalReportContent+REPORT_RUN_HANDLE_KEY = "report_run_handles"+class EvalReportAgentState(TypedDict):"""State for the evaluation report agent graph.@@ -44,3 +46,6 @@ class EvalReportAgentState(TypedDict):report: EvalReportContenttrace_id_allowlist: list[str]session_id_allowlist: list[str]+ # Short handle -> run UUID for every past run the agent has listed. The agent sees+ # only the handle, because a run UUID is UUID-shaped but can never be cited.+ report_run_handles: dict[str, 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 c5d710f3c933..877e496b171a 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@@ -469,7 +469,7 @@ class TestRunEvalReportAgentDeadIdGuard(SimpleTestCase):@patch.object(graph, "create_react_agent")@patch.object(graph, "build_flex_first_chat_client")@patch.object(graph, "_compute_metrics")- def test_uncited_opaque_id_from_the_result_allowlist_falls_back(+ def test_uncited_opaque_id_from_the_result_allowlist_is_unwrapped(self, mock_metrics, _mock_build_llm, mock_create_agent, _mock_build_callbacks):mock_metrics.return_value = EvalReportMetrics()@@ -501,8 +501,9 @@ class TestRunEvalReportAgentDeadIdGuard(SimpleTestCase):))- self.assertEqual(content.title, "Automated fallback report for Relevance")- self.assertIn(session_id, content.sections[0].content)+ # One dead identifier costs the reader a link, not the whole analysis.+ self.assertEqual(content.title, "A report")+ self.assertEqual(content.sections[0].content, f"See {session_id}.")class TestRunEvalReportAgentMetricsUnavailable(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 963a89749e25..7b565c8d4e38 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@@ -4,7 +4,7 @@ import reimport jsonimport timeimport datetime as dt-from typing import NotRequired, TypedDict+from typing import Any, NotRequired, TypedDictfrom posthog.test.base import BaseTestfrom unittest.mock import (@@ -33,6 +33,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (EvalReportContent,ReportSection,)+from posthog.temporal.ai_observability.eval_reports.report_agent.state import REPORT_RUN_HANDLE_KEYfrom posthog.temporal.ai_observability.eval_reports.report_agent.tools import (_SESSION_TRACES_SQL,_UUID_RE,@@ -55,6 +56,7 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.tools import (sample_session_details,sample_trace_details,set_title,+ strip_dead_backticked_ids,)_VALID_GEN_ID = "12345678-1234-1234-1234-123456789abc"@@ -86,6 +88,7 @@ class _ReportToolState(TypedDict):report: EvalReportContenttrace_id_allowlist: list[str]session_id_allowlist: list[str]+ report_run_handles: NotRequired[dict[str, str]]evaluation_target: NotRequired[str]team_id: NotRequired[int]evaluation_id: NotRequired[str]@@ -724,6 +727,16 @@ class TestAddSection(SimpleTestCase):self.assertNotIn("Error", result)self.assertEqual(len(state["report"].sections), 1)+ def test_rejects_section_with_a_backticked_run_handle(self):+ # A handle is not UUID-shaped, so only the handle map makes the guard read it as an ID.+ state = _state_with_empty_report()+ state["report_run_handles"] = {"run_1": _VALID_GEN_ID}++ result = _add_section_fn(state=state, title="Summary", content="Steady since `run_1`.")++ self.assertIn("Error", result)+ self.assertEqual(state["report"].sections, [])+def test_rejects_cited_backticked_id_in_a_section_title(self):# Section titles reach the reader as a heading, so citation linking never runs over them.state = _state_with_empty_report()@@ -773,6 +786,21 @@ class TestDeadBacktickedIds(SimpleTestCase):set(),[_VALID_GEN_ID.upper()],),+ (+ # The renderer links this wrapper, so the guard must not call it dead.+ "cited_uuid_in_double_backtick_span_links",+ f"See `` `{_VALID_GEN_ID}` `` for the regression.",+ [Citation(generation_id=_VALID_GEN_ID, trace_id=_VALID_TRACE_ID)],+ set(),+ [],+ ),+ (+ "uncited_uuid_in_double_backtick_span_is_dead",+ f"Steady since run `` `{_RUN_ID}` ``.",+ [],+ set(),+ [_RUN_ID],+ ),("cited_uuid_double_backticks_is_dead",f"See ``{_VALID_GEN_ID}``.",@@ -788,6 +816,31 @@ class TestDeadBacktickedIds(SimpleTestCase):) -> None:self.assertEqual(_dead_backticked_ids(text, citations, handled_ids), expected)+ @parameterized.expand(+ [+ ("uncited_uuid_loses_its_backticks", f"Steady since run `{_RUN_ID}`.", f"Steady since run {_RUN_ID}."),+ (+ "uncited_uuid_loses_its_double_backtick_span",+ f"Steady since run `` `{_RUN_ID}` ``.",+ f"Steady since run {_RUN_ID}.",+ ),+ (+ "cited_id_keeps_its_backticks",+ f"See `{_OPAQUE_SESSION_ID}`.",+ f"See `{_OPAQUE_SESSION_ID}`.",+ ),+ (+ "cited_id_keeps_its_double_backtick_span",+ f"See `` `{_OPAQUE_SESSION_ID}` ``.",+ f"See `` `{_OPAQUE_SESSION_ID}` ``.",+ ),+ ("prose_keeps_its_backticks", "The `total_runs` field.", "The `total_runs` field."),+ ]+ )+ def test_strip_dead_backticked_ids(self, _name: str, text: str, expected: str) -> None:+ citations = [Citation(session_id=self._OPAQUE_SESSION_ID)]+ self.assertEqual(strip_dead_backticked_ids(text, citations, {self._OPAQUE_SESSION_ID}), expected)+def test_scan_stays_linear_on_a_whitespace_run(self):# A model that degenerates into whitespace after a stray backtick writes exactly the# input that makes an ambiguous backtick pattern backtrack. The check runs inside the@@ -1037,9 +1090,10 @@ class TestListAndGetReportRun(BaseTest):period_start=now - dt.timedelta(days=2),period_end=now - dt.timedelta(days=1),)- self.state = {+ self.state: dict[str, Any] = {"evaluation_id": str(self.evaluation.id),"period_start": now.isoformat(),+ REPORT_RUN_HANDLE_KEY: {},}def test_list_returns_compact_index_newest_first(self):@@ -1049,10 +1103,25 @@ class TestListAndGetReportRun(BaseTest):self.assertEqual(result[0]["pass_rate"], 94.2)self.assertEqual(result[0]["total_runs"], 53)self.assertNotIn("result_rates", result[0])- self.assertIn("run_id", result[0])# Full content intentionally omittedself.assertNotIn("content", result[0])+ def test_list_hands_out_handles_and_get_resolves_them(self):+ # A run UUID is UUID-shaped but can never be cited, so an agent that repeats one in+ # backticked prose writes a dead identifier. It never sees the UUID to repeat.+ listed = json.loads(_list_recent_report_runs_fn(state=self.state))+ handles = [run["run_id"] for run in listed]++ self.assertNotIn(str(self.recent_run.id), handles)+ self.assertEqual(len(set(handles)), len(handles))+ fetched = json.loads(_get_report_run_fn(state=self.state, run_id=handles[0]))+ self.assertEqual(fetched["content"]["title"], "Recent report")+ self.assertEqual(fetched["run_id"], handles[0])++ def test_get_rejects_an_unknown_handle(self):+ result = json.loads(_get_report_run_fn(state=self.state, run_id="run_9"))+ self.assertIn("error", result)+def test_list_filters_by_since_days(self):result = json.loads(_list_recent_report_runs_fn(state=self.state, since_days=3))self.assertEqual(len(result), 1)@@ -1085,8 +1154,8 @@ class TestListAndGetReportRun(BaseTest):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.assertNotIn("Trace report", {run["title"] for run in generation_runs})+ self.assertEqual([run["title"] for run in trace_runs], ["Trace report"])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"],@@ -1098,7 +1167,7 @@ class TestListAndGetReportRun(BaseTest):# excluded by a strict `lt` filter, dropping the immediately previous report —# the most useful one for delta/continuity analysis.boundary_start = dt.datetime.fromisoformat(self.state["period_start"])- boundary_run = self.EvaluationReportRun.objects.create(+ self.EvaluationReportRun.objects.create(report=self.report,content={"title": "Back-to-back report", "sections": []},metadata={"pass_rate": 77.7, "total_runs": 11},@@ -1108,7 +1177,7 @@ class TestListAndGetReportRun(BaseTest):result = json.loads(_list_recent_report_runs_fn(state=self.state))titles = [r["title"] for r in result]self.assertIn("Back-to-back report", titles)- boundary_entry = next(r for r in result if r["run_id"] == str(boundary_run.id))+ boundary_entry = next(r for r in result if r["title"] == "Back-to-back report")self.assertEqual(boundary_entry["pass_rate"], 77.7)self.assertEqual(boundary_entry["total_runs"], 11)@@ -1117,7 +1186,7 @@ class TestListAndGetReportRun(BaseTest):# downstream store activity mirrors them into metadata. The tool must read# either source so it stays correct if the mirror is removed.now = timezone.now()- content_only_run = self.EvaluationReportRun.objects.create(+ self.EvaluationReportRun.objects.create(report=self.report,content={"title": "Content-only metrics",@@ -1132,7 +1201,7 @@ class TestListAndGetReportRun(BaseTest):period_end=now - dt.timedelta(hours=1),)result = json.loads(_list_recent_report_runs_fn(state=self.state))- entry = next(r for r in result if r["run_id"] == str(content_only_run.id))+ entry = next(r for r in result if r["title"] == "Content-only metrics")self.assertEqual(entry["pass_rate"], 75.0)self.assertEqual(entry["result_rates"], {"pass": 75.0, "fail": 25.0, "na": 0.0})self.assertEqual(entry["total_runs"], 8)@@ -1152,10 +1221,10 @@ class TestListAndGetReportRun(BaseTest):period_end=now - dt.timedelta(hours=1),)- listed_run_ids = {run["run_id"] for run in json.loads(_list_recent_report_runs_fn(state=self.state))}+ listed_titles = {run["title"] for run in json.loads(_list_recent_report_runs_fn(state=self.state))}fetched = json.loads(_get_report_run_fn(state=self.state, run_id=str(unavailable_run.id)))- self.assertNotIn(str(unavailable_run.id), listed_run_ids)+ self.assertNotIn("Metrics temporarily unavailable", listed_titles)self.assertIn("error", fetched)def test_get_rejects_non_uuid(self):diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.pyindex 9edd997f5730..d118fa716182 100644--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py@@ -37,9 +37,11 @@ from posthog.temporal.ai_observability.eval_reports.report_agent.schema import (ReportSection,calculate_boolean_pass_rate,calculate_result_rates,+ citation_wrappers,normalize_metrics_payload,normalize_report_content_payload,)+from posthog.temporal.ai_observability.eval_reports.report_agent.state import REPORT_RUN_HANDLE_KEYfrom posthog.temporal.ai_observability.eval_reports.targets import (GENERATION_TARGET,SESSION_ID_ALLOWLIST_KEY,@@ -70,7 +72,7 @@ _UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f# excludes only the backtick, so the run to the next one is unambiguous and the# scan stays linear. A class that also matched the surrounding whitespace makes# every split of a whitespace run a candidate, and the agent writes the input.-_BACKTICKED_TOKEN_RE = re.compile(r"`+([^`]*)`+")+_BACKTICKED_TOKEN_RE = re.compile(r"`` `([^`]*)` ``|`+([^`]*)`+")# Match a canonical UUID anywhere it is used as a whole token. Opaque IDs are not# UUID-shaped, so the guard also checks the session's handled-ID allowlists.@@ -128,19 +130,50 @@ def _is_allowlisted(state: dict, allowlist_key: str, value: str) -> bool:def _handled_ids(state: dict) -> set[str]:- """Return every target ID this run's queries returned, across both allowlists.+ """Return every identifier this run handed the agent: target IDs and run handles.The agent state and the finished agent result are the same mapping, so thein-loop guard and the final validation key on one definition of a handled ID.+ A run handle is not UUID-shaped, so without it here the guard reads a backticked+ handle as prose and ships an internal token to the reader."""handled: set[str] = set()for allowlist_key in (TRACE_ID_ALLOWLIST_KEY, SESSION_ID_ALLOWLIST_KEY):allowlist = state.get(allowlist_key)if isinstance(allowlist, list):handled.update(value for value in allowlist if isinstance(value, str))+ handles = state.get(REPORT_RUN_HANDLE_KEY)+ if isinstance(handles, dict):+ handled.update(handle for handle in handles if isinstance(handle, str))return handled+def _report_run_handle(state: dict, run_id: str) -> str:+ """Return the short handle the agent uses for a past run, minting one on first sight.++ A run UUID looks like a citable ID to the model but can never be cited, so handing it+ over invites backticked prose the guard then has to treat as a dead identifier.+ """+ handles = state.get(REPORT_RUN_HANDLE_KEY)+ if not isinstance(handles, dict):+ return run_id+ for handle, known_run_id in handles.items():+ if known_run_id == run_id:+ return handle+ handle = f"run_{len(handles) + 1}"+ handles[handle] = run_id+ return handle+++def _resolve_report_run_handle(state: dict, handle: str) -> str | None:+ """Return the run UUID a handle stands for, or None when the handle is unknown."""+ handles = state.get(REPORT_RUN_HANDLE_KEY)+ if isinstance(handles, dict) and handle in handles:+ return handles[handle]+ # A raw UUID still resolves, so a run started before handles existed keeps working.+ return handle if _UUID_RE.fullmatch(handle or "") else None++def _report_run_target_filter(evaluation_target: str) -> Q:target = resolve_evaluation_target(evaluation_target)if target == GENERATION_TARGET:@@ -1286,7 +1319,8 @@ def list_recent_report_runs() -> str:"""List metadata for previous report runs of this evaluation.- Returns a compact index: run_id, period, title, outcome rates, total runs.+ Returns a compact index: run_id (a short handle, not a UUID), period, title,+ outcome rates, total runs.No full content — use this to discover which past runs look interesting,then call `get_report_run(run_id)` to pull the full narrative for the onesworth reading. This two-step pattern keeps context small when scanning a@@ -1333,7 +1367,7 @@ def list_recent_report_runs(normalized_metrics = normalize_metrics_payload({**metadata, **metrics})output_type = normalized_metrics["output_type"]entry = {- "run_id": str(run.id),+ "run_id": _report_run_handle(state, str(run.id)),"period_start": str(run.period_start),"period_end": str(run.period_end),"title": content.get("title", ""),@@ -1362,17 +1396,18 @@ def get_report_run(sections, citations, metrics).Args:- run_id: The report run UUID, from list_recent_report_runs.+ run_id: The run handle from list_recent_report_runs, e.g. "run_1"."""from products.ai_observability.backend.models.evaluation_reports import EvaluationReportRun- if not _UUID_RE.fullmatch(run_id or ""):- return json.dumps({"error": "Invalid run_id format"})+ resolved_run_id = _resolve_report_run_handle(state, run_id)+ if resolved_run_id is None:+ return json.dumps({"error": f"Unknown run handle {run_id!r}. Use one returned by list_recent_report_runs."})# 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 = EvaluationReportRun.objects.filter(id=resolved_run_id, report__evaluation_id=evaluation_id)runs = runs.filter(_report_run_target_filter(evaluation_target))runs = runs.filter(_completed_report_run_filter())try:@@ -1385,7 +1420,7 @@ def get_report_run(return json.dumps({- "run_id": str(run.id),+ "run_id": _report_run_handle(state, str(run.id)),"period_start": str(run.period_start),"period_end": str(run.period_end),"content": content,@@ -1492,25 +1527,56 @@ def set_title(return f"Title set: {clean!r}"+def _span_token(match: re.Match[str]) -> str:+ """The candidate identifier inside an inline-code span, whichever branch matched.++ The `` `id` `` wrapper the renderer links holds backticks of its own, so it needs a+ branch to itself. The general branch stops at the inner pair and skips over the ID.+ """+ inner = match.group(1) if match.group(1) is not None else match.group(2)+ return inner.strip()++def _dead_backticked_ids(text: str, citations: list[Citation], handled_ids: set[str]) -> list[str]:"""Return backticked IDs in `text` that no report renderer turns into a link.- A renderer links only an exactly-cited ID wrapped in one pair of backticks. An+ A renderer links an exactly-cited ID in any wrapper `citation_wrappers` names. AnID is any backticked token the session handled (its query allowlists) or acanonical UUID; other backticked spans are prose and stay untouched."""cited_ids = {citation.cited_id() for citation in citations}dead: list[str] = []for match in _BACKTICKED_TOKEN_RE.finditer(text):- token = match.group(1).strip()- if token not in handled_ids and _UUID_SHAPE_RE.fullmatch(token) is None:- continue- links = token in cited_ids and match.group(0) == f"`{token}`"- if not links and token not in dead:+ token = _span_token(match)+ if _is_dead_id_span(match.group(0), token, cited_ids, handled_ids) and token not in dead:dead.append(token)return dead+def _is_dead_id_span(span: str, token: str, cited_ids: Container[str], handled_ids: Container[str]) -> bool:+ """Is this inline-code span an ID that no report renderer turns into a link?"""+ if token not in handled_ids and _UUID_SHAPE_RE.fullmatch(token) is None:+ return False+ return not (token in cited_ids and span in citation_wrappers(token))+++def strip_dead_backticked_ids(text: str, citations: list[Citation], handled_ids: set[str]) -> str:+ """Unwrap every dead backticked ID in `text`, leaving the ID as plain prose.++ This is what the tool errors ask the agent to do itself. Applying it before delivery+ keeps a whole report's analysis instead of trading it for a deterministic stub.+ """+ cited_ids = {citation.cited_id() for citation in citations}++ def unwrap(match: re.Match[str]) -> str:+ token = _span_token(match)+ if _is_dead_id_span(match.group(0), token, cited_ids, handled_ids):+ return token+ return match.group(0)++ return _BACKTICKED_TOKEN_RE.sub(unwrap, text)++def _dead_backticked_ids_in_report(titles: Iterable[str], bodies: Iterable[str], citations: list[Citation], handled_ids: set[str]) -> list[str]:@@ -1588,7 +1654,7 @@ def add_section(return (f"Error: the following backticked IDs will not render as citation links: {preview}. ""Cite each generation, trace, or session with add_citation, then use one pair of backticks around the exact cited ID. "- "Run IDs from list_recent_report_runs cannot be cited. Name a prior run by its period and remove the backticks."+ "An ID you read in a prior report belongs to another period and cannot be cited here. Remove its backticks.")state["report"].sections.append(ReportSection(title=clean_title, content=clean_content))return f"Section {len(state['report'].sections)}/{MAX_REPORT_SECTIONS} added: {clean_title!r} ({len(clean_content)} chars)"