You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ms...@apache.org on 2026/10/20 16:29:14 UTC
(superset) branch master updated: fix(pivot-table): blank mixed-metric totals in exports and reports (#45311)
This is an automated email from the ASF dual-hosted git repository.
msyavuz 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 1df897b3bba fix(pivot-table): blank mixed-metric totals in exports and reports (#45311)
1df897b3bba is described below
commit 1df897b3bbae3b75dbd2e76c10af0ff2c4e70dcf
Author: Mafi <ma...@gmail.com>
AuthorDate: Wed Oct 21 03:29:05 2026 +1100
fix(pivot-table): blank mixed-metric totals in exports and reports (#45311)
Co-authored-by: itzzdev09 <de...@gmail.com>
Co-authored-by: Evan Rusackas <ev...@preset.io>
---
UPDATING.md | 9 +
superset/charts/client_processing.py | 127 ++++----
superset/utils/excel.py | 7 +-
tests/unit_tests/charts/test_client_processing.py | 318 +++++++++++++++++----
.../mcp_service/native_tool_inventory.json | 30 +-
tests/unit_tests/utils/excel_tests.py | 13 +
6 files changed, 378 insertions(+), 126 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index ac9d0d0c111..591f79f3503 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,15 @@ assists people when migrating to a new version.
## Next
+- **Pivot Table mixed-metric export totals.** CSV/Excel exports and scheduled
+ CSV/text reports leave Total and Subtotal cells blank when they combine different
+ metrics, including two SUM metrics. Metric-specific values and totals remain
+ available, including with Combine metrics and Transpose pivot enabled. Previously
+ these cells could show an arbitrary metric's value or a sum across unrelated metrics.
+ Downstream consumers must handle empty cells or use a single metric that explicitly
+ computes the desired combined value. This change does not restore result-aggregation
+ parity between exports and the browser.
+
- **Impala SQL Lab stops no longer call the coordinator's HTTP cancel.** A SQL
Lab stop on Impala is delivered to the worker that is polling the query, which
cancels it with `cancel_operation()`, as Hive and Presto already do. The HTTP
diff --git a/superset/charts/client_processing.py b/superset/charts/client_processing.py
index 97b7fe60315..d8419e390a5 100644
--- a/superset/charts/client_processing.py
+++ b/superset/charts/client_processing.py
@@ -157,23 +157,20 @@ def get_metric_rollup_reducers(
return reducers
-def _collapsed_metric(present: list[Any], metrics: list[str]) -> Any:
+def _collapsed_metric(present: list[Any] | set[Any]) -> Any:
"""
- The metric a rollup spanning `present` stands for.
-
- A total that collapses the metric axis is undefined in the renderer, which
- resolves it to the last metric pushed into the shared slot (see the
- ``metricAxis`` handling in ``react-pivottable/utilities.ts``). Mirror that
- by taking the last metric in the configured order, so exported percentages
- match the chart rather than summing metrics that share no unit.
+ The metric a rollup spanning `present` stands for, or `None` when `present`
+ spans more than one distinct metric.
+
+ A total that collapses the metric axis has no single meaningful value once
+ it mixes distinct metrics -- e.g. a "Total" cell combining `MAX(sales)`
+ with `MEDIAN(msrp)`. The browser change in #44657 blanks that case instead
+ of picking one arbitrarily (see ``metricAxis`` handling in
+ ``react-pivottable/utilities.ts``); mirror it here so exported/scheduled
+ values agree with what the chart shows.
"""
- distinct = set(present)
- if len(distinct) == 1:
- return distinct.pop()
- for metric in reversed(metrics):
- if metric in distinct:
- return metric
- return None
+ distinct = present if isinstance(present, set) else set(present)
+ return next(iter(distinct)) if len(distinct) == 1 else None
def _broadcast(total: pd.Series, block: pd.DataFrame, axis: int) -> pd.DataFrame:
@@ -194,14 +191,30 @@ def _metric_of_column(column: Any, metric_level: int) -> Any:
return column[metric_level] if isinstance(column, tuple) else column
+def _rollup_metric(column: Any, metric_level: int, metrics: set[str]) -> Any:
+ """The metric to read from a rollup record for a cell in ``column``.
+
+ A column carrying a total label instead of a metric name collapses the metric
+ axis; see ``_collapsed_metric``.
+ """
+ name = _metric_of_column(column, metric_level)
+ return name if name in metrics else _collapsed_metric(metrics)
+
+
def _reduce(
data: Union[pd.DataFrame, pd.Series],
reducer: str,
axis: Optional[int] = None,
) -> Any:
- """Apply a rollup reducer (``sum``/``min``/``max``), skipping empty cells."""
+ """Apply a rollup reducer (``sum``/``min``/``max``), skipping empty cells.
+
+ A rollup with no non-null observations stays blank:
+ ``sum`` otherwise defaults an all-NaN input to 0, treating missing values
+ as a measured zero.
+ """
method = getattr(data, reducer)
- return method(axis=axis) if axis is not None else method()
+ kwargs = {"min_count": 1} if reducer == "sum" else {}
+ return method(axis=axis, **kwargs) if axis is not None else method(**kwargs)
def _rollup_index(
@@ -271,12 +284,6 @@ def _apply_rollup_totals( # pylint: disable=too-many-arguments,too-many-locals
keyed = _rollup_index(rollup_levels)
metric_names = set(metrics)
- def metric_of(column: Any) -> Any:
- name = _metric_of_column(column, metric_level)
- return (
- name if name in metric_names else _collapsed_metric(list(metrics), metrics)
- )
-
def lookup(row: Any, column: Any) -> tuple[bool, Any]:
row_depth = row_prefix_depth.get(row, len(rows))
column_depth = column_prefix_depth.get(column, len(columns))
@@ -287,7 +294,7 @@ def _apply_rollup_totals( # pylint: disable=too-many-arguments,too-many-locals
record = keyed(grouped).get(key)
if record is None:
return False, None
- return True, record.get(metric_of(column))
+ return True, record.get(_rollup_metric(column, metric_level, metric_names))
# Index positionally: a tuple label on a MultiIndex is ambiguous to `.loc`.
for column_position, column in enumerate(df.columns):
@@ -331,12 +338,6 @@ def _rollup_denominators( # pylint: disable=too-many-arguments,too-many-locals
keyed = _rollup_index(rollup_levels)
metric_names = set(metrics)
- def metric_of(column: Any) -> Any:
- name = _metric_of_column(column, metric_level)
- return (
- name if name in metric_names else _collapsed_metric(list(metrics), metrics)
- )
-
def denominator(row: Any, column: Any) -> tuple[bool, Any]:
if mode == ShowValuesAs.PERCENT_OF_TOTAL:
grouped: list[str] = []
@@ -356,7 +357,7 @@ def _rollup_denominators( # pylint: disable=too-many-arguments,too-many-locals
record = keyed(grouped).get(key)
if record is None:
return False, None
- return True, record.get(metric_of(column))
+ return True, record.get(_rollup_metric(column, metric_level, metric_names))
resolved = [[denominator(row, column) for column in df.columns] for row in df.index]
values = pd.DataFrame(
@@ -397,8 +398,8 @@ def _apply_show_values_as( # pylint: disable=too-many-arguments
- A total is rolled up within a single metric, so a cell is never divided by
a total that mixes in another metric, and each metric uses its own
reducer -- a MIN/MAX metric divides by the row's minimum/maximum rather
- than its sum. A total that collapses the metric axis resolves to a single
- metric the way the renderer does; see ``_collapsed_metric``.
+ than its sum. A total that combines distinct metrics stays blank; see
+ ``_collapsed_metric``.
A zero denominator yields NaN (blank) rather than infinity, matching
``pandas_postprocessing.pivot``'s ``show_values_as``.
@@ -418,6 +419,8 @@ def _apply_show_values_as( # pylint: disable=too-many-arguments
derived = pd.DataFrame(np.nan, index=numeric.index, columns=numeric.columns)
for metric in dict.fromkeys(metric_of_column):
selection = np.array([column == metric for column in metric_of_column])
+ # Mixed-metric numerators are blank, so the fallback cross-metric
+ # denominator cannot produce a displayed value.
denominator_selection = (
selection if metric is not None else np.ones(len(selection), dtype=bool)
)
@@ -431,8 +434,7 @@ def _apply_show_values_as( # pylint: disable=too-many-arguments
metric_of_column, denominator_selection, strict=True
)
if keep and column_metric is not None
- ],
- metrics,
+ ]
)
reducer = reducers.get(str(denominator_metric), DEFAULT_ROLLUP_REDUCER)
if denominator_metric is not None:
@@ -606,27 +608,37 @@ def pivot_df( # pylint: disable=too-many-locals, too-many-arguments, too-many-s
# still divides by itself: a MAX metric's row total is the row's maximum,
# and dividing that maximum by itself reads 100%.
totals_metric_level = df.columns.nlevels - 1 if combine_metrics else 0
- # A column carrying a total label rather than a metric name rolls up
- # everything; with no metric to resolve it to, it sums.
+ # Single-metric totals retain their reducer. Mixed-metric totals are
+ # blanked before reduction; the fallback cannot make them meaningful.
cross_metric_reducer = (
reducers.get(metrics[0], DEFAULT_ROLLUP_REDUCER)
if len(set(metrics)) == 1
else DEFAULT_ROLLUP_REDUCER
)
- def collapse(block: pd.DataFrame) -> tuple[pd.DataFrame, str]:
- """Narrow a total's source columns to one metric, and pick its reducer."""
- metric_names = set(metrics)
+ metric_names = set(metrics)
+
+ def collapse(block: pd.DataFrame) -> tuple[Optional[pd.DataFrame], str]:
+ """Narrow a total's source columns to one metric, and pick its reducer.
+
+ Returns `(None, reducer)` when `block` spans more than one distinct
+ metric: such a total has no single meaningful value, so the caller
+ blanks it instead of summing across metrics that share no unit
+ (matches the browser change proposed in #44657).
+ """
present = [
_metric_of_column(column, totals_metric_level) for column in block.columns
]
known = [metric for metric in present if metric in metric_names]
- metric = _collapsed_metric(known, metrics) if known else None
- if metric is None:
+ if not known:
return block, cross_metric_reducer
+ metric = _collapsed_metric(known)
+ if metric is None:
+ return None, DEFAULT_ROLLUP_REDUCER
keep = [column == metric for column in present]
return block.loc[:, keep], reducers.get(str(metric), DEFAULT_ROLLUP_REDUCER)
+ mixed_metric_totals: list[Any] = []
if show_rows_total:
# add subtotal for each group and overall total; we start from the
# overall group, and iterate deeper into subgroups
@@ -654,8 +666,13 @@ def pivot_df( # pylint: disable=too-many-locals, too-many-arguments, too-many-s
# to a number. The row totals below already coerce; do the
# same here so a total means the same thing on both axes.
block = block.apply(pd.to_numeric, errors="coerce")
- if percent_mode:
- source, reducer = collapse(block)
+ source, reducer = collapse(block)
+ mixed_metrics = (
+ source is None and aggfunc != CURRENCY_CONTEXT_AGGREGATION
+ )
+ if mixed_metrics:
+ subtotal = pd.Series(np.nan, index=block.index)
+ elif percent_mode:
subtotal = _reduce(source, reducer, axis=1)
else:
subtotal = summarize_frame(aggfunc, block, axis=1)
@@ -665,6 +682,8 @@ def pivot_df( # pylint: disable=too-many-locals, too-many-arguments, too-many-s
# insert column after subgroup
df.insert(int(slice_.stop), subtotal_name, subtotal)
inserted_columns.append(subtotal_name)
+ if mixed_metrics:
+ mixed_metric_totals.append(subtotal_name)
column_prefix_depth[subtotal_name] = (
level if combine_metrics else max(0, level - 1)
)
@@ -686,7 +705,9 @@ def pivot_df( # pylint: disable=too-many-locals, too-many-arguments, too-many-s
)
raise
- subtotal_values = df.iloc[slice_, :]
+ # These labels were inserted above; no columns are removed
+ # before this point. Keep strict lookup to catch broken invariants.
+ subtotal_values = df.iloc[slice_, :].drop(columns=mixed_metric_totals)
if aggfunc != CURRENCY_CONTEXT_AGGREGATION:
subtotal_values = subtotal_values.apply(
pd.to_numeric, errors="coerce"
@@ -702,7 +723,11 @@ def pivot_df( # pylint: disable=too-many-locals, too-many-arguments, too-many-s
subtotal.name = tuple([*subgroup, total, *([""] * depth)]) # noqa: C409
# insert row after subgroup
df = pd.concat(
- [df[: slice_.stop], subtotal.to_frame().T, df[slice_.stop :]]
+ [
+ df[: slice_.stop],
+ subtotal.to_frame().T.reindex(columns=df.columns),
+ df[slice_.stop :],
+ ]
)
inserted_rows.append(subtotal.name)
row_prefix_depth[subtotal.name] = level
@@ -752,13 +777,13 @@ def pivot_df( # pylint: disable=too-many-locals, too-many-arguments, too-many-s
else None,
)
- # if we want to apply the metrics on the rows we need to pivot the
- # dataframe back
+ # Replace placeholders before transposing, while column dtypes are intact.
+ df.replace("SUPERSET_PANDAS_NAN", np.nan, inplace=True)
if apply_metrics_on_rows:
- df = df.T
+ # Mixed blank columns must not coerce integer cells through float64
+ # during transposition (which would round integers above 2**53).
+ df = df.astype(object).T if mixed_metric_totals else df.T
- # replace the remaining temporary placeholder string for np.nan after pivoting
- df.replace("SUPERSET_PANDAS_NAN", np.nan, inplace=True)
df.rename(
index={"SUPERSET_PANDAS_NAN": np.nan},
columns={"SUPERSET_PANDAS_NAN": np.nan},
diff --git a/superset/utils/excel.py b/superset/utils/excel.py
index 269ace9d725..437cd6739dd 100644
--- a/superset/utils/excel.py
+++ b/superset/utils/excel.py
@@ -219,7 +219,12 @@ def apply_column_types(
series = df.iloc[:, idx]
if column_type == GenericDataType.NUMERIC:
try:
- series = pd.to_numeric(series)
+ # Nullable integers retain exact values alongside blank totals.
+ # Convert to object before apply, which would otherwise coerce
+ # nullable integers through float64 during scalar mapping.
+ series = pd.to_numeric(series, dtype_backend="numpy_nullable").astype(
+ object
+ )
# if the number is too large, convert it to a string
# Excel does not support numbers larger than 10^15
series = series.apply(
diff --git a/tests/unit_tests/charts/test_client_processing.py b/tests/unit_tests/charts/test_client_processing.py
index e4e1ba88410..c59d8100095 100644
--- a/tests/unit_tests/charts/test_client_processing.py
+++ b/tests/unit_tests/charts/test_client_processing.py
@@ -25,6 +25,8 @@ from flask_babel import lazy_gettext as _
from sqlalchemy.orm.session import Session
from superset.charts.client_processing import (
+ _collapsed_metric,
+ _reduce,
apply_client_processing,
apply_pivot_number_formats,
format_column,
@@ -245,7 +247,7 @@ def test_pivot_df_no_cols_no_rows_two_metrics():
== f"""
| | ('SUM(num)',) | ('MAX(num)',) | ('{_("Total")} (Sum)',) |
|:-----------------|----------------:|----------------:|-------------------:|
-| ('{_("Total")} (Sum)',) | 80679663 | 37296 | 80716959 |
+| ('{_("Total")} (Sum)',) | 8.06797e+07 | 37296 | nan |
""".strip()
)
@@ -356,9 +358,9 @@ def test_pivot_df_single_row_two_metrics():
== f"""
| | ('SUM(num)',) | ('MAX(num)',) | ('{_("Total")} (Sum)',) |
|:-----------------|----------------:|----------------:|-------------------:|
-| ('boy',) | 47123 | 1280 | 48403 |
-| ('girl',) | 118065 | 2588 | 120653 |
-| ('{_("Total")} (Sum)',) | 165188 | 3868 | 169056 |
+| ('boy',) | 47123 | 1280 | nan |
+| ('girl',) | 118065 | 2588 | nan |
+| ('{_("Total")} (Sum)',) | 165188 | 3868 | nan |
""".strip()
)
@@ -382,11 +384,11 @@ def test_pivot_df_single_row_two_metrics():
|:-------------------------|-------------------:|
| ('SUM(num)', 'boy') | 47123 |
| ('SUM(num)', 'girl') | 118065 |
-| ('SUM(num)', 'Subtotal') | 165188 |
+| ('SUM(num)', '{_("Subtotal")}') | 165188 |
| ('MAX(num)', 'boy') | 1280 |
| ('MAX(num)', 'girl') | 2588 |
-| ('MAX(num)', 'Subtotal') | 3868 |
-| ('{_("Total")} (Sum)', '') | 169056 |
+| ('MAX(num)', '{_("Subtotal")}') | 3868 |
+| ('{_("Total")} (Sum)', '') | nan |
""".strip()
)
@@ -410,11 +412,11 @@ def test_pivot_df_single_row_two_metrics():
|:---------------------|-------------------:|
| ('boy', 'SUM(num)') | 47123 |
| ('boy', 'MAX(num)') | 1280 |
-| ('boy', 'Subtotal') | 48403 |
+| ('boy', '{_("Subtotal")}') | nan |
| ('girl', 'SUM(num)') | 118065 |
| ('girl', 'MAX(num)') | 2588 |
-| ('girl', 'Subtotal') | 120653 |
-| ('{_("Total")} (Sum)', '') | 169056 |
+| ('girl', '{_("Subtotal")}') | nan |
+| ('{_("Total")} (Sum)', '') | nan |
""".strip()
)
@@ -525,9 +527,9 @@ def test_pivot_df_single_row_null_values():
== """
| | ('SUM(num)',) | ('MAX(num)',) | ('Total (Sum)',) |
|:-----------------|----------------:|----------------:|-------------------:|
-| ('boy',) | nan | nan | 0 |
-| ('girl',) | 118065 | 2588 | 120653 |
-| ('Total (Sum)',) | 118065 | 2588 | 120653 |
+| ('boy',) | nan | nan | nan |
+| ('girl',) | 118065 | 2588 | nan |
+| ('Total (Sum)',) | 118065 | 2588 | nan |
""".strip()
)
@@ -576,11 +578,11 @@ def test_pivot_df_single_row_null_values():
|:---------------------|-------------------:|
| ('boy', 'SUM(num)') | nan |
| ('boy', 'MAX(num)') | nan |
-| ('boy', 'Subtotal') | 0 |
+| ('boy', '{_("Subtotal")}') | nan |
| ('girl', 'SUM(num)') | 118065 |
| ('girl', 'MAX(num)') | 2588 |
-| ('girl', 'Subtotal') | 120653 |
-| ('{_("Total")} (Sum)', '') | 120653 |
+| ('girl', '{_("Subtotal")}') | nan |
+| ('{_("Total")} (Sum)', '') | nan |
""".strip()
)
@@ -692,9 +694,9 @@ def test_pivot_df_single_row_null_mix_values_strings():
== """
| | ('SUM(num)',) | ('MAX(num)',) | ('Total (Sum)',) |
|:-----------------|:----------------|----------------:|-------------------:|
-| ('boy',) | NULL | nan | 0 |
-| ('girl',) | 118065 | 2588 | 120653 |
-| ('Total (Sum)',) | 118065.0 | 2588 | 120653 |
+| ('boy',) | NULL | nan | nan |
+| ('girl',) | 118065 | 2588 | nan |
+| ('Total (Sum)',) | 118065.0 | 2588 | nan |
""".strip()
)
@@ -718,11 +720,11 @@ def test_pivot_df_single_row_null_mix_values_strings():
|:---------------------|:-------------------|
| ('boy', 'SUM(num)') | NULL |
| ('boy', 'MAX(num)') | nan |
-| ('boy', 'Subtotal') | 0.0 |
+| ('boy', 'Subtotal') | nan |
| ('girl', 'SUM(num)') | 118065 |
| ('girl', 'MAX(num)') | 2588.0 |
-| ('girl', 'Subtotal') | 120653.0 |
-| ('Total (Sum)', '') | 120653.0 |
+| ('girl', 'Subtotal') | nan |
+| ('Total (Sum)', '') | nan |
""".strip()
)
@@ -862,7 +864,7 @@ def test_pivot_df_single_row_null_mix_values_numbers():
| ('MAX(num)', 'boy') | nan |
| ('MAX(num)', 'girl') | 2588 |
| ('MAX(num)', 'Subtotal') | 2588 |
-| ('Total (Sum)', '') | 120674 |
+| ('Total (Sum)', '') | nan |
""".strip()
)
@@ -886,11 +888,11 @@ def test_pivot_df_single_row_null_mix_values_numbers():
|:---------------------|-------------------:|
| ('boy', 'SUM(num)') | 21 |
| ('boy', 'MAX(num)') | nan |
-| ('boy', 'Subtotal') | 21 |
+| ('boy', '{_("Subtotal")}') | nan |
| ('girl', 'SUM(num)') | 118065 |
| ('girl', 'MAX(num)') | 2588 |
-| ('girl', 'Subtotal') | 120653 |
-| ('{_("Total")} (Sum)', '') | 120674 |
+| ('girl', '{_("Subtotal")}') | nan |
+| ('{_("Total")} (Sum)', '') | nan |
""".strip()
)
@@ -1091,15 +1093,15 @@ def test_pivot_df_complex():
== """
| | ('SUM(num)', 'CA') | ('SUM(num)', 'FL') | ('SUM(num)', 'Subtotal') | ('MAX(num)', 'CA') | ('MAX(num)', 'FL') | ('MAX(num)', 'Subtotal') | ('Total (Sum)', '') |
|:---------------------|---------------------:|---------------------:|---------------------------:|---------------------:|---------------------:|---------------------------:|----------------------:|
-| ('boy', 'Edward') | 31290 | 9395 | 40685 | 1280 | 389 | 1669 | 42354 |
-| ('boy', 'Tony') | 3765 | 2673 | 6438 | 598 | 247 | 845 | 7283 |
-| ('boy', 'Subtotal') | 35055 | 12068 | 47123 | 1878 | 636 | 2514 | 49637 |
-| ('girl', 'Amy') | 45426 | 14740 | 60166 | 2227 | 854 | 3081 | 63247 |
-| ('girl', 'Cindy') | 14149 | 1218 | 15367 | 842 | 217 | 1059 | 16426 |
-| ('girl', 'Dawn') | 11403 | 5089 | 16492 | 1157 | 461 | 1618 | 18110 |
-| ('girl', 'Sophia') | 18859 | 7181 | 26040 | 2588 | 1187 | 3775 | 29815 |
-| ('girl', 'Subtotal') | 89837 | 28228 | 118065 | 6814 | 2719 | 9533 | 127598 |
-| ('Total (Sum)', '') | 124892 | 40296 | 165188 | 8692 | 3355 | 12047 | 177235 |
+| ('boy', 'Edward') | 31290 | 9395 | 40685 | 1280 | 389 | 1669 | nan |
+| ('boy', 'Tony') | 3765 | 2673 | 6438 | 598 | 247 | 845 | nan |
+| ('boy', 'Subtotal') | 35055 | 12068 | 47123 | 1878 | 636 | 2514 | nan |
+| ('girl', 'Amy') | 45426 | 14740 | 60166 | 2227 | 854 | 3081 | nan |
+| ('girl', 'Cindy') | 14149 | 1218 | 15367 | 842 | 217 | 1059 | nan |
+| ('girl', 'Dawn') | 11403 | 5089 | 16492 | 1157 | 461 | 1618 | nan |
+| ('girl', 'Sophia') | 18859 | 7181 | 26040 | 2588 | 1187 | 3775 | nan |
+| ('girl', 'Subtotal') | 89837 | 28228 | 118065 | 6814 | 2719 | 9533 | nan |
+| ('Total (Sum)', '') | 124892 | 40296 | 165188 | 8692 | 3355 | 12047 | nan |
""".strip() # noqa: E501
)
@@ -1189,11 +1191,11 @@ def test_pivot_df_complex():
|:--------------------|--------------------:|------------------:|----------------------:|------------------:|--------------------:|-------------------:|---------------------:|-----------------------:|----------------------:|
| ('CA', 'SUM(num)') | 31290 | 3765 | 35055 | 45426 | 14149 | 11403 | 18859 | 89837 | 124892 |
| ('CA', 'MAX(num)') | 1280 | 598 | 1878 | 2227 | 842 | 1157 | 2588 | 6814 | 8692 |
-| ('CA', 'Subtotal') | 32570 | 4363 | 36933 | 47653 | 14991 | 12560 | 21447 | 96651 | 133584 |
+| ('CA', 'Subtotal') | nan | nan | nan | nan | nan | nan | nan | nan | nan |
| ('FL', 'SUM(num)') | 9395 | 2673 | 12068 | 14740 | 1218 | 5089 | 7181 | 28228 | 40296 |
| ('FL', 'MAX(num)') | 389 | 247 | 636 | 854 | 217 | 461 | 1187 | 2719 | 3355 |
-| ('FL', 'Subtotal') | 9784 | 2920 | 12704 | 15594 | 1435 | 5550 | 8368 | 30947 | 43651 |
-| ('Total (Sum)', '') | 42354 | 7283 | 49637 | 63247 | 16426 | 18110 | 29815 | 127598 | 177235 |
+| ('FL', 'Subtotal') | nan | nan | nan | nan | nan | nan | nan | nan | nan |
+| ('Total (Sum)', '') | nan | nan | nan | nan | nan | nan | nan | nan | nan |
""".strip() # noqa: E501
)
@@ -1381,9 +1383,8 @@ def test_pivot_df_multi_column():
== """
| | ('SUM(num)', 'boy') | ('SUM(num)', 'girl') | ('SUM(num)', 'Subtotal') | ('MAX(num)', 'boy') | ('MAX(num)', 'girl') | ('MAX(num)', 'Subtotal') | ('Total (Sum)', '') |
|:-----------------|----------------------:|-----------------------:|---------------------------:|----------------------:|-----------------------:|---------------------------:|----------------------:|
-| ('CA',) | 35055 | 89837 | 124892 | 1878 | 6814 | 8692 | 133584 |
-| ('Total (Sum)',) | 12068 | 28228 | 40296 | 636 | 2719 | 3355 | 43651 |
-
+| ('CA',) | 35055 | 89837 | 124892 | 1878 | 6814 | 8692 | nan |
+| ('Total (Sum)',) | 12068 | 28228 | 40296 | 636 | 2719 | 3355 | nan |
""".strip() # noqa: E501
)
@@ -1453,11 +1454,11 @@ def test_pivot_df_multi_column():
|:---------------------|----------:|-------------------:|
| ('boy', 'SUM(num)') | 35055 | 12068 |
| ('boy', 'MAX(num)') | 1878 | 636 |
-| ('boy', 'Subtotal') | 36933 | 12704 |
+| ('boy', 'Subtotal') | nan | nan |
| ('girl', 'SUM(num)') | 89837 | 28228 |
| ('girl', 'MAX(num)') | 6814 | 2719 |
-| ('girl', 'Subtotal') | 96651 | 30947 |
-| ('Total (Sum)', '') | 133584 | 43651 |
+| ('girl', 'Subtotal') | nan | nan |
+| ('Total (Sum)', '') | nan | nan |
""".strip()
)
@@ -1677,16 +1678,16 @@ def test_pivot_df_complex_null_values():
== """
| | ('SUM(num)', nan) | ('SUM(num)', 'Subtotal') | ('MAX(num)', nan) | ('MAX(num)', 'Subtotal') | ('Total (Sum)', '') |
|:---------------------|--------------------:|---------------------------:|--------------------:|---------------------------:|----------------------:|
-| ('boy', 'Edward') | 40685 | 40685 | 1669 | 1669 | 42354 |
-| ('boy', 'Tony') | 6438 | 6438 | 845 | 845 | 7283 |
-| ('boy', 'Subtotal') | 47123 | 47123 | 2514 | 2514 | 49637 |
-| ('girl', 'Amy') | 60166 | 60166 | 3081 | 3081 | 63247 |
-| ('girl', 'Cindy') | 15367 | 15367 | 1059 | 1059 | 16426 |
-| ('girl', 'Dawn') | 16492 | 16492 | 1618 | 1618 | 18110 |
-| ('girl', 'Sophia') | 26040 | 26040 | 3775 | 3775 | 29815 |
-| ('girl', 'Subtotal') | 118065 | 118065 | 9533 | 9533 | 127598 |
-| ('Total (Sum)', '') | 165188 | 165188 | 12047 | 12047 | 177235 |
- """.strip() # noqa: E501
+| ('boy', 'Edward') | 40685 | 40685 | 1669 | 1669 | nan |
+| ('boy', 'Tony') | 6438 | 6438 | 845 | 845 | nan |
+| ('boy', 'Subtotal') | 47123 | 47123 | 2514 | 2514 | nan |
+| ('girl', 'Amy') | 60166 | 60166 | 3081 | 3081 | nan |
+| ('girl', 'Cindy') | 15367 | 15367 | 1059 | 1059 | nan |
+| ('girl', 'Dawn') | 16492 | 16492 | 1618 | 1618 | nan |
+| ('girl', 'Sophia') | 26040 | 26040 | 3775 | 3775 | nan |
+| ('girl', 'Subtotal') | 118065 | 118065 | 9533 | 9533 | nan |
+| ('Total (Sum)', '') | 165188 | 165188 | 12047 | 12047 | nan |
+ """.strip() # noqa: E501
)
# apply_metrics_on_rows
@@ -1775,8 +1776,8 @@ def test_pivot_df_complex_null_values():
|:--------------------|--------------------:|------------------:|----------------------:|------------------:|--------------------:|-------------------:|---------------------:|-----------------------:|----------------------:|
| (nan, 'SUM(num)') | 40685 | 6438 | 47123 | 60166 | 15367 | 16492 | 26040 | 118065 | 165188 |
| (nan, 'MAX(num)') | 1669 | 845 | 2514 | 3081 | 1059 | 1618 | 3775 | 9533 | 12047 |
-| (nan, 'Subtotal') | 42354 | 7283 | 49637 | 63247 | 16426 | 18110 | 29815 | 127598 | 177235 |
-| ('Total (Sum)', '') | 42354 | 7283 | 49637 | 63247 | 16426 | 18110 | 29815 | 127598 | 177235 |
+| (nan, 'Subtotal') | nan | nan | nan | nan | nan | nan | nan | nan | nan |
+| ('Total (Sum)', '') | nan | nan | nan | nan | nan | nan | nan | nan | nan |
""".strip() # noqa: E501
)
@@ -1906,9 +1907,79 @@ def test_pivot_df_show_values_as_keeps_metrics_separate():
assert pivoted.loc[("US",), ("SUM(num)", "boy")] == 0.25
assert pivoted.loc[("UK",), ("MAX(num)", "boy")] == 0.375
assert pivoted.loc[("UK",), ("MAX(num)", "girl")] == 0.625
- # a total collapsing the metric axis resolves to one metric, as the
- # renderer does, so it still divides by itself
- assert pivoted.loc[("US",), (total_label(), "")] == 1
+ # a total collapsing the metric axis mixes SUM(num) and MAX(num), which
+ # share no unit, so the renderer blanks it (#44657) instead of picking one
+ # arbitrarily (#44725) -- exported values must agree with what it shows
+ assert pd.isna(pivoted.loc[("US",), (total_label(), "")])
+
+
+def test_pivot_df_show_values_as_blanks_mixed_metric_grand_total():
+ """https://github.com/apache/superset/issues/44725
+
+ A pivot with 2+ metrics on columns and row/column totals enabled has no
+ single meaningful value for the cell where both the row and column totals
+ meet (it would mix every configured metric). Before #44657 the renderer
+ picked one metric there; the export/report path must match its current,
+ blanked behavior rather than showing a specific, plausible-looking number.
+ """
+ df = show_values_as_df()
+ df["MAX(num)"] = [1, 3, 6, 10]
+ pivoted = pivot_df(
+ df,
+ **{**SHOW_VALUES_AS_OPTIONS, "metrics": ["SUM(num)", "MAX(num)"]},
+ show_values_as="percent_total",
+ )
+
+ assert pd.isna(pivoted.loc[("UK",), (total_label(), "")])
+ assert pd.isna(pivoted.loc[("US",), (total_label(), "")])
+ assert pd.isna(pivoted.loc[(total_label(),), (total_label(), "")])
+
+
+@pytest.mark.parametrize("layout", ["COLUMNS", "ROWS"])
+@pytest.mark.parametrize("with_rollups", [False, True])
+@pytest.mark.parametrize("mode", [None, "percent_row", "percent_col", "percent_total"])
+@pytest.mark.parametrize("aggregation", ["Sum", "Average"])
+def test_pivot_table_v2_blanks_mixed_metric_totals(
+ layout: str, with_rollups: bool, mode: str | None, aggregation: str
+):
+ """Mixed totals stay blank in both layouts, with or without GROUPING SETS."""
+ if with_rollups:
+ df = grouping_sets_df()
+ df["MAX(num)"] = [1, 6, 6, 1, 6, 6]
+ metrics = ["AVG(num)", "MAX(num)"]
+ else:
+ df = show_values_as_df()
+ df["MAX(num)"] = [1, 3, 6, 10]
+ metrics = ["SUM(num)", "MAX(num)"]
+ form_data = {
+ "groupbyRows": ["nation"],
+ "groupbyColumns": ["gender"],
+ "metrics": metrics,
+ "metricsLayout": layout,
+ "rowTotals": True,
+ "colTotals": True,
+ "showValuesAs": mode,
+ "aggregateFunction": aggregation,
+ }
+ pivoted = pivot_table_v2(df, form_data, apply_number_format=False)
+ total = f"{_('Total')} ({aggregation})"
+ if layout == "ROWS":
+ mixed = pivoted.loc[(total, ""), :]
+ leaf = pivoted.loc[(metrics[0], "US"), ("boy",)]
+ metric_total = pivoted.loc[(metrics[0], "Subtotal"), (total,)]
+ else:
+ mixed = pivoted.loc[:, (total, "")]
+ leaf = pivoted.loc[("US",), (metrics[0], "boy")]
+ metric_total = pivoted.loc[(total,), (metrics[0], "Subtotal")]
+ # Includes the grand-total corner: all-blank sums must not revive it as 0.
+ assert mixed.isna().all()
+ assert pd.notna(leaf)
+ assert pd.notna(metric_total)
+ if mode is None:
+ assert leaf == 10
+ assert metric_total == (
+ 19 if with_rollups else (80 if aggregation == "Sum" else 20)
+ )
def test_pivot_df_show_values_as_with_combined_metrics():
@@ -4950,3 +5021,132 @@ def test_apply_client_processing_csv_format_pivot_table_multiple_rows():
("London", "Consumer"),
("London", "Corporate"),
}
+
+
+@pytest.mark.parametrize("reducer", ["sum", "min", "max"])
+def test_pivot_rollup_reducer_preserves_blank_and_zero(reducer: str):
+ assert pd.isna(_reduce(pd.Series([float("nan"), float("nan")]), reducer))
+ assert _reduce(pd.Series([0, float("nan")]), reducer) == 0
+
+
+@pytest.mark.parametrize("layout", ["COLUMNS", "ROWS"])
+@pytest.mark.parametrize("combine", [False, True])
+@pytest.mark.parametrize("transpose", [False, True])
+def test_pivot_mixed_totals_preserve_integer_csv(
+ layout: str, combine: bool, transpose: bool
+):
+ """Blank totals must not round integer leaves or change their CSV spelling."""
+ large = 2**53 + 1
+ frame = pd.DataFrame(
+ {
+ "nation": ["US", "UK"],
+ "gender": ["boy", "boy"],
+ "SUM(a)": [large, 2],
+ "SUM(b)": [3, 4],
+ }
+ )
+ result = pivot_table_v2(
+ frame,
+ {
+ "groupbyRows": ["nation"],
+ "groupbyColumns": ["gender"],
+ "metrics": ["SUM(a)", "SUM(b)"],
+ "metricsLayout": layout,
+ "combineMetric": combine,
+ "transposePivot": transpose,
+ "rowTotals": True,
+ "colTotals": True,
+ },
+ apply_number_format=False,
+ )
+ csv = result.to_csv()
+ assert str(large) in csv
+ assert str(large - 1) not in csv
+ assert ".0" not in csv
+
+
+@pytest.mark.parametrize("mode", [None, "percent_row", "percent_col", "percent_total"])
+@pytest.mark.parametrize("transpose", [False, True])
+@pytest.mark.parametrize("single_metric", [False, True])
+@pytest.mark.parametrize("layout", ["COLUMNS", "ROWS"])
+def test_combined_metric_subtotals(
+ mode: str | None, transpose: bool, single_metric: bool, layout: str
+):
+ frame = show_values_as_df()
+ frame["MAX(num)"] = [1, 3, 6, 10]
+ metrics = ["SUM(num)"] if single_metric else ["SUM(num)", "MAX(num)"]
+ result = pivot_table_v2(
+ frame,
+ {
+ "groupbyRows": ["nation"],
+ "groupbyColumns": ["gender"],
+ "metrics": metrics,
+ "metricsLayout": layout,
+ "combineMetric": True,
+ "transposePivot": transpose,
+ "rowTotals": True,
+ "colTotals": True,
+ "showValuesAs": mode,
+ },
+ apply_number_format=False,
+ )
+ # Transpose swaps the dimension axes before constructing the pivot.
+ metrics_on_rows = layout == "ROWS"
+ if metrics_on_rows:
+ result = result.T
+ groups = ["US", "UK"] if transpose != metrics_on_rows else ["boy", "girl"]
+ for group in groups:
+ subtotal = result.loc[:, (group, "Subtotal")]
+ assert subtotal.notna().all() if single_metric else subtotal.isna().all()
+
+
+@pytest.mark.parametrize("metrics", [set(), {"SUM(num)"}, {"SUM(num)", "MAX(num)"}])
+def test_collapsed_metric_preserves_shared_metric_set(metrics: set[str]):
+ original = metrics.copy()
+ expected = "SUM(num)" if len(metrics) == 1 else None
+ assert _collapsed_metric(metrics) == expected
+ assert _collapsed_metric(metrics) == expected
+ assert metrics == original
+
+
+@pytest.mark.parametrize("combine", [False, True])
+@pytest.mark.parametrize("transpose", [False, True])
+def test_pivot_mixed_totals_preserve_integer_xlsx(combine: bool, transpose: bool):
+ """The full XLSX path keeps large integers as exact text and small ones numeric."""
+ from openpyxl import load_workbook
+
+ large = 2**53 + 1
+ source = pd.DataFrame(
+ {
+ "nation": ["US", "UK"],
+ "gender": ["boy", "boy"],
+ "SUM(a)": [str(large), "2"],
+ "SUM(b)": [3, 4],
+ }
+ )
+ result = apply_client_processing(
+ {
+ "queries": [
+ {
+ "result_format": ChartDataResultFormat.XLSX,
+ "data": excel.df_to_excel(source, index=False),
+ }
+ ]
+ },
+ {
+ "viz_type": "pivot_table_v2",
+ "groupbyRows": ["nation"],
+ "groupbyColumns": ["gender"],
+ "metrics": ["SUM(a)", "SUM(b)"],
+ "metricsLayout": "ROWS",
+ "combineMetric": combine,
+ "transposePivot": transpose,
+ "rowTotals": True,
+ "colTotals": True,
+ },
+ )
+ sheet = load_workbook(BytesIO(result["queries"][0]["data"])).active
+ cells = [cell for row in sheet for cell in row]
+ assert any(cell.value == str(large) and cell.data_type == "s" for cell in cells)
+ assert any(cell.value == 3 and cell.data_type == "n" for cell in cells)
+ assert not any(str(cell.value).startswith(str(large - 1)) for cell in cells)
diff --git a/tests/unit_tests/mcp_service/native_tool_inventory.json b/tests/unit_tests/mcp_service/native_tool_inventory.json
index 5c65bcf4c46..aa6a827e947 100644
--- a/tests/unit_tests/mcp_service/native_tool_inventory.json
+++ b/tests/unit_tests/mcp_service/native_tool_inventory.json
@@ -234,11 +234,11 @@
"compact_description_chars": 250,
"description_chars": 3577,
"entry_bytes": {
- "structured": 25915,
+ "structured": 26411,
"text_only": 6037
},
"input_schema_bytes": 2037,
- "output_schema_bytes": 19862
+ "output_schema_bytes": 20358
},
"generate_dashboard": {
"annotations": {
@@ -343,14 +343,14 @@
"openWorldHint": false,
"readOnlyHint": true
},
- "compact_description_chars": 241,
- "description_chars": 434,
+ "compact_description_chars": 240,
+ "description_chars": 553,
"entry_bytes": {
- "structured": 8610,
- "text_only": 3359
+ "structured": 9342,
+ "text_only": 3595
},
- "input_schema_bytes": 2679,
- "output_schema_bytes": 5235
+ "input_schema_bytes": 2793,
+ "output_schema_bytes": 5731
},
"get_chart_sql": {
"annotations": {
@@ -1194,11 +1194,11 @@
"compact_description_chars": 45,
"description_chars": 2416,
"entry_bytes": {
- "structured": 26567,
+ "structured": 27063,
"text_only": 6689
},
"input_schema_bytes": 3913,
- "output_schema_bytes": 19862
+ "output_schema_bytes": 20358
},
"update_chart_preview": {
"annotations": {
@@ -1267,16 +1267,16 @@
},
"totals": {
"catalog_bytes": {
- "structured": 522735,
- "text_only": 214220
+ "structured": 524459,
+ "text_only": 214456
},
"compact_catalog_bytes": {
- "structured": 470159,
- "text_only": 161644
+ "structured": 471762,
+ "text_only": 161759
},
"largest_entry": {
"structured": {
- "bytes": 26567,
+ "bytes": 27063,
"name": "update_chart"
},
"text_only": {
diff --git a/tests/unit_tests/utils/excel_tests.py b/tests/unit_tests/utils/excel_tests.py
index 560c62da3a7..719d07dbd68 100644
--- a/tests/unit_tests/utils/excel_tests.py
+++ b/tests/unit_tests/utils/excel_tests.py
@@ -297,3 +297,16 @@ def test_column_data_types_with_large_numeric_values():
"1100108628127863",
"18014398509481984",
]
+
+
+def test_numeric_column_with_blanks_preserves_large_integers() -> None:
+ """Blank cells must not round integers before Excel's text conversion."""
+ large = 2**53 + 1
+ df = pd.DataFrame({"value": pd.Series([large, None, 3], dtype=object)})
+ apply_column_types(df, [GenericDataType.NUMERIC])
+ sheet = load_workbook(io.BytesIO(df_to_excel(df, index=False))).active
+ assert sheet["A2"].value == str(large)
+ assert sheet["A2"].data_type == "s"
+ assert sheet["A3"].value is None
+ assert sheet["A4"].value == 3
+ assert sheet["A4"].data_type == "n"