: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(dashboards): bound the optimized run_insights output (#103519)
posthog[bot]8a212087aa2f
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 32d499bc7a88..42a3bba623f8 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -119,7 +119,13 @@ from products.dashboards.backend.api.widget_openapi_serializers import (UpdateDashboardWidgetRequestOpenApi,WidgetCatalogResponseSerializer,)-from products.dashboards.backend.constants import DASHBOARD_GRID_COLUMN_COUNT, MAX_WIDGETS_BATCH_SIZE+from products.dashboards.backend.constants import (+ DASHBOARD_GRID_COLUMN_COUNT,+ MAX_WIDGETS_BATCH_SIZE,+ RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS,+ RUN_INSIGHTS_MAX_TOTAL_CHARS,+ RUN_INSIGHTS_MIN_TILE_CHARS,+)from products.dashboards.backend.facade.api import DashboardTileBasicSerializerfrom products.dashboards.backend.facade.enums import PrivilegeLevel, RestrictionLevelfrom products.dashboards.backend.feature_flags import dashboard_widgets_enabled@@ -130,6 +136,15 @@ from products.dashboards.backend.models.dashboard import ()from products.dashboards.backend.models.dashboard_tile import ButtonTile, DashboardTile, Textfrom products.dashboards.backend.models.dashboard_widget import DashboardWidget+from products.dashboards.backend.run_insights_output import (+ bound_formatted_result,+ parse_max_result_chars,+ parse_tile_ids,+ render_unsupported_result,+ tile_budget,+ tile_fits_response_budget,+ unrun_tile_results,+)from products.dashboards.backend.widget_access import (check_widget_tile_product_access,get_widget_api_scope_error,@@ -3247,8 +3262,30 @@ class DashboardsViewSet(OpenApiTypes.STR,enum=["optimized", "json"],description=(- "'optimized' (default) returns LLM-friendly formatted text per insight. "- "'json' returns the raw query result objects."+ "'optimized' (default) returns LLM-friendly formatted text per insight, bounded by "+ "max_result_chars. 'json' returns the raw query result objects, unbounded."+ ),+ ),+ OpenApiParameter(+ "tile_ids",+ OpenApiTypes.STR,+ description=(+ "Comma-separated dashboard tile IDs to run. Defaults to every insight tile on the "+ "dashboard. Use it to read one tile without receiving the others. An ID that is not on "+ "this dashboard is rejected."+ ),+ ),+ OpenApiParameter(+ "max_result_chars",+ OpenApiTypes.INT,+ description=(+ "Per-tile character budget for 'optimized' output, truncation marker included. A longer "+ "table keeps its header and both ends, and names how many rows were dropped from the "+ f"middle. Defaults to {RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS}; pass 0 for the whole table, "+ f"or {RUN_INSIGHTS_MIN_TILE_CHARS} or more, since a smaller budget cannot carry the marker. "+ "Ignored when output_format is 'json'. Any value above zero is also held down to what the "+ f"response has left of its {RUN_INSIGHTS_MAX_TOTAL_CHARS} character budget, and tiles past "+ "that budget are not run."),),VARIABLES_OVERRIDE_PARAM,@@ -3261,6 +3298,10 @@ class DashboardsViewSet("""Run all insights on a dashboard and return their results."""dashboard = self.get_object()output_format = request.query_params.get("output_format", "optimized")+ requested_tile_ids = parse_tile_ids(request.query_params.get("tile_ids"))+ max_result_chars = (+ parse_max_result_chars(request.query_params.get("max_result_chars")) if output_format == "optimized" else 0+ )access_method = dashboard_access_method(request)record_dashboard_access(access_method)@@ -3282,20 +3323,48 @@ class DashboardsViewSet()self.user_permissions.set_preloaded_dashboard_tiles(list(tiles))- sorted_tiles = DashboardTile.sort_tiles_by_layout(tiles, "sm")+ # Order over every tile first, so a tile_ids subset keeps the dashboard's own ordering.+ ordered_tiles = list(enumerate(DashboardTile.sort_tiles_by_layout(tiles, "sm")))+ if requested_tile_ids:+ wanted_tile_ids = set(requested_tile_ids)+ unknown_ids = sorted(wanted_tile_ids - {tile.id for _, tile in ordered_tiles})+ if unknown_ids:+ raise exceptions.ValidationError(+ f"These tile IDs are not on this dashboard: {', '.join(str(tile_id) for tile_id in unknown_ids)}. "+ "Read the dashboard to see the tiles it has."+ )+ ordered_tiles = [(order, tile) for order, tile in ordered_tiles if tile.id in wanted_tile_ids]++ # Narrowing to runnable tiles here lets the budget path count what it leaves out.+ insight_tiles = [+ (order, tile, tile.insight) for order, tile in ordered_tiles if tile.insight and tile.insight.query+ ]tile_results = []- for order, tile in enumerate(sorted_tiles):- if not tile.insight or not tile.insight.query:- continue+ used_chars = 0+ for index, (order, tile, insight) in enumerate(insight_tiles):+ if output_format == "optimized" and not tile_fits_response_budget(used_chars):+ tile_results.extend(unrun_tile_results(insight_tiles[index:]))+ break+tile_context = {**context, "dashboard_tile": tile, "order": order}tile_data = DashboardTileResultSerializer(tile, context=tile_context).dataif output_format == "optimized":insight_data = tile_data.get("insight") or {}- formatted = self._format_insight_for_llm(tile.insight, insight_data)- if formatted is not None and insight_data:+ raw_result = insight_data.get("result")+ if insight_data and raw_result is not None:+ formatted = self._format_insight_for_llm(insight, insight_data)+ if formatted is None:+ # No formatter covers this query type, so the raw result still has to be bounded.+ formatted = render_unsupported_result(raw_result)+ formatted = bound_formatted_result(+ formatted,+ tile_id=tile.id,+ max_chars=tile_budget(max_result_chars, used_chars),+ )insight_data["result"] = formatted+ used_chars += len(formatted)tile_results.append(tile_data)@@ -3318,18 +3387,9 @@ class DashboardsViewSet(if not dashboard_widgets_enabled(team=self.team, user=cast(User, request.user)):raise exceptions.PermissionDenied("Dashboard widgets are not enabled for this project.")- tile_ids_param = request.query_params.get("tile_ids")- if not tile_ids_param:- raise exceptions.ValidationError("tile_ids is required.")-- try:- tile_ids = [int(tile_id.strip()) for tile_id in tile_ids_param.split(",") if tile_id.strip()]- except ValueError as exc:- raise exceptions.ValidationError("tile_ids must be a comma-separated list of integers.") from exc-- tile_ids = list(dict.fromkeys(tile_ids))+ tile_ids = parse_tile_ids(request.query_params.get("tile_ids"))if not tile_ids:- raise exceptions.ValidationError("tile_ids must include at least one tile ID.")+ raise exceptions.ValidationError("tile_ids is required.")if len(tile_ids) > MAX_WIDGETS_BATCH_SIZE:raise exceptions.ValidationError(f"At most {MAX_WIDGETS_BATCH_SIZE} tile_ids may be requested at once.")diff --git a/products/dashboards/backend/api/test/test_run_insights.py b/products/dashboards/backend/api/test/test_run_insights.pyindex 5e2cb9f70176..d41d2adcf246 100644--- a/products/dashboards/backend/api/test/test_run_insights.py+++ b/products/dashboards/backend/api/test/test_run_insights.py@@ -3,6 +3,7 @@ import jsonfrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.schema import DateRange, EventsNode, InsightVizNode, TrendsFilter, TrendsQuery@@ -12,16 +13,18 @@ from posthog.models.organization import Organizationfrom posthog.models.team import Teamfrom products.dashboards.backend.access import DashboardAccessMethod+from products.dashboards.backend.api.dashboard import DashboardsViewSet+from products.dashboards.backend.constants import RUN_INSIGHTS_MIN_TILE_CHARSfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile, Textfrom products.product_analytics.backend.facade.models import Insight, InsightVariable-def _trends_query_dict(event: str = "$pageview") -> dict:+def _trends_query_dict(event: str = "$pageview", date_from: str = "-7d") -> dict:return InsightVizNode(source=TrendsQuery(series=[EventsNode(event=event)],- dateRange=DateRange(date_from="-7d"),+ dateRange=DateRange(date_from=date_from),trendsFilter=TrendsFilter(display="ActionsLineGraph"),),).model_dump()@@ -101,6 +104,139 @@ class TestDashboardRunInsights(APIBaseTest):if isinstance(result, str):self.assertIn("|", result)+ def test_tile_ids_runs_only_the_selected_tiles(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ first_id, _ = self.dashboard_api.create_insight(+ {"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]}+ )+ second_id, _ = self.dashboard_api.create_insight(+ {"name": "B", "query": _trends_query_dict("$autocapture"), "dashboards": [dashboard_id]}+ )+ second_tile = DashboardTile.objects.get(dashboard_id=dashboard_id, insight_id=second_id)++ body = self._run(dashboard_id, output_format="json", tile_ids=str(second_tile.id))++ self.assertEqual([tile["insight"]["id"] for tile in body["results"]], [second_id])+ # The order stays the tile's position on the dashboard, not its index in the subset.+ self.assertEqual(body["results"][0]["order"], 1)+ self.assertNotEqual(first_id, second_id)++ def test_rejects_a_non_numeric_tile_id(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})++ response = self.client.get(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/run_insights/",+ data={"tile_ids": "12,abc"},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ def test_rejects_a_tile_id_that_is_not_on_this_dashboard(self) -> None:+ # Dropping the unknown ID instead would answer a stale tile_ids with an empty dashboard.+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ insight_id, _ = self.dashboard_api.create_insight(+ {"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]}+ )+ tile = DashboardTile.objects.get(dashboard_id=dashboard_id, insight_id=insight_id)++ response = self.client.get(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/run_insights/",+ data={"tile_ids": f"{tile.id},{tile.id + 1000}"},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertIn(str(tile.id + 1000), response.json()["detail"])++ @parameterized.expand([("negative", "-1"), ("too_small_to_hold_a_marker", "10")])+ def test_rejects_an_unusable_max_result_chars(self, _name: str, max_result_chars: str) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})++ response = self.client.get(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/run_insights/",+ data={"max_result_chars": max_result_chars},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)++ def test_optimized_result_is_held_to_the_per_tile_budget(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ self.dashboard_api.create_insight(+ {"name": "A", "query": _trends_query_dict(date_from="-90d"), "dashboards": [dashboard_id]}+ )++ full = self._run(dashboard_id, refresh="blocking", max_result_chars="0")["results"][0]["insight"]["result"]+ if not isinstance(full, str):+ self.skipTest("LLM formatting is unavailable, so there is nothing to bound")++ bounded = self._run(dashboard_id, refresh="blocking", max_result_chars="600")["results"][0]["insight"]["result"]++ self.assertLessEqual(len(bounded), 600)+ self.assertLess(len(bounded), len(full))+ self.assertIn("tile_ids=", bounded)+ # A head-only cut would keep nothing from the recent end of a 90-day table.+ full_lines = [line for line in full.splitlines() if line]+ self.assertTrue(set(full_lines[len(full_lines) // 2 :]) & set(bounded.splitlines()))++ def test_optimized_stops_running_tiles_at_the_response_budget(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ self.dashboard_api.create_insight({"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]})+ self.dashboard_api.create_insight(+ {"name": "B", "query": _trends_query_dict("$autocapture"), "dashboards": [dashboard_id]}+ )++ with patch(+ "products.dashboards.backend.run_insights_output.RUN_INSIGHTS_MAX_TOTAL_CHARS",+ RUN_INSIGHTS_MIN_TILE_CHARS,+ ):+ body = self._run(dashboard_id, refresh="blocking")++ self.assertEqual(len(body["results"]), 2)+ self.assertNotIn("Not run", str(body["results"][0]["insight"]["result"]))+ self.assertIn("Not run", body["results"][1]["insight"]["result"])+ self.assertEqual(+ set(body["results"][1]["insight"].keys()),+ {"id", "short_id", "name", "derived_name", "result"},+ )++ def test_json_format_ignores_max_result_chars(self) -> None:+ # The parameter is documented as optimized-only, so a bad value must not fail a json read.+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ self.dashboard_api.create_insight({"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]})++ body = self._run(dashboard_id, output_format="json", refresh="blocking", max_result_chars="-1")++ self.assertIsInstance(body["results"][0]["insight"]["result"], list)++ def test_bounds_a_result_no_formatter_covers(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ self.dashboard_api.create_insight({"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]})++ with patch.object(DashboardsViewSet, "_format_insight_for_llm", return_value=None):+ body = self._run(dashboard_id, refresh="blocking", max_result_chars=str(RUN_INSIGHTS_MIN_TILE_CHARS))++ result = body["results"][0]["insight"]["result"]+ self.assertIsInstance(result, str)+ self.assertLessEqual(len(result), RUN_INSIGHTS_MIN_TILE_CHARS)+ self.assertIn("tile_ids=", result)++ def test_a_generous_per_tile_budget_cannot_overshoot_the_response_budget(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ self.dashboard_api.create_insight(+ {"name": "A", "query": _trends_query_dict(date_from="-90d"), "dashboards": [dashboard_id]}+ )++ with patch(+ "products.dashboards.backend.run_insights_output.RUN_INSIGHTS_MAX_TOTAL_CHARS",+ RUN_INSIGHTS_MIN_TILE_CHARS,+ ):+ body = self._run(dashboard_id, refresh="blocking", max_result_chars="1000000")++ result = body["results"][0]["insight"]["result"]+ if not isinstance(result, str):+ self.skipTest("LLM formatting is unavailable, so there is nothing to bound")+ rows = [line for line in result.splitlines() if not line.startswith("[")]+ self.assertLessEqual(sum(len(row) + 1 for row in rows), RUN_INSIGHTS_MIN_TILE_CHARS)+def test_skips_text_tiles(self) -> None:dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})self.dashboard_api.create_insight({"name": "A", "query": _trends_query_dict(), "dashboards": [dashboard_id]})diff --git a/products/dashboards/backend/constants.py b/products/dashboards/backend/constants.pyindex b7cca2103988..8cca24968103 100644--- a/products/dashboards/backend/constants.py+++ b/products/dashboards/backend/constants.py@@ -53,3 +53,16 @@ WIDGET_DATE_FROM_LABELS: dict[str, str] = {"-30d": "Last 30 days","-90d": "Last 90 days",}++# `optimized` run_insights output is read by agents with a limited context window, so each tile's+# formatted table is held to this many characters unless the caller asks for more.+RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS = 2000++# Ceiling on the whole `optimized` run_insights response. Tiles past it are not run.+RUN_INSIGHTS_MAX_TOTAL_CHARS = 30000++# Below this, a tile can only carry a sliced header, so it is reported as not run instead.+RUN_INSIGHTS_MIN_TILE_CHARS = 200++# The marker list grows with the dashboard, so it gets a ceiling of its own.+RUN_INSIGHTS_MAX_UNRUN_TILES = 25diff --git a/products/dashboards/backend/run_insights_output.py b/products/dashboards/backend/run_insights_output.pynew file mode 100644index 000000000000..175fa5318beb--- /dev/null+++ b/products/dashboards/backend/run_insights_output.py@@ -0,0 +1,170 @@+import json+from typing import Any++from rest_framework import exceptions++from products.dashboards.backend.constants import (+ RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS,+ RUN_INSIGHTS_MAX_TOTAL_CHARS,+ RUN_INSIGHTS_MAX_UNRUN_TILES,+ RUN_INSIGHTS_MIN_TILE_CHARS,+)+from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.facade.models import Insight++ELISION_NOTE = (+ "[{omitted} of {total} rows omitted here. To read the whole table, run dashboard-insights-run "+ "with tile_ids={tile_id} and max_result_chars=0.]"+)++CUT_NOTE = (+ "[Cut at {max_chars} characters. To read the whole table, run dashboard-insights-run with "+ "tile_ids={tile_id} and max_result_chars=0.]"+)++BUDGET_NOTE = (+ "[Not run. The response reached its {budget} character budget. To read this tile, run "+ "dashboard-insights-run again with tile_ids={tile_id}.]"+)++UNLISTED_NOTE = " [{unlisted} further tiles are not listed. Read the dashboard for their IDs.]"+++def parse_tile_ids(raw: str | None) -> list[int]:+ """Parse the `tile_ids` query param into ordered, deduplicated IDs. Empty means the param was+ not given, which each caller reads its own way."""+ if raw is None or not raw.strip():+ return []+ try:+ tile_ids = [int(part) for part in (part.strip() for part in raw.split(",")) if part]+ except ValueError as exc:+ raise exceptions.ValidationError("tile_ids must be a comma-separated list of integers.") from exc+ return list(dict.fromkeys(tile_ids))+++def parse_max_result_chars(raw: str | None) -> int:+ """Parse the `max_result_chars` query param. Zero means no per-tile limit.++ A budget below the floor is rejected rather than served, because a tile that cannot hold its+ truncation marker would have to either overrun the budget or drop the marker, and a caller+ that cannot see data was dropped reads a cut table as the whole one.+ """+ if raw is None or not raw.strip():+ return RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS+ try:+ max_chars = int(raw)+ except ValueError as exc:+ raise exceptions.ValidationError("max_result_chars must be an integer.") from exc+ if max_chars < 0:+ raise exceptions.ValidationError("max_result_chars must be zero or greater.")+ if 0 < max_chars < RUN_INSIGHTS_MIN_TILE_CHARS:+ raise exceptions.ValidationError(+ f"max_result_chars must be {RUN_INSIGHTS_MIN_TILE_CHARS} or greater, or zero for the whole table."+ )+ return max_chars+++def tile_fits_response_budget(used_chars: int) -> bool:+ """Whether the response has enough budget left for another tile to carry usable rows.+ Below the floor a tile yields a sliced header and a marker, so it is reported as not run."""+ return RUN_INSIGHTS_MAX_TOTAL_CHARS - used_chars >= RUN_INSIGHTS_MIN_TILE_CHARS+++def tile_budget(max_result_chars: int, used_chars: int) -> int:+ """Per-tile budget, held down to what the response has left. Zero stays unbounded."""+ if max_result_chars <= 0:+ return 0+ return min(max_result_chars, RUN_INSIGHTS_MAX_TOTAL_CHARS - used_chars)+++def bound_formatted_result(formatted: str, *, tile_id: int, max_chars: int) -> str:+ """Hold a formatted insight table inside `max_chars`, keeping both ends of it.++ Rows come out of the middle because which end carries the answer depends on the query type.+ A trends table runs oldest bucket first, so its recent data is at the bottom, while a funnel+ runs first step first and a paths table runs most-travelled first. Dropping the tail would+ hand an agent the opening of a date range and read as the whole of it.++ The marker counts against `max_chars`, so the result never grows past it. That holds for+ every budget the API accepts, because `parse_max_result_chars` rejects one too small to+ hold a marker.+ """+ if max_chars <= 0 or len(formatted) <= max_chars:+ return formatted++ lines = formatted.splitlines()+ # Both counts are at most the line count, so this reserves the widest the marker can render.+ marker_room = len(ELISION_NOTE.format(omitted=len(lines), total=len(lines), tile_id=tile_id)) + 1+ rows_budget = max_chars - marker_room++ if len(lines) < 3 or len(lines[0]) + 1 > rows_budget:+ # No middle to drop, or the header does not fit, so cutting the text is what holds the bound.+ cut_note = CUT_NOTE.format(max_chars=max_chars, tile_id=tile_id)+ return formatted[: max(max_chars - len(cut_note) - 1, 0)] + "\n" + cut_note++ # The first line is the column header in every formatter, so it is always kept.+ head = [lines[0]]+ tail: list[str] = []+ used = len(lines[0]) + 1+ next_head, next_tail = 1, len(lines) - 1++ while next_head <= next_tail:+ took = False+ # The tail goes first so an odd row count spends its last row on the recent end. Each pass+ # tries both ends, so one long row cannot stop the other end from filling.+ for from_tail in (True, False):+ if next_head > next_tail:+ break+ line = lines[next_tail] if from_tail else lines[next_head]+ if used + len(line) + 1 > rows_budget:+ continue+ used += len(line) + 1+ if from_tail:+ tail.append(line)+ next_tail -= 1+ else:+ head.append(line)+ next_head += 1+ took = True+ if not took:+ break++ note = ELISION_NOTE.format(omitted=next_tail - next_head + 1, total=len(lines) - 1, tile_id=tile_id)+ return "\n".join([*head, note, *reversed(tail)])+++def render_unsupported_result(result: Any) -> str:+ """Text for a result no LLM formatter covers, so `optimized` output stays bounded anyway."""+ return json.dumps(result, default=str)+++def unrun_tile_results(remaining: list[tuple[int, DashboardTile, Insight]]) -> list[dict[str, Any]]:+ """Markers for the tiles the response budget left out.++ The list is capped because it grows with the dashboard, and a few hundred markers would cost+ more than the budget they report. The last marker says how many tiles it leaves off, so a+ caller is never left thinking the dashboard ends there.+ """+ listed = remaining[:RUN_INSIGHTS_MAX_UNRUN_TILES]+ results = [unrun_tile_result(tile, insight, order) for order, tile, insight in listed]+ unlisted = len(remaining) - len(listed)+ if unlisted and results:+ results[-1]["insight"]["result"] += UNLISTED_NOTE.format(unlisted=unlisted)+ return results+++def unrun_tile_result(tile: DashboardTile, insight: Insight, order: int) -> dict[str, Any]:+ """Stand-in for a tile the response budget left out, shaped like a run tile."""+ return {+ "id": tile.id,+ "insight": {+ "id": insight.id,+ "short_id": insight.short_id,+ "name": insight.name,+ "derived_name": insight.derived_name,+ "result": BUDGET_NOTE.format(budget=RUN_INSIGHTS_MAX_TOTAL_CHARS, tile_id=tile.id),+ },+ "order": order,+ "last_refresh": None,+ "is_cached": False,+ }diff --git a/products/dashboards/backend/test/test_run_insights_output.py b/products/dashboards/backend/test/test_run_insights_output.pynew file mode 100644index 000000000000..c417e2a49fc4--- /dev/null+++ b/products/dashboards/backend/test/test_run_insights_output.py@@ -0,0 +1,161 @@+from datetime import date+from types import SimpleNamespace++from django.test import SimpleTestCase++from parameterized import parameterized+from rest_framework import exceptions++from products.dashboards.backend.constants import (+ RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS,+ RUN_INSIGHTS_MAX_TOTAL_CHARS,+ RUN_INSIGHTS_MAX_UNRUN_TILES,+ RUN_INSIGHTS_MIN_TILE_CHARS,+)+from products.dashboards.backend.run_insights_output import (+ CUT_NOTE,+ ELISION_NOTE,+ bound_formatted_result,+ parse_max_result_chars,+ parse_tile_ids,+ render_unsupported_result,+ tile_budget,+ tile_fits_response_budget,+ unrun_tile_results,+)+++def _table(rows: int) -> str:+ return "\n".join(["Date|Count", *(f"2026-01-01 {row:02d}:00|{row}" for row in range(rows))])+++class TestBoundFormattedResult(SimpleTestCase):+ @parameterized.expand([("table_fits_the_budget", 10_000), ("zero_means_no_limit", 0)])+ def test_returns_the_table_unchanged(self, _name: str, max_chars: int) -> None:+ table = _table(3)++ self.assertEqual(bound_formatted_result(table, tile_id=7, max_chars=max_chars), table)++ def test_keeps_the_newest_rows_and_not_only_the_oldest(self) -> None:+ # Trends tables run oldest bucket first, so a head-only cut reads as the whole date range.+ table = _table(60)++ bounded = bound_formatted_result(table, tile_id=7, max_chars=300).splitlines()++ self.assertEqual(bounded[0], "Date|Count")+ self.assertEqual(bounded[1], table.splitlines()[1])+ self.assertEqual(bounded[-1], table.splitlines()[-1])++ @parameterized.expand([("small", 300), ("default", RUN_INSIGHTS_DEFAULT_MAX_RESULT_CHARS)])+ def test_holds_the_whole_result_marker_included_within_the_budget(self, _name: str, max_chars: int) -> None:+ bounded = bound_formatted_result(_table(400), tile_id=7, max_chars=max_chars)++ self.assertLessEqual(len(bounded), max_chars)++ def test_names_the_tile_and_how_many_rows_it_dropped(self) -> None:+ bounded = bound_formatted_result(_table(60), tile_id=7, max_chars=300).splitlines()++ note = next(line for line in bounded if line.startswith("["))+ self.assertIn(f"{60 - (len(bounded) - 2)} of 60 rows omitted", note)+ self.assertIn("tile_ids=7", note)++ @parameterized.expand(+ [+ # One long row must still be cut, otherwise a wide table bypasses the budget entirely.+ ("single_row_wider_than_the_budget", "x" * 500, 300),+ ("header_wider_than_the_budget", "H" * 300 + "\nr1\nr2", 250),+ ]+ )+ def test_cuts_text_it_cannot_hold_by_whole_rows(self, _name: str, formatted: str, max_chars: int) -> None:+ bounded = bound_formatted_result(formatted, tile_id=7, max_chars=max_chars)++ self.assertLessEqual(len(bounded), max_chars)+ self.assertTrue(formatted.startswith(bounded.splitlines()[0]))+ self.assertIn("tile_ids=7", bounded)++ def test_the_floor_leaves_room_for_the_widest_marker(self) -> None:+ # The per-tile bound only holds unconditionally while the smallest budget the API accepts+ # can still carry a marker, so this guards the two against drifting apart.+ widest = max(+ len(ELISION_NOTE.format(omitted=2**63, total=2**63, tile_id=2**63)),+ len(CUT_NOTE.format(max_chars=2**63, tile_id=2**63)),+ )++ self.assertLess(widest, RUN_INSIGHTS_MIN_TILE_CHARS)+++class TestParseQueryParams(SimpleTestCase):+ @parameterized.expand([("missing", None), ("blank", " ")])+ def test_tile_ids_selects_nothing(self, _name: str, raw: str | None) -> None:+ self.assertEqual(parse_tile_ids(raw), [])++ def test_tile_ids_drops_repeats_and_keeps_request_order(self) -> None:+ # run_widgets returns its results in the order asked for, so the parser must not sort.+ self.assertEqual(parse_tile_ids(" 4, 3 ,4"), [4, 3])++ def test_max_result_chars_defaults(self) -> None:+ self.assertGreater(parse_max_result_chars(None), 0)++ @parameterized.expand([("below_the_floor", "10"), ("just_below_the_floor", str(RUN_INSIGHTS_MIN_TILE_CHARS - 1))])+ def test_max_result_chars_rejects_a_budget_too_small_for_a_marker(self, _name: str, raw: str) -> None:+ with self.assertRaises(exceptions.ValidationError):+ parse_max_result_chars(raw)++ @parameterized.expand([("the_floor", str(RUN_INSIGHTS_MIN_TILE_CHARS)), ("unbounded", "0")])+ def test_max_result_chars_accepts_the_floor_and_zero(self, _name: str, raw: str) -> None:+ self.assertEqual(parse_max_result_chars(raw), int(raw))+++class TestRenderUnsupportedResult(SimpleTestCase):+ def test_renders_a_value_json_cannot_serialize(self) -> None:+ self.assertIn("2026-01-01", render_unsupported_result([{"day": date(2026, 1, 1)}]))+++class TestTileBudget(SimpleTestCase):+ def test_holds_a_tile_down_to_what_the_response_has_left(self) -> None:+ # Without this a single generous max_result_chars would overshoot the whole-response budget.+ self.assertEqual(tile_budget(1_000_000, RUN_INSIGHTS_MAX_TOTAL_CHARS - 100), 100)++ def test_keeps_the_smaller_per_tile_limit(self) -> None:+ self.assertEqual(tile_budget(50, 0), 50)++ def test_zero_stays_unbounded(self) -> None:+ self.assertEqual(tile_budget(0, RUN_INSIGHTS_MAX_TOTAL_CHARS - 1), 0)++ @parameterized.expand(+ [+ ("nothing_used", 0, True),+ ("floor_exactly_left", RUN_INSIGHTS_MAX_TOTAL_CHARS - RUN_INSIGHTS_MIN_TILE_CHARS, True),+ ("below_the_floor", RUN_INSIGHTS_MAX_TOTAL_CHARS - 1, False),+ ]+ )+ def test_a_tile_needs_the_floor_to_run(self, _name: str, used_chars: int, expected: bool) -> None:+ self.assertEqual(tile_fits_response_budget(used_chars), expected)+++class TestUnrunTileResults(SimpleTestCase):+ @staticmethod+ def _remaining(count: int) -> list:+ return [+ (+ order,+ SimpleNamespace(id=1000 + order),+ SimpleNamespace(id=order, short_id="abcdefgh", name=f"Tile {order}", derived_name=None),+ )+ for order in range(count)+ ]++ def test_lists_every_tile_when_they_fit_the_cap(self) -> None:+ results = unrun_tile_results(self._remaining(3))++ self.assertEqual([result["order"] for result in results], [0, 1, 2])+ self.assertNotIn("not listed", results[-1]["insight"]["result"])++ def test_caps_the_list_and_says_what_it_left_off(self) -> None:+ # Uncapped, hundreds of tiles cost more in markers than the budget they report.+ remaining = self._remaining(RUN_INSIGHTS_MAX_UNRUN_TILES + 40)++ results = unrun_tile_results(remaining)++ self.assertEqual(len(results), RUN_INSIGHTS_MAX_UNRUN_TILES)+ self.assertIn("40 further tiles are not listed", results[-1]["insight"]["result"])diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 52e71d707609..3bc97a2ea296 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -10762,13 +10762,21 @@ export type DashboardsRunInsightsRetrieveParams = {filters_override?: stringformat?: DashboardsRunInsightsRetrieveFormat/**- * 'optimized' (default) returns LLM-friendly formatted text per insight. 'json' returns the raw query result objects.+ * Per-tile character budget for 'optimized' output, truncation marker included. A longer table keeps its header and both ends, and names how many rows were dropped from the middle. Defaults to 2000; pass 0 for the whole table, or 200 or more, since a smaller budget cannot carry the marker. Ignored when output_format is 'json'. Any value above zero is also held down to what the response has left of its 30000 character budget, and tiles past that budget are not run.+ */+ max_result_chars?: number+ /**+ * 'optimized' (default) returns LLM-friendly formatted text per insight, bounded by max_result_chars. 'json' returns the raw query result objects, unbounded.*/output_format?: DashboardsRunInsightsRetrieveOutputFormat/*** Cache behavior. 'force_cache' (default) serves from cache even if stale. 'blocking' uses cache if fresh, otherwise recalculates. 'force_blocking' always recalculates.*/refresh?: DashboardsRunInsightsRetrieveRefresh+ /**+ * Comma-separated dashboard tile IDs to run. Defaults to every insight tile on the dashboard. Use it to read one tile without receiving the others. An ID that is not on this dashboard is rejected.+ */+ tile_ids?: string/*** Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.*/diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yamlindex bb79e780664e..67d9ff5b3ab9 100644--- a/products/dashboards/mcp/tools.yaml+++ b/products/dashboards/mcp/tools.yaml@@ -290,8 +290,15 @@ tools:description: >Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); setrefresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or- 'json' for raw query results. Supports variables_override and filters_override query params to run insights- with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.+ 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's+ table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the+ middle, held down further by whatever the response has left of its overall budget, and tiles past that+ budget are not run. To fit more of what you need into that budget, in order: pass tile_ids to run only the+ tiles you care about; pass filters_override={"interval": "day"} (or "week"/"month") to turn a long run of+ hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more),+ or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with tile_ids. Supports+ variables_override and filters_override query params to run insights with one-off overrides without+ persisting; see the parameter descriptions for the exact JSON shape required.param_overrides:id:cast: string-intdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 901351b8a033..561e0e1c5986 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -2687,7 +2687,7 @@}},"dashboard-insights-run": {- "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.",+ "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the middle, held down further by whatever the response has left of its overall budget, and tiles past that budget are not run. To fit more of what you need into that budget, in order: pass tile_ids to run only the tiles you care about; pass filters_override={\"interval\": \"day\"} (or \"week\"/\"month\") to turn a long run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with tile_ids. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.","category": "Dashboards","feature": "dashboards","summary": "Run dashboard insights",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex de558c229405..1194be4a328d 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -2702,7 +2702,7 @@}},"dashboard-insights-run": {- "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.",+ "description": "Run all insights on a dashboard and return their results. Uses cached results by default (may be stale); set refresh to 'blocking' for fresh results. Set format to 'optimized' (default) for LLM-friendly text tables or 'json' for raw query results. 'optimized' output is bounded so a wide dashboard fits in context: a tile's table is held to max_result_chars characters by keeping its header and both ends and dropping rows from the middle, held down further by whatever the response has left of its overall budget, and tiles past that budget are not run. To fit more of what you need into that budget, in order: pass tile_ids to run only the tiles you care about; pass filters_override={\"interval\": \"day\"} (or \"week\"/\"month\") to turn a long run of hourly buckets into fewer, wider rows, which also cuts the query cost; raise max_result_chars (200 or more), or pass 0 for a tile's whole table. 'json' is unbounded, so pair it with tile_ids. Supports variables_override and filters_override query params to run insights with one-off overrides without persisting; see the parameter descriptions for the exact JSON shape required.","category": "Dashboards","feature": "dashboards","summary": "Run dashboard insights",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a2dc91309343..0afab01d4681 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -101644,13 +101644,21 @@ export namespace Schemas {filters_override?: string;format?: DashboardsRunInsightsRetrieveFormat;/**- * 'optimized' (default) returns LLM-friendly formatted text per insight. 'json' returns the raw query result objects.+ * Per-tile character budget for 'optimized' output, truncation marker included. A longer table keeps its header and both ends, and names how many rows were dropped from the middle. Defaults to 2000; pass 0 for the whole table, or 200 or more, since a smaller budget cannot carry the marker. Ignored when output_format is 'json'. Any value above zero is also held down to what the response has left of its 30000 character budget, and tiles past that budget are not run.+ */+ max_result_chars?: number;+ /**+ * 'optimized' (default) returns LLM-friendly formatted text per insight, bounded by max_result_chars. 'json' returns the raw query result objects, unbounded.*/output_format?: DashboardsRunInsightsRetrieveOutputFormat;/*** Cache behavior. 'force_cache' (default) serves from cache even if stale. 'blocking' uses cache if fresh, otherwise recalculates. 'force_blocking' always recalculates.*/refresh?: DashboardsRunInsightsRetrieveRefresh;+ /**+ * Comma-separated dashboard tile IDs to run. Defaults to every insight tile on the dashboard. Use it to read one tile without receiving the others. An ID that is not on this dashboard is rejected.+ */+ tile_ids?: string;/*** Object (or pre-encoded JSON string) to override dashboard variables for this request only (not persisted). Format: {"<variable_id>": {"code_name": "<code_name>", "variableId": "<variable_id>", "value": <new_value>}}. Each entry must include `code_name` — partial entries are silently dropped. The simplest workflow is to call `dashboard-get` first, copy the matching entry from the response, and mutate `value`. Top-level keys replace; nested values are not deep-merged. Ignored when accessed via a sharing token.*/diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 561d346013b0..de6f9c4058e3 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -1400,11 +1400,17 @@ export const DashboardsRunInsightsRetrieveQueryParams = () => zod.object({'Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.'),format: zod.enum(['json', 'txt']).optional(),+ max_result_chars: zod+ .number()+ .optional()+ .describe(+ "Per-tile character budget for 'optimized' output, truncation marker included. A longer table keeps its header and both ends, and names how many rows were dropped from the middle. Defaults to 2000; pass 0 for the whole table, or 200 or more, since a smaller budget cannot carry the marker. Ignored when output_format is 'json'. Any value above zero is also held down to what the response has left of its 30000 character budget, and tiles past that budget are not run."+ ),output_format: zod.enum(['json', 'optimized']).optional().describe(- "'optimized' (default) returns LLM-friendly formatted text per insight. 'json' returns the raw query result objects."+ "'optimized' (default) returns LLM-friendly formatted text per insight, bounded by max_result_chars. 'json' returns the raw query result objects, unbounded."),refresh: zod.enum(['blocking', 'force_blocking', 'force_cache'])@@ -1412,6 +1418,12 @@ export const DashboardsRunInsightsRetrieveQueryParams = () => zod.object({.describe("Cache behavior. 'force_cache' (default) serves from cache even if stale. 'blocking' uses cache if fresh, otherwise recalculates. 'force_blocking' always recalculates."),+ tile_ids: zod+ .string()+ .optional()+ .describe(+ 'Comma-separated dashboard tile IDs to run. Defaults to every insight tile on the dashboard. Use it to read one tile without receiving the others. An ID that is not on this dashboard is rejected.'+ ),variables_override: zod.string().optional()diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.tsindex 40b2d9d184ba..3c4fd77811be 100644--- a/services/mcp/src/tools/generated/dashboards.ts+++ b/services/mcp/src/tools/generated/dashboards.ts@@ -368,8 +368,10 @@ const dashboardInsightsRun = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/${encodeURIComponent(String(params.id))}/run_insights/`,query: {filters_override: params.filters_override,+ max_result_chars: params.max_result_chars,output_format: params.output_format,refresh: params.refresh,+ tile_ids: params.tile_ids,variables_override: params.variables_override,},})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.jsonindex 2fdee766e23e..2378a0195344 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-insights-run.json@@ -20,8 +20,12 @@"description": "A unique integer value identifying this dashboard.","type": "number"},+ "max_result_chars": {+ "description": "Per-tile character budget for 'optimized' output, truncation marker included. A longer table keeps its header and both ends, and names how many rows were dropped from the middle. Defaults to 2000; pass 0 for the whole table, or 200 or more, since a smaller budget cannot carry the marker. Ignored when output_format is 'json'. Any value above zero is also held down to what the response has left of its 30000 character budget, and tiles past that budget are not run.",+ "type": "number"+ },"output_format": {- "description": "'optimized' (default) returns LLM-friendly formatted text per insight. 'json' returns the raw query result objects.",+ "description": "'optimized' (default) returns LLM-friendly formatted text per insight, bounded by max_result_chars. 'json' returns the raw query result objects, unbounded.","enum": ["json", "optimized"],"type": "string"},@@ -30,6 +34,10 @@"enum": ["blocking", "force_blocking", "force_cache"],"type": "string"},+ "tile_ids": {+ "description": "Comma-separated dashboard tile IDs to run. Defaults to every insight tile on the dashboard. Use it to read one tile without receiving the others. An ID that is not on this dashboard is rejected.",+ "type": "string"+ },"variables_override": {"anyOf": [{