You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by mi...@apache.org on 2026/10/06 11:25:04 UTC
(superset) branch master updated: feat(mcp): return the Big Number headline from chart and dashboard data (#44948)
This is an automated email from the ASF dual-hosted git repository.
aminghadersohi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 05a3d4b880f feat(mcp): return the Big Number headline from chart and dashboard data (#44948)
05a3d4b880f is described below
commit 05a3d4b880fbf4e7755237620f6de2b29e9f58af
Author: Amin Ghadersohi <am...@gmail.com>
AuthorDate: Tue Oct 6 22:24:56 2026 +1100
feat(mcp): return the Big Number headline from chart and dashboard data (#44948)
---
docs/admin_docs/configuration/mcp-server.mdx | 33 +
superset/mcp_service/chart/big_number_headline.py | 388 ++++++++++++
superset/mcp_service/chart/schemas.py | 43 ++
superset/mcp_service/chart/tool/get_chart_data.py | 39 ++
superset/mcp_service/dashboard/schemas.py | 10 +
.../dashboard/tool/get_dashboard_data.py | 9 +
.../mcp_service/chart/test_big_number_headline.py | 665 +++++++++++++++++++++
.../mcp_service/chart/tool/test_get_chart_data.py | 258 ++++++++
.../dashboard/tool/test_get_dashboard_data.py | 44 ++
9 files changed, 1489 insertions(+)
diff --git a/docs/admin_docs/configuration/mcp-server.mdx b/docs/admin_docs/configuration/mcp-server.mdx
index a8b60d714f3..e2c1b2ef540 100644
--- a/docs/admin_docs/configuration/mcp-server.mdx
+++ b/docs/admin_docs/configuration/mcp-server.mdx
@@ -1562,6 +1562,39 @@ For saved and unsaved charts, `get_chart_data` column metadata excludes missing
values from `unique_count`. Values serialized as JSON `null`, including NaN,
NaT, and non-finite numbers, contribute to `null_count` instead.
+## Big Number headlines
+
+For Big Number charts (`big_number` and `big_number_total`), `get_chart_data`
+and `get_dashboard_data` return a `headline` object holding the number the chart
+displays. Agents should report `headline.value` rather than reading or summing
+the data rows: for the trendline variant the rows are a time series, and the
+displayed number is derived from the whole series by the chart's aggregation.
+
+| Field | Contents |
+| --- | --- |
+| `value` | The displayed number, or `null` when it cannot be computed exactly |
+| `aggregation` | `total` for `big_number_total`; otherwise the chart's aggregation (`LAST_VALUE`, `sum`, `mean`, `min`, `max`, `median`, or `raw`) |
+| `rows_used` | The number of non-null values aggregated |
+| `reason` | Why `value` is `null` |
+
+A headline is only returned when it matches the rendered chart, so `value` is
+`null` with a `reason` when:
+
+- The query returned no rows, the metric column is missing, or every metric
+ value is null.
+- The chart applies a rolling window or resampling that the executed query did
+ not include, or the fetch was truncated at the row limit.
+- The aggregation picks the latest value (`LAST_VALUE`) and some rows have no
+ usable timestamp. The chart's ordering of such rows depends on row order, so
+ the value it shows cannot be determined exactly. Order-independent
+ aggregations still include those rows.
+- The aggregation is `raw` ("Overall value") and the chart has no saved query
+ context. That value comes from a second query that only a saved query context
+ carries, so unsaved and `form_data_key` requests return `null`.
+
+When `form_data_key` is supplied, the headline follows the unsaved visualization
+type, including when switching to or from a Big Number chart.
+
## Dataset query dimensions and nested fields
The `query_dataset` tool accepts exact column names registered on the selected
diff --git a/superset/mcp_service/chart/big_number_headline.py b/superset/mcp_service/chart/big_number_headline.py
new file mode 100644
index 00000000000..32d102df1be
--- /dev/null
+++ b/superset/mcp_service/chart/big_number_headline.py
@@ -0,0 +1,388 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Headline value of Big Number charts.
+
+A Big Number chart renders one number. For the trendline variant (``big_number``)
+that number is derived client-side from the time series; for ``big_number_total``
+it is the single metric value. Neither is any of the first sample rows, so this
+module reproduces the frontend computation:
+
+- ``aggregationChoices`` in ``superset-ui-chart-controls`` (``customControls.tsx``)
+- ``BigNumberWithTrendline/transformProps.ts`` and ``BigNumberTotal/transformProps.ts``
+
+A headline is only returned when it is exact. Otherwise ``value`` is null with a
+``reason``: a wrong number is worse than none.
+"""
+
+from __future__ import annotations
+
+import math
+import statistics
+from collections.abc import Callable, Mapping, Sequence
+from datetime import date, datetime, timezone
+from decimal import Decimal
+from typing import Any, cast
+
+from superset.mcp_service.chart.schemas import BigNumberHeadline
+from superset.superset_typing import Metric
+from superset.utils.core import DTTM_ALIAS, get_metric_name
+
+BIG_NUMBER_TRENDLINE_VIZ_TYPE = "big_number"
+BIG_NUMBER_TOTAL_VIZ_TYPE = "big_number_total"
+
+DEFAULT_AGGREGATION = "LAST_VALUE"
+RAW_AGGREGATION = "raw"
+
+# Metric-value transforms for the trend series. Keys and order mirror the
+# frontend's `aggregationChoices`. `LAST_VALUE` and `raw` receive values ordered
+# newest first and take the first, so they need no entry beyond that.
+_AGGREGATIONS: dict[str, Callable[[list[float]], float | None]] = {
+ "raw": lambda values: values[0] if values else None,
+ "LAST_VALUE": lambda values: values[0] if values else None,
+ "sum": lambda values: sum(values) if values else None,
+ "mean": lambda values: sum(values) / len(values) if values else None,
+ "min": lambda values: min(values) if values else None,
+ "max": lambda values: max(values) if values else None,
+ "median": lambda values: statistics.median(values) if values else None,
+}
+
+# Rolling types that make the query add a `rolling` (sum, mean, std) or `cum`
+# (cumsum) post-processing step, as in the frontend's `rollingWindowOperator`.
+_ROLLING_OPERATIONS = {
+ "cumsum": "cum",
+ "sum": "rolling",
+ "mean": "rolling",
+ "std": "rolling",
+}
+
+
+def is_big_number_viz_type(viz_type: str | None) -> bool:
+ """Whether the visualization displays a Big Number headline."""
+ return viz_type in (BIG_NUMBER_TRENDLINE_VIZ_TYPE, BIG_NUMBER_TOTAL_VIZ_TYPE)
+
+
+def executed_query_facts(query_context: Any) -> tuple[int | None, list[str]]:
+ """Row limit and post-processing operations of the first executed query.
+
+ Read from the query that actually ran, so it reflects any row-limit override
+ and shows whether the chart's advanced analytics were part of the query.
+ """
+ queries = getattr(query_context, "queries", None) or []
+ if not queries:
+ return None, []
+ first = queries[0]
+ row_limit = getattr(first, "row_limit", None)
+ operations = [
+ str(step.get("operation"))
+ for step in getattr(first, "post_processing", None) or []
+ if isinstance(step, Mapping) and step.get("operation")
+ ]
+ return (row_limit if isinstance(row_limit, int) else None), operations
+
+
+def _unavailable(aggregation: str | None, reason: str) -> BigNumberHeadline:
+ """Return an unavailable headline with its explanation."""
+ return BigNumberHeadline(value=None, aggregation=aggregation, reason=reason)
+
+
+def _parse_date_ms(value: str) -> int | None:
+ """Epoch milliseconds for an ISO-8601 string, else None (frontend:
+ strict `dayjs.utc` parse in `parseMetricValue`)."""
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return int(parsed.timestamp() * 1000)
+
+
+def _parse_metric_value(value: Any) -> int | float | None:
+ """Mirror of the frontend's `parseMetricValue`, plus JSON-safety: numbers
+ pass through, date strings become epoch ms, anything else (including NaN and
+ infinities, which serialize as null) is null."""
+ if isinstance(value, bool) or value is None:
+ return None
+ if isinstance(value, Decimal):
+ value = float(value)
+ if isinstance(value, (int, float)):
+ try:
+ return value if math.isfinite(value) else None
+ except OverflowError:
+ return None
+ if isinstance(value, datetime):
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=timezone.utc)
+ return int(value.timestamp() * 1000)
+ if isinstance(value, str):
+ return _parse_date_ms(value)
+ return None
+
+
+def _timestamp_ms(value: Any) -> float | None:
+ """Sortable time value for an x-axis cell (the API serializes these as epoch
+ ms; direct query results may carry datetimes)."""
+ if isinstance(value, date) and not isinstance(value, datetime):
+ value = datetime(value.year, value.month, value.day, tzinfo=timezone.utc)
+ return _parse_metric_value(value)
+
+
+def _metric_label(form_data: Mapping[str, Any]) -> str | None:
+ """Resolve the metric label using the frontend column-name aliases."""
+ metric = form_data.get("metric")
+ if not metric:
+ return None
+ if (
+ isinstance(metric, Mapping)
+ and not metric.get("label")
+ and metric.get("expressionType") == "SIMPLE"
+ ):
+ column = metric.get("column")
+ if isinstance(column, Mapping) and column.get("columnName"):
+ return f"{metric.get('aggregate')}({column['columnName']})"
+ try:
+ return get_metric_name(cast(Metric, metric)) or None
+ except (ValueError, TypeError, AttributeError):
+ return None
+
+
+def _x_axis_labels(form_data: Mapping[str, Any]) -> list[str]:
+ """Candidate time-column labels: the configured x-axis, then `__timestamp`.
+
+ Without an x-axis, the legacy ``granularity_sqla`` column is a candidate
+ too: the MCP query (``resolve_big_number_columns``) selects it by name,
+ while a frontend-built query aliases it as `__timestamp`.
+ """
+ labels: list[str] = []
+ x_axis = form_data.get("x_axis")
+ if isinstance(x_axis, str) and x_axis:
+ labels.append(x_axis)
+ elif isinstance(x_axis, Mapping):
+ label = x_axis.get("label") or x_axis.get("column_name")
+ if isinstance(label, str) and label:
+ labels.append(label)
+ if not labels:
+ granularity = form_data.get("granularity_sqla")
+ if isinstance(granularity, str) and granularity:
+ labels.append(granularity)
+ labels.append(DTTM_ALIAS)
+ return labels
+
+
+def _total_headline(
+ form_data: Mapping[str, Any], rows: Sequence[Mapping[str, Any]]
+) -> BigNumberHeadline:
+ """`big_number_total`: the single metric value of the first row."""
+ label = _metric_label(form_data)
+ if not rows:
+ return _unavailable("total", "The query returned no rows.")
+ if label is None or label not in rows[0]:
+ return _unavailable("total", "The metric column was not in the result.")
+ raw = rows[0][label]
+ parsed = _parse_metric_value(raw)
+ if parsed is None and isinstance(raw, str) and raw.strip():
+ return BigNumberHeadline(value=raw, aggregation="total", rows_used=1)
+ if parsed is None:
+ return _unavailable("total", "The metric value is null.")
+ return BigNumberHeadline(value=parsed, aggregation="total", rows_used=1)
+
+
+def _overall_value(
+ label: str, x_labels: Sequence[str], rows: Sequence[Mapping[str, Any]]
+) -> int | float | str | None:
+ """Value of the `raw` ("Overall value") query layer, as the frontend reads
+ it: the metric column, else the first other numeric column."""
+ row = rows[0]
+ value = row.get(label)
+ if value is None:
+ value = next(
+ (
+ cell
+ for key, cell in row.items()
+ if key not in x_labels
+ and isinstance(cell, (int, float, Decimal))
+ and not isinstance(cell, bool)
+ ),
+ None,
+ )
+ if isinstance(value, Decimal):
+ value = float(value)
+ if isinstance(value, float) and not math.isfinite(value):
+ return None
+ return value if isinstance(value, (int, float, str)) else None
+
+
+def _raw_headline(
+ label: str,
+ x_labels: Sequence[str],
+ queries: Sequence[Mapping[str, Any]],
+) -> BigNumberHeadline:
+ """`raw` ("Overall value"): read from the second, un-trended query layer."""
+ overall_rows = queries[1].get("data") if len(queries) > 1 else None
+ if not overall_rows:
+ return _unavailable(
+ RAW_AGGREGATION,
+ "The overall-value (raw) query layer did not return a value.",
+ )
+ value = _overall_value(label, x_labels, overall_rows)
+ if value is None:
+ return _unavailable(
+ RAW_AGGREGATION, "The overall-value (raw) query returned null."
+ )
+ return BigNumberHeadline(
+ value=value, aggregation=RAW_AGGREGATION, rows_used=len(overall_rows)
+ )
+
+
+def _series_problem(
+ form_data: Mapping[str, Any],
+ first: Mapping[str, Any],
+ row_limit: int | None,
+ post_processing_operations: Sequence[str],
+) -> str | None:
+ """Why the returned trend rows cannot give an exact headline, if they can't."""
+ rolling_type = form_data.get("rolling_type")
+ expected_operation = _ROLLING_OPERATIONS.get(str(rolling_type))
+ if expected_operation and expected_operation not in post_processing_operations:
+ return (
+ f"The chart uses a rolling window ({rolling_type}) that the returned "
+ "rows do not reflect."
+ )
+ # As in the frontend's `resampleOperator`, both controls add the step.
+ if (
+ form_data.get("resample_rule")
+ and form_data.get("resample_method")
+ and "resample" not in post_processing_operations
+ ):
+ return (
+ f"The chart resamples the series ({form_data['resample_rule']}, "
+ f"{form_data['resample_method']}), which the returned rows do not "
+ "reflect."
+ )
+ rows = first.get("data") or []
+ returned_total = first.get("rowcount")
+ if (row_limit and len(rows) >= row_limit) or (
+ isinstance(returned_total, int) and returned_total > len(rows)
+ ):
+ return (
+ "The fetch was truncated at the row limit, so the series is "
+ "incomplete; the headline cannot be computed exactly."
+ )
+ return None
+
+
+def _trend_values(
+ label: str,
+ x_labels: Sequence[str],
+ rows: Sequence[Mapping[str, Any]],
+ *,
+ newest_first: bool,
+) -> list[int | float] | None:
+ """Non-null metric values, newest first when the aggregation needs it.
+
+ Returns None when the newest value cannot be determined exactly. The
+ frontend sorts with a comparator that treats a row lacking a usable
+ timestamp as equal to every other row, so with such a row present the order
+ it renders depends on the input order and the browser's sort, and the value
+ it shows need not be the newest dated one.
+ """
+ values = [_parse_metric_value(row.get(label)) for row in rows]
+ if not newest_first:
+ return [value for value in values if value is not None]
+ x_label = next(
+ (name for name in x_labels if any(name in row for row in rows)), None
+ )
+ timestamps = [_timestamp_ms(row.get(x_label)) if x_label else None for row in rows]
+ non_null = [value for value in values if value is not None]
+ if None in timestamps and len(set(non_null)) > 1:
+ return None
+ # Descending by time; ties retain their input order, as in the stable
+ # frontend sort.
+ ordered = sorted(
+ zip(timestamps, values, strict=True), key=lambda item: -(item[0] or 0)
+ )
+ return [value for _, value in ordered if value is not None]
+
+
+def compute_big_number_headline(
+ viz_type: str | None,
+ form_data: Mapping[str, Any],
+ queries: Sequence[Mapping[str, Any]],
+ *,
+ row_limit: int | None = None,
+ post_processing_operations: Sequence[str] = (),
+) -> BigNumberHeadline | None:
+ """Headline of a Big Number chart from its executed query results.
+
+ Args:
+ viz_type: The chart's viz type; anything but a Big Number returns None.
+ form_data: The chart's form data (metric, aggregation, rolling_type, ...).
+ queries: The executed query results, in query-context order.
+ row_limit: The row limit the first query ran with, used to detect a
+ truncated fetch.
+ post_processing_operations: Operations of the first executed query.
+ """
+ if not is_big_number_viz_type(viz_type):
+ return None
+
+ first = queries[0] if queries else {}
+ rows: Sequence[Mapping[str, Any]] = first.get("data") or []
+ if viz_type == BIG_NUMBER_TOTAL_VIZ_TYPE:
+ return _total_headline(form_data, rows)
+
+ # Case-insensitive lookup with a LAST_VALUE fallback, as the frontend does.
+ requested = str(form_data.get("aggregation") or "")
+ key = next(
+ (name for name in _AGGREGATIONS if name.lower() == requested.lower()),
+ DEFAULT_AGGREGATION,
+ )
+ label = _metric_label(form_data)
+ if not rows:
+ return _unavailable(key, "The query returned no rows.")
+ if label is None or label not in rows[0]:
+ return _unavailable(key, "The metric column was not in the result.")
+ x_labels = _x_axis_labels(form_data)
+
+ # Only an exact "raw" selects the server-side overall value; the frontend
+ # adds that second query layer for the same exact match.
+ if requested == RAW_AGGREGATION:
+ return _raw_headline(label, x_labels, queries)
+
+ if problem := _series_problem(
+ form_data, first, row_limit, post_processing_operations
+ ):
+ return _unavailable(key, problem)
+
+ # `raw` reaches here only for a non-exact spelling, where the frontend takes
+ # the newest value just like LAST_VALUE.
+ values = _trend_values(
+ label,
+ x_labels,
+ rows,
+ newest_first=key in (DEFAULT_AGGREGATION, RAW_AGGREGATION),
+ )
+ if values is None:
+ return _unavailable(
+ key,
+ "Some rows have no usable timestamp, so the latest value the chart "
+ "shows depends on row order and cannot be determined exactly.",
+ )
+ result = _AGGREGATIONS[key](values)
+ if result is None:
+ return _unavailable(key, "The series has no non-null values.")
+ return BigNumberHeadline(value=result, aggregation=key, rows_used=len(values))
diff --git a/superset/mcp_service/chart/schemas.py b/superset/mcp_service/chart/schemas.py
index ef8b0322517..f48d99179f8 100644
--- a/superset/mcp_service/chart/schemas.py
+++ b/superset/mcp_service/chart/schemas.py
@@ -4276,6 +4276,39 @@ class ChartQueryResult(BaseModel):
total_rows: OptionalRowCount = Field(None, description="Total available rows")
+class BigNumberHeadline(BaseModel):
+ """The single headline number a Big Number chart displays.
+
+ The data rows are a time series for the trendline variant, so the displayed
+ number is not any one row: it is derived from the series by the chart's
+ aggregation (for example, the sum over all weekly rows). `value` is null,
+ with `reason` set, when it cannot be computed exactly.
+ """
+
+ value: int | float | str | None = Field(
+ None,
+ description=(
+ "The headline number as the chart displays it; null when it could "
+ "not be computed exactly (see reason)"
+ ),
+ )
+ aggregation: str | None = Field(
+ None,
+ description=(
+ "How the value was derived: 'total' for a Big Number chart, "
+ "otherwise the chart's aggregation applied to the trend series "
+ "(LAST_VALUE, sum, mean, min, max, median, or raw)"
+ ),
+ )
+ rows_used: int | None = Field(
+ None,
+ description="Count of non-null values aggregated; null if not applicable",
+ )
+ reason: str | None = Field(
+ None, description="Why value is null; null when a value is present"
+ )
+
+
class ChartData(BaseModel):
"""Rich chart data response with statistical insights."""
@@ -4295,6 +4328,16 @@ class ChartData(BaseModel):
),
)
+ headline: BigNumberHeadline | None = Field(
+ None,
+ description=(
+ "Big Number charts only (big_number, big_number_total): the headline "
+ "number the chart displays, computed from the full result rather than "
+ "the sample rows. Report this as the chart's value; do not derive it "
+ "from the rows. Null for other chart types."
+ ),
+ )
+
# Data insights
row_count: RowCount = Field(description="Rows returned")
total_rows: OptionalRowCount = Field(description="Total available rows")
diff --git a/superset/mcp_service/chart/tool/get_chart_data.py b/superset/mcp_service/chart/tool/get_chart_data.py
index 2e6878bbf8b..eb0568ca9a8 100644
--- a/superset/mcp_service/chart/tool/get_chart_data.py
+++ b/superset/mcp_service/chart/tool/get_chart_data.py
@@ -40,6 +40,10 @@ from superset.exceptions import (
)
from superset.extensions import event_logger
from superset.mcp_service import guest_scope
+from superset.mcp_service.chart.big_number_headline import (
+ compute_big_number_headline,
+ executed_query_facts,
+)
from superset.mcp_service.chart.chart_helpers import (
build_query_context_from_form_data,
build_query_dicts_from_form_data,
@@ -54,6 +58,7 @@ from superset.mcp_service.chart.query_result import (
query_result_failure,
)
from superset.mcp_service.chart.schemas import (
+ BigNumberHeadline,
ChartData,
ChartError,
ChartQueryResult,
@@ -291,6 +296,23 @@ def _filter_candidates(
return result
+def _big_number_headline(
+ viz_type: str | None,
+ form_data: dict[str, Any],
+ queries: list[dict[str, Any]],
+ query_context: Any,
+) -> BigNumberHeadline | None:
+ """Headline for Big Number charts, from the full executed result set."""
+ row_limit, operations = executed_query_facts(query_context)
+ return compute_big_number_headline(
+ viz_type,
+ form_data,
+ queries,
+ row_limit=row_limit,
+ post_processing_operations=operations,
+ )
+
+
def _build_query_results(
query_results: list[dict[str, Any]], limit: int | None
) -> list[ChartQueryResult] | None:
@@ -343,6 +365,14 @@ async def get_chart_data(
actually sees in the Explore view (not the saved version).
Returns underlying data in requested format with cache status.
+
+ For Big Number charts (big_number, big_number_total) the result also carries
+ `headline`: the number the chart displays, computed from the full result
+ (for big_number, by the chart's aggregation over the whole trend series).
+ The data rows alone are not that number, so report `headline.value`; when it
+ is null, `headline.reason` says why and the chart's value is unknown. The
+ "Overall value" (raw) aggregation needs the chart's saved query context, so
+ it has no headline for unsaved state or a `form_data_key`.
"""
return await execute_chart_data(request, ctx)
@@ -1049,6 +1079,12 @@ async def execute_chart_data( # noqa: C901
columns=columns,
data=data[: request.limit] if request.limit else data,
query_results=_build_query_results(result["queries"], request.limit),
+ headline=_big_number_headline(
+ form_data.get("viz_type") or chart_viz_type,
+ form_data,
+ result["queries"],
+ query_context,
+ ),
row_count=len(data),
total_rows=query_result.get("rowcount"),
summary=summary,
@@ -1300,6 +1336,9 @@ async def _query_from_form_data( # noqa: C901
columns=columns,
data=data[: request.limit] if request.limit else data,
query_results=_build_query_results(result["queries"], request.limit),
+ headline=_big_number_headline(
+ viz_type, form_data, result["queries"], query_context
+ ),
row_count=len(data),
total_rows=query_result.get("rowcount"),
summary=summary,
diff --git a/superset/mcp_service/dashboard/schemas.py b/superset/mcp_service/dashboard/schemas.py
index ad51bb93667..cde220c7ca6 100644
--- a/superset/mcp_service/dashboard/schemas.py
+++ b/superset/mcp_service/dashboard/schemas.py
@@ -93,6 +93,7 @@ if TYPE_CHECKING:
from superset.daos.base import ColumnOperator, ColumnOperatorEnum
from superset.exceptions import SupersetSecurityException
from superset.mcp_service.chart.schemas import (
+ BigNumberHeadline,
resolve_chart_datasource_id,
resolve_chart_datasource_name,
)
@@ -3246,6 +3247,15 @@ class DashboardChartData(BaseModel):
None,
description="Per-query layers for multi-query charts; null for single-query",
)
+ headline: BigNumberHeadline | None = Field(
+ None,
+ description=(
+ "Big Number charts only (big_number, big_number_total): the headline "
+ "number the chart displays, computed from the full result rather than "
+ "sample_data. Report this as the chart's value; do not derive it from "
+ "the sample rows. Null for other chart types."
+ ),
+ )
filtered: bool = Field(
False, description="Whether active filters were applied to this chart"
)
diff --git a/superset/mcp_service/dashboard/tool/get_dashboard_data.py b/superset/mcp_service/dashboard/tool/get_dashboard_data.py
index 3cc0e916f25..b80ace8b42a 100644
--- a/superset/mcp_service/dashboard/tool/get_dashboard_data.py
+++ b/superset/mcp_service/dashboard/tool/get_dashboard_data.py
@@ -138,6 +138,7 @@ def _summarize_chart_data(
total_rows=total_rows,
truncated=truncated,
queries=queries,
+ headline=result.headline,
filtered=bool(extra),
)
@@ -164,6 +165,14 @@ async def get_dashboard_data(
answer analytical questions about a whole dashboard in one call instead of
calling get_chart_data for every chart.
+ Big Number charts (big_number, big_number_total) also carry `headline`: the
+ one number the chart displays, computed from the full result, not from
+ sample_data. For big_number it is the chart's aggregation (latest value, sum,
+ mean, min, max, median, or overall value) over the whole trend series. Report
+ headline.value as the chart's value instead of reading or summing
+ sample_data; when it is null, headline.reason says why and the value is
+ unknown.
+
Example:
```json
{
diff --git a/tests/unit_tests/mcp_service/chart/test_big_number_headline.py b/tests/unit_tests/mcp_service/chart/test_big_number_headline.py
new file mode 100644
index 00000000000..ebd45c81f6e
--- /dev/null
+++ b/tests/unit_tests/mcp_service/chart/test_big_number_headline.py
@@ -0,0 +1,665 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Unit tests for the Big Number headline computation.
+
+The expected values follow the frontend: `aggregationChoices` and the
+BigNumber transformProps.
+"""
+
+from datetime import datetime, timezone
+from decimal import Decimal
+from itertools import permutations
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from superset.mcp_service.chart.big_number_headline import (
+ compute_big_number_headline,
+ executed_query_facts,
+ is_big_number_viz_type,
+)
+
+METRIC = "SUM(ytd_sales)"
+WEEK_MS = 7 * 24 * 3600 * 1000
+
+
+def _trend_rows(
+ values: list[Any], x_label: str = "__timestamp"
+) -> list[dict[str, Any]]:
+ """Chronological weekly rows."""
+ return [
+ {x_label: index * WEEK_MS, METRIC: value} for index, value in enumerate(values)
+ ]
+
+
+def _form_data(**overrides: Any) -> dict[str, Any]:
+ return {"viz_type": "big_number", "metric": METRIC, **overrides}
+
+
+def _headline(
+ rows: list[dict[str, Any]],
+ *,
+ overall: list[dict[str, Any]] | None = None,
+ row_limit: int | None = None,
+ operations: tuple[str, ...] = (),
+ rowcount: int | None = None,
+ viz_type: str = "big_number",
+ **form_data: Any,
+):
+ first: dict[str, Any] = {"data": rows}
+ if rowcount is not None:
+ first["rowcount"] = rowcount
+ queries = [first] + ([{"data": overall}] if overall is not None else [])
+ return compute_big_number_headline(
+ viz_type,
+ _form_data(**form_data),
+ queries,
+ row_limit=row_limit,
+ post_processing_operations=operations,
+ )
+
+
+@pytest.mark.parametrize(
+ ("aggregation", "expected"),
+ [
+ (None, 40),
+ ("", 40),
+ ("LAST_VALUE", 40),
+ ("sum", 100),
+ ("mean", 25),
+ ("min", 10),
+ ("max", 40),
+ ("median", 25),
+ ],
+)
+def test_aggregation_over_the_whole_series(aggregation: Any, expected: float) -> None:
+ headline = _headline(_trend_rows([10, 20, 30, 40]), aggregation=aggregation)
+
+ assert headline is not None
+ assert headline.value == expected
+ assert headline.reason is None
+ assert headline.rows_used == 4
+
+
+def test_every_row_counts_not_just_the_first_ten() -> None:
+ # 19 weekly values, as in a year-to-date weekly chart: the sum covers all of
+ # them, not the ten a sample would carry.
+ values = list(range(1, 20))
+ headline = _headline(_trend_rows(values), aggregation="sum")
+
+ assert headline is not None
+ assert headline.value == sum(values) == 190
+ assert headline.rows_used == 19
+
+
+def test_median_of_odd_count_is_the_middle_value() -> None:
+ headline = _headline(_trend_rows([9, 1, 5]), aggregation="median")
+
+ assert headline is not None
+ assert headline.value == 5
+
+
+@pytest.mark.parametrize(
+ ("aggregation", "expected_key"),
+ [
+ ("SUM", "sum"),
+ ("Mean", "mean"),
+ ("last_value", "LAST_VALUE"),
+ ("MAX", "max"),
+ ("not_an_aggregation", "LAST_VALUE"),
+ ],
+)
+def test_aggregation_lookup_is_case_insensitive_with_last_value_fallback(
+ aggregation: str, expected_key: str
+) -> None:
+ headline = _headline(_trend_rows([10, 20, 30]), aggregation=aggregation)
+
+ assert headline is not None
+ assert headline.aggregation == expected_key
+
+
+def test_last_value_is_the_newest_row_regardless_of_row_order() -> None:
+ rows = [
+ {"__timestamp": 3 * WEEK_MS, METRIC: 4},
+ {"__timestamp": 1 * WEEK_MS, METRIC: 2},
+ {"__timestamp": 2 * WEEK_MS, METRIC: 3},
+ ]
+
+ headline = _headline(rows, aggregation="LAST_VALUE")
+
+ assert headline is not None
+ assert headline.value == 4
+
+
+def test_last_value_orders_datetime_x_axis_values() -> None:
+ rows = [
+ {"order_date": datetime(2026, 3, 1), METRIC: 3},
+ {"order_date": datetime(2026, 1, 1), METRIC: 1},
+ {"order_date": datetime(2026, 2, 1, tzinfo=timezone.utc), METRIC: 2},
+ ]
+
+ headline = _headline(rows, x_axis="order_date")
+
+ assert headline is not None
+ assert headline.value == 3
+
+
+def test_last_value_orders_rows_keyed_by_granularity_column() -> None:
+ """Without an x-axis, the MCP query selects `granularity_sqla` by name."""
+ rows = [
+ {"ds": 3000, METRIC: 30},
+ {"ds": 1000, METRIC: 10},
+ {"ds": 2000, METRIC: 20},
+ ]
+
+ headline = _headline(rows, granularity_sqla="ds")
+
+ assert headline is not None
+ assert headline.value == 30
+ assert headline.reason is None
+
+
+def test_x_axis_takes_precedence_over_granularity_column() -> None:
+ rows = [
+ {"order_date": 2000, "ds": 1000, METRIC: 20},
+ {"order_date": 1000, "ds": 2000, METRIC: 10},
+ ]
+
+ headline = _headline(rows, x_axis="order_date", granularity_sqla="ds")
+
+ assert headline is not None
+ assert headline.value == 20
+
+
+def test_last_value_skips_a_null_latest_value() -> None:
+ headline = _headline(_trend_rows([10, 20, None]), aggregation="LAST_VALUE")
+
+ assert headline is not None
+ assert headline.value == 20
+ assert headline.rows_used == 2
+
+
+@pytest.mark.parametrize(
+ ("aggregation", "expected"),
+ [("sum", 30), ("mean", 15), ("min", 10), ("max", 20), ("median", 15)],
+)
+def test_nulls_are_dropped_before_aggregating(
+ aggregation: str, expected: float
+) -> None:
+ headline = _headline(_trend_rows([10, None, 20, None]), aggregation=aggregation)
+
+ assert headline is not None
+ assert headline.value == expected
+ assert headline.rows_used == 2
+
+
+def test_non_finite_and_boolean_values_count_as_null() -> None:
+ headline = _headline(
+ _trend_rows([10, float("nan"), float("inf"), True, 20]), aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value == 30
+
+
+def test_decimal_values_are_summed() -> None:
+ headline = _headline(
+ _trend_rows([Decimal("1.5"), Decimal("2.5")]), aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value == 4.0
+
+
+def test_all_null_series_has_no_headline() -> None:
+ headline = _headline(_trend_rows([None, None]), aggregation="sum")
+
+ assert headline is not None
+ assert headline.value is None
+ assert headline.reason
+
+
+def test_empty_result_has_no_headline() -> None:
+ headline = _headline([], aggregation="sum")
+
+ assert headline is not None
+ assert headline.value is None
+ assert "no rows" in (headline.reason or "")
+
+
+def test_missing_metric_column_has_no_headline() -> None:
+ headline = _headline([{"__timestamp": 0, "other": 1}], aggregation="sum")
+
+ assert headline is not None
+ assert headline.value is None
+ assert "metric column" in (headline.reason or "")
+
+
+def test_adhoc_metric_is_resolved_by_label() -> None:
+ rows = [{"__timestamp": 0, "Total Sales": 7}]
+
+ headline = compute_big_number_headline(
+ "big_number",
+ {
+ "metric": {"label": "Total Sales", "expressionType": "SQL"},
+ "aggregation": "sum",
+ },
+ [{"data": rows}],
+ )
+
+ assert headline is not None
+ assert headline.value == 7
+
+
+def test_truncated_by_row_limit_has_no_headline() -> None:
+ headline = _headline(_trend_rows([1, 2, 3]), row_limit=3, aggregation="sum")
+
+ assert headline is not None
+ assert headline.value is None
+ assert "truncated" in (headline.reason or "")
+
+
+def test_truncated_by_larger_source_total_has_no_headline() -> None:
+ headline = _headline(
+ _trend_rows([1, 2, 3]), row_limit=100, rowcount=250, aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value is None
+ assert "truncated" in (headline.reason or "")
+
+
+def test_fetch_below_row_limit_is_complete() -> None:
+ headline = _headline(
+ _trend_rows([1, 2, 3]), row_limit=4, rowcount=3, aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value == 6
+
+
+def test_raw_uses_the_overall_value_layer() -> None:
+ headline = _headline(
+ _trend_rows([10, 20, 30]),
+ overall=[{METRIC: 123.5}],
+ aggregation="raw",
+ )
+
+ assert headline is not None
+ assert headline.value == 123.5
+ assert headline.aggregation == "raw"
+ assert headline.reason is None
+
+
+def test_raw_falls_back_to_the_first_numeric_column_of_the_layer() -> None:
+ headline = _headline(
+ _trend_rows([10, 20]),
+ overall=[{"__timestamp": 5, "renamed": 9}],
+ aggregation="raw",
+ )
+
+ assert headline is not None
+ assert headline.value == 9
+
+
+def test_raw_ignores_truncation_of_the_trend_layer() -> None:
+ headline = _headline(
+ _trend_rows([10, 20, 30]),
+ overall=[{METRIC: 60}],
+ row_limit=3,
+ aggregation="raw",
+ )
+
+ assert headline is not None
+ assert headline.value == 60
+
+
+@pytest.mark.parametrize("overall", [None, [], [{METRIC: None}]])
+def test_raw_without_an_overall_value_has_no_headline(overall: Any) -> None:
+ headline = _headline(_trend_rows([10, 20, 30]), overall=overall, aggregation="raw")
+
+ assert headline is not None
+ assert headline.value is None
+ assert headline.aggregation == "raw"
+ assert "raw" in (headline.reason or "")
+
+
+def test_only_exact_raw_selects_the_overall_value_layer() -> None:
+ # The frontend adds the second query only for the exact string "raw"; any
+ # other casing is a client-side lookup of the raw choice, i.e. the latest value.
+ headline = _headline(_trend_rows([10, 20, 30]), aggregation="RAW")
+
+ assert headline is not None
+ assert headline.value == 30
+ assert headline.aggregation == "raw"
+
+
+@pytest.mark.parametrize(
+ ("rolling_type", "operation"),
+ [("sum", "rolling"), ("mean", "rolling"), ("std", "rolling"), ("cumsum", "cum")],
+)
+def test_rolling_window_not_in_the_rows_has_no_headline(
+ rolling_type: str, operation: str
+) -> None:
+ headline = _headline(
+ _trend_rows([1, 2, 3]), rolling_type=rolling_type, aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value is None
+ assert "rolling window" in (headline.reason or "")
+
+ reflected = _headline(
+ _trend_rows([1, 2, 3]),
+ rolling_type=rolling_type,
+ aggregation="sum",
+ operations=("pivot", operation, "flatten"),
+ )
+ assert reflected is not None
+ assert reflected.value == 6
+
+
+@pytest.mark.parametrize("rolling_type", [None, "None", ""])
+def test_no_rolling_window_needs_no_post_processing(rolling_type: Any) -> None:
+ headline = _headline(
+ _trend_rows([1, 2, 3]), rolling_type=rolling_type, aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value == 6
+
+
+@pytest.mark.parametrize(
+ "resample",
+ [
+ {"resample_rule": "1D", "resample_method": "zerofill"},
+ {"resample_rule": "1D", "resample_method": "asfreq"},
+ {"resample_rule": "1W", "resample_method": "ffill"},
+ ],
+)
+@pytest.mark.parametrize("aggregation", ["LAST_VALUE", "sum", "mean", "min", "median"])
+def test_resample_not_in_the_rows_has_no_headline(
+ resample: dict[str, Any], aggregation: str
+) -> None:
+ """Resampling changes the series, so unresampled rows give no headline."""
+ headline = _headline(
+ _trend_rows([70, 70, 70, 70]), aggregation=aggregation, **resample
+ )
+
+ assert headline is not None
+ assert headline.value is None
+ assert "resamples" in (headline.reason or "")
+
+ reflected = _headline(
+ _trend_rows([70, 70, 70, 70]),
+ aggregation=aggregation,
+ operations=("pivot", "resample", "flatten"),
+ **resample,
+ )
+ assert reflected is not None
+ assert reflected.value is not None
+
+
+@pytest.mark.parametrize(
+ "resample",
+ [
+ {"resample_rule": "1D"},
+ {"resample_method": "zerofill"},
+ {"resample_rule": None, "resample_method": "asfreq"},
+ {"resample_rule": "1D", "resample_method": ""},
+ ],
+)
+def test_incomplete_resample_needs_no_post_processing(
+ resample: dict[str, Any],
+) -> None:
+ """Like the frontend, resampling needs both a rule and a method."""
+ headline = _headline(_trend_rows([1, 2, 3]), aggregation="sum", **resample)
+
+ assert headline is not None
+ assert headline.value == 6
+
+
+@pytest.mark.parametrize("timestamp", [None, "invalid", float("nan"), float("inf")])
+@pytest.mark.parametrize("undated_metric", [1, None])
+@pytest.mark.parametrize("aggregation", ["LAST_VALUE", "RAW"])
+@pytest.mark.parametrize("row_order", list(permutations(range(3))))
+def test_latest_value_with_an_undated_row_has_no_headline(
+ timestamp: str | float | None,
+ undated_metric: int | None,
+ aggregation: str,
+ row_order: tuple[int, ...],
+) -> None:
+ """The frontend comparator treats an undated row as equal to every row, so
+ the value it renders depends on input order; no latest value is exact."""
+ rows: list[dict[str, Any]] = [
+ {"__timestamp": timestamp, METRIC: undated_metric},
+ {"__timestamp": 5, METRIC: 2},
+ {"__timestamp": 3, METRIC: 3},
+ ]
+
+ headline = _headline([rows[index] for index in row_order], aggregation=aggregation)
+
+ assert headline is not None
+ assert headline.value is None
+ assert "timestamp" in (headline.reason or "")
+
+
+def test_latest_value_does_not_diverge_from_the_rendered_chart() -> None:
+ """For these rows the frontend sort leaves the order unchanged and the
+ chart shows 10, not the newest dated 30."""
+ headline = _headline(
+ [
+ {"__timestamp": 1000, METRIC: 10},
+ {"__timestamp": None, METRIC: 99},
+ {"__timestamp": 3000, METRIC: 30},
+ ]
+ )
+
+ assert headline is not None
+ assert headline.value is None
+
+
+@pytest.mark.parametrize("aggregation", ["LAST_VALUE", "RAW"])
+@pytest.mark.parametrize("has_dated_null", [False, True])
+def test_latest_value_requires_dated_rows(
+ aggregation: str, has_dated_null: bool
+) -> None:
+ """Missing timestamps cannot supply a latest value."""
+ rows: list[dict[str, Any]] = [{METRIC: 1}, {"__timestamp": None, METRIC: 3}]
+ if has_dated_null:
+ rows.append({"__timestamp": 5, METRIC: None})
+
+ headline = _headline(rows, aggregation=aggregation)
+
+ assert headline is not None
+ assert headline.value is None
+ assert headline.reason
+
+
+@pytest.mark.parametrize("row_order", list(permutations(range(3))))
+def test_latest_value_with_an_undated_row_and_one_distinct_value(
+ row_order: tuple[int, ...],
+) -> None:
+ """When every non-null metric is equal, row order cannot change the value."""
+ rows: list[dict[str, Any]] = [
+ {"__timestamp": None, METRIC: 7},
+ {"__timestamp": 5, METRIC: 7},
+ {"__timestamp": 3, METRIC: None},
+ ]
+
+ headline = _headline([rows[index] for index in row_order])
+
+ assert headline is not None
+ assert headline.value == 7
+ assert headline.rows_used == 2
+
+
+def test_latest_value_preserves_input_order_for_equal_timestamps() -> None:
+ """Equal dated timestamps use the first non-null metric in input order."""
+ headline = _headline(
+ [
+ {"__timestamp": 5, METRIC: None},
+ {"__timestamp": 5, METRIC: 2},
+ {"__timestamp": 5, METRIC: 3},
+ ]
+ )
+
+ assert headline is not None
+ assert headline.value == 2
+ assert headline.rows_used == 2
+
+
+def test_order_independent_aggregations_need_no_times() -> None:
+ rows = [{"__timestamp": None, METRIC: 1}, {"__timestamp": None, METRIC: 2}]
+
+ headline = _headline(rows, aggregation="sum")
+
+ assert headline is not None
+ assert headline.value == 3
+
+
+def test_big_number_total_is_the_single_metric_value() -> None:
+ headline = _headline(
+ [{METRIC: 4321.5}], viz_type="big_number_total", aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value == 4321.5
+ assert headline.aggregation == "total"
+ assert headline.rows_used == 1
+ assert headline.reason is None
+
+
+def test_big_number_total_ignores_trend_aggregation_and_row_limit() -> None:
+ headline = _headline(
+ [{METRIC: 5}], viz_type="big_number_total", row_limit=1, aggregation="sum"
+ )
+
+ assert headline is not None
+ assert headline.value == 5
+
+
+def test_big_number_total_keeps_a_text_value() -> None:
+ headline = _headline([{METRIC: "N/A"}], viz_type="big_number_total")
+
+ assert headline is not None
+ assert headline.value == "N/A"
+
+
+@pytest.mark.parametrize(
+ "rows", [[], [{METRIC: None}], [{"other": 1}]], ids=["empty", "null", "no-metric"]
+)
+def test_big_number_total_without_a_value_has_no_headline(
+ rows: list[dict[str, Any]],
+) -> None:
+ headline = _headline(rows, viz_type="big_number_total")
+
+ assert headline is not None
+ assert headline.value is None
+ assert headline.reason
+
+
+@pytest.mark.parametrize(
+ "viz_type", ["table", "pop_kpi", "echarts_timeseries_line", None]
+)
+def test_other_chart_types_have_no_headline(viz_type: Any) -> None:
+ assert _headline(_trend_rows([1, 2]), viz_type=viz_type) is None
+
+
+def test_executed_query_facts_reads_limit_and_operations() -> None:
+ query_context = SimpleNamespace(
+ queries=[
+ SimpleNamespace(
+ row_limit=1000,
+ post_processing=[
+ {"operation": "pivot"},
+ {},
+ {"operation": "rolling"},
+ "not-a-step",
+ ],
+ )
+ ]
+ )
+
+ assert executed_query_facts(query_context) == (1000, ["pivot", "rolling"])
+
+
+@pytest.mark.parametrize(
+ "query_context",
+ [
+ SimpleNamespace(queries=[]),
+ SimpleNamespace(queries=[SimpleNamespace()]),
+ SimpleNamespace(),
+ ],
+)
+def test_executed_query_facts_tolerates_missing_attributes(query_context: Any) -> None:
+ assert executed_query_facts(query_context) == (None, [])
+
+
+@pytest.mark.parametrize("viz_type", ["big_number", "big_number_total"])
+@pytest.mark.parametrize(
+ "column",
+ [
+ {"columnName": "ytd_sales"},
+ {"column_name": "ytd_sales"},
+ {"columnName": "ytd_sales", "column_name": "other"},
+ ],
+)
+def test_simple_adhoc_metric_column_aliases(
+ viz_type: str, column: dict[str, str]
+) -> None:
+ """Simple adhoc labels accept both aliases, preferring camelCase."""
+ metric = {"expressionType": "SIMPLE", "aggregate": "SUM", "column": column}
+ headline = compute_big_number_headline(
+ viz_type, {"metric": metric}, [{"data": [{"__timestamp": 0, METRIC: 7}]}]
+ )
+
+ assert headline is not None
+ assert headline.value == 7
+ assert metric["column"] == column
+
+
+@pytest.mark.parametrize("viz_type", ["big_number", "big_number_total"])
+@pytest.mark.parametrize("value", [10**400, -(10**400)])
+def test_huge_integer_metric_is_unavailable(viz_type: str, value: int) -> None:
+ """Integers beyond float range return a null headline without crashing."""
+ headline = _headline(_trend_rows([value]), viz_type=viz_type)
+
+ assert headline is not None
+ assert headline.value is None
+ assert headline.reason
+
+
+@pytest.mark.parametrize("viz_type", ["big_number", "big_number_total"])
+def test_empty_form_data_is_safe(viz_type: str) -> None:
+ """Empty form data lacks a metric but remains a valid mapping."""
+ headline = compute_big_number_headline(viz_type, {}, [{"data": [{METRIC: 7}]}])
+
+ assert headline is not None
+ assert headline.value is None
+ assert "metric column" in (headline.reason or "")
+
+
+@pytest.mark.parametrize(
+ ("viz_type", "expected"),
+ [("big_number", True), ("big_number_total", True), ("table", False), (None, False)],
+)
+def test_is_big_number_viz_type(viz_type: str | None, expected: bool) -> None:
+ """Only the two Big Number visualization types have a headline."""
+ assert is_big_number_viz_type(viz_type) is expected
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
index 2cd2b202a49..1a0b681f30e 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
@@ -3526,3 +3526,261 @@ async def test_malformed_gantt_query_returns_validation_error(
assert isinstance(result, ChartError)
assert result.error_type == "ValidationError"
assert message in result.error
+
+
+class TestBigNumberHeadline:
+ """get_chart_data returns the Big Number headline, computed from the full
+ result set the query returned (not a sample) and the executed query."""
+
+ _METRIC = "SUM(ytd_sales)"
+
+ def _chart(self, form_data: dict[str, Any], viz_type: str = "big_number") -> Any:
+ return SimpleNamespace(
+ id=108,
+ slice_name="Total Sales",
+ viz_type=viz_type,
+ datasource_id=1,
+ datasource_type="table",
+ query_context=json.dumps(
+ {
+ "datasource": {"id": 1, "type": "table"},
+ "queries": [{"metrics": [self._METRIC], "row_limit": 50}],
+ "result_format": "json",
+ "result_type": "full",
+ }
+ ),
+ params=json.dumps(
+ {"viz_type": viz_type, "metric": self._METRIC, **form_data}
+ ),
+ )
+
+ async def _headline(
+ self,
+ mcp_server: Any,
+ form_data: dict[str, Any],
+ queries: list[dict[str, Any]],
+ *,
+ viz_type: str = "big_number",
+ post_processing: list[dict[str, Any]] | None = None,
+ limit: int | None = None,
+ cached_viz_type: str | None = None,
+ ) -> dict[str, Any] | None:
+ module = importlib.import_module(
+ "superset.mcp_service.chart.tool.get_chart_data"
+ )
+
+ def fake_load(self: Any, data: dict[str, Any]) -> Any:
+ query_objects = [
+ SimpleNamespace(
+ filter=[],
+ time_range=None,
+ row_limit=data["queries"][0]["row_limit"],
+ post_processing=post_processing or [],
+ to_dict=lambda: {},
+ )
+ ]
+ return SimpleNamespace(queries=query_objects, form_data={})
+
+ class _Command:
+ def __init__(self, query_context: Any) -> None: ...
+ def validate(self) -> None: ...
+ def run(self) -> dict[str, Any]:
+ return {"queries": queries}
+
+ cached_form_data = {
+ "viz_type": cached_viz_type,
+ "metric": self._METRIC,
+ "datasource": "1__table",
+ **form_data,
+ }
+ with (
+ patch.object(
+ module,
+ "get_cached_form_data",
+ return_value=json.dumps(cached_form_data),
+ ),
+ patch.object(
+ module,
+ "build_query_context_from_form_data",
+ return_value=fake_load(None, {"queries": [{"row_limit": 50}]}),
+ ),
+ patch.object(
+ module,
+ "find_chart_by_identifier",
+ return_value=self._chart(form_data, viz_type),
+ ),
+ patch.object(
+ module,
+ "validate_chart_dataset",
+ return_value=SimpleNamespace(is_valid=True, warnings=[], error=None),
+ ),
+ patch(
+ "superset.commands.chart.data.get_data_command.ChartDataCommand",
+ _Command,
+ ),
+ patch(
+ "superset.charts.schemas.ChartDataQueryContextSchema.load", fake_load
+ ),
+ ):
+ async with Client(mcp_server) as client:
+ request: dict[str, Any] = {"identifier": "108"}
+ if cached_viz_type:
+ request["form_data_key"] = "big-number-edits"
+ if limit:
+ request["limit"] = limit
+ result = await client.call_tool("get_chart_data", {"request": request})
+ return json.loads(result.content[0].text)["headline"]
+
+ def _query(self, values: list[Any]) -> dict[str, Any]:
+ return {
+ "data": [
+ {"__timestamp": index * 604800000, self._METRIC: value}
+ for index, value in enumerate(values)
+ ],
+ "colnames": ["__timestamp", self._METRIC],
+ "rowcount": len(values),
+ }
+
+ @pytest.mark.asyncio
+ async def test_headline_aggregates_every_row(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ values = list(range(1, 20))
+ headline = await self._headline(
+ mcp_server, {"aggregation": "sum"}, [self._query(values)]
+ )
+
+ assert headline is not None
+ assert headline["value"] == sum(values)
+ assert headline["aggregation"] == "sum"
+
+ @pytest.mark.asyncio
+ async def test_headline_is_null_when_the_fetch_hit_the_row_limit(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ headline = await self._headline(
+ mcp_server, {"aggregation": "sum"}, [self._query([1, 2, 3])], limit=3
+ )
+
+ assert headline is not None
+ assert headline["value"] is None
+ assert "truncated" in headline["reason"]
+
+ @pytest.mark.asyncio
+ async def test_headline_is_null_when_rolling_is_not_in_the_executed_query(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ form_data = {"aggregation": "sum", "rolling_type": "mean"}
+ queries = [self._query([1, 2, 3])]
+
+ without = await self._headline(mcp_server, form_data, queries)
+ with_rolling = await self._headline(
+ mcp_server,
+ form_data,
+ queries,
+ post_processing=[{"operation": "rolling"}],
+ )
+
+ assert without is not None
+ assert without["value"] is None
+ assert with_rolling is not None
+ assert with_rolling["value"] == 6
+
+ @pytest.mark.asyncio
+ async def test_headline_is_null_when_resample_is_not_in_the_executed_query(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ form_data = {
+ "aggregation": "mean",
+ "resample_rule": "1D",
+ "resample_method": "zerofill",
+ }
+ queries = [self._query([70, 70, 70, 70])]
+
+ without = await self._headline(mcp_server, form_data, queries)
+ with_resample = await self._headline(
+ mcp_server,
+ form_data,
+ queries,
+ post_processing=[{"operation": "resample"}],
+ )
+
+ assert without is not None
+ assert without["value"] is None
+ assert "resamples" in without["reason"]
+ assert with_resample is not None
+ assert with_resample["value"] == 70
+
+ @pytest.mark.asyncio
+ async def test_raw_headline_comes_from_the_overall_value_layer(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ overall = {"data": [{self._METRIC: 99}], "colnames": [self._METRIC]}
+ headline = await self._headline(
+ mcp_server,
+ {"aggregation": "raw"},
+ [self._query([1, 2, 3]), overall],
+ )
+
+ assert headline is not None
+ assert headline["value"] == 99
+
+ @pytest.mark.asyncio
+ async def test_big_number_total_headline(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ headline = await self._headline(
+ mcp_server,
+ {},
+ [{"data": [{self._METRIC: 4321}], "colnames": [self._METRIC]}],
+ viz_type="big_number_total",
+ )
+
+ assert headline is not None
+ assert headline["value"] == 4321
+ assert headline["aggregation"] == "total"
+
+ @pytest.mark.asyncio
+ async def test_other_chart_types_have_no_headline(
+ self, mcp_server: Any, mock_auth: Any
+ ) -> None:
+ headline = await self._headline(
+ mcp_server, {}, [self._query([1, 2, 3])], viz_type="table"
+ )
+
+ assert headline is None
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("saved_viz_type", "cached_viz_type", "expected_value", "expected_aggregation"),
+ [
+ ("table", "big_number", 6, "sum"),
+ ("big_number", "big_number_total", 1, "total"),
+ ("big_number_total", "big_number", 6, "sum"),
+ ("big_number", "table", None, None),
+ ],
+ )
+ async def test_headline_uses_the_unsaved_visualization_type(
+ self,
+ mcp_server: Any,
+ mock_auth: Any,
+ saved_viz_type: str,
+ cached_viz_type: str,
+ expected_value: int | None,
+ expected_aggregation: str | None,
+ ) -> None:
+ """Unsaved visualization changes determine which headline is displayed."""
+ headline = await self._headline(
+ mcp_server,
+ {"aggregation": "sum"},
+ [self._query([1, 2, 3])],
+ viz_type=saved_viz_type,
+ cached_viz_type=cached_viz_type,
+ )
+
+ if expected_aggregation is None:
+ assert headline is None
+ else:
+ assert headline is not None
+ assert headline["value"] == expected_value
+ assert headline["aggregation"] == expected_aggregation
diff --git a/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_data.py b/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_data.py
index 237a2b47281..51b9e45a9ea 100644
--- a/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_data.py
+++ b/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_data.py
@@ -26,6 +26,7 @@ from pydantic import ValidationError
from superset.mcp_service.app import mcp
from superset.mcp_service.chart.schemas import (
+ BigNumberHeadline,
ChartData,
ChartError,
ChartQueryResult,
@@ -139,6 +140,49 @@ async def test_returns_compact_summary_per_chart(mock_dao, mock_exec, mcp_server
assert "insights" not in first
+@patch(EXEC, new_callable=AsyncMock)
+@patch(DAO)
+@pytest.mark.asyncio
+async def test_big_number_headline_comes_from_the_chart_result_not_the_sample(
+ mock_dao, mock_exec, mcp_server
+):
+ """The headline spans the whole series; sample_rows only trims what's shown."""
+ rows = [{"__timestamp": i, "total": i} for i in range(1, 20)]
+ big_number = _chart_data(108, "Total Sales (YTD)", "big_number", rows=rows)
+ big_number.headline = BigNumberHeadline(
+ value=190, aggregation="sum", rows_used=len(rows)
+ )
+ unavailable = _chart_data(109, "Other KPI", "big_number")
+ unavailable.headline = BigNumberHeadline(
+ aggregation="sum", reason="The fetch was truncated at the row limit."
+ )
+ mock_dao.return_value = _dashboard(
+ 13,
+ "Sales",
+ [
+ _slice(108, "Total Sales (YTD)", "big_number"),
+ _slice(109, "Other KPI", "big_number"),
+ _slice(110, "Table"),
+ ],
+ )
+ mock_exec.side_effect = [big_number, unavailable, _chart_data(110, "Table")]
+
+ async with Client(mcp_server) as client:
+ data = await _call(client, {"identifier": 13, "sample_rows": 3})
+
+ first, second, third = data["charts"]
+ assert len(first["sample_data"]) == 3
+ assert first["headline"] == {
+ "value": 190,
+ "aggregation": "sum",
+ "rows_used": 19,
+ "reason": None,
+ }
+ assert second["headline"]["value"] is None
+ assert "truncated" in second["headline"]["reason"]
+ assert third["headline"] is None
+
+
@patch(EXEC, new_callable=AsyncMock)
@patch(DAO)
@pytest.mark.asyncio