You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/09/16 23:26:16 UTC

(superset) branch master updated: fix(chart): include Decimal metrics in contribution totals (#43222)

This is an automated email from the ASF dual-hosted git repository.

rusackas 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 baccb68d3b4 fix(chart): include Decimal metrics in contribution totals (#43222)
baccb68d3b4 is described below

commit baccb68d3b484532bc7962d9ed30c436352f36f8
Author: Sepuri Sai Krishna <sa...@gmail.com>
AuthorDate: Thu Sep 17 04:56:08 2026 +0530

    fix(chart): include Decimal metrics in contribution totals (#43222)
---
 superset/common/query_context_processor.py         |  22 +++-
 superset/tasks/async_queries.py                    |   3 +-
 .../common/test_query_context_processor.py         | 117 +++++++++++++++++++++
 tests/unit_tests/tasks/test_async_queries.py       |  43 ++++++++
 4 files changed, 181 insertions(+), 4 deletions(-)

diff --git a/superset/common/query_context_processor.py b/superset/common/query_context_processor.py
index 2bff5f9b1ef..2c27fb9fb06 100644
--- a/superset/common/query_context_processor.py
+++ b/superset/common/query_context_processor.py
@@ -26,6 +26,7 @@ import pandas as pd
 import pyarrow as pa
 from flask import current_app
 from flask_babel import gettext as _
+from pandas.api.types import infer_dtype
 
 from superset.common.chart_data import ChartDataResultFormat
 from superset.common.chart_data_timing import (
@@ -113,6 +114,23 @@ def normalize_contribution_totals(
     return queries_needing_totals, totals_idx
 
 
+def is_summable(series: pd.Series) -> bool:
+    """
+    Whether a column holds values the contribution totals can be summed over.
+
+    A dtype-kind test alone is not enough. `decimal.Decimal` metrics -- how
+    drivers such as psycopg2 hand back NUMERIC/DECIMAL columns -- are stored
+    with an object dtype, so they fall outside the numeric kinds even though
+    they sum and divide perfectly well. Omitting them leaves the totals
+    dictionary without an entry for the metric, and `contribution()` then
+    reads back `None` and writes a zero contribution instead of the real
+    percentage.
+    """
+    if series.dtype.kind in "biufc":
+        return True
+    return infer_dtype(series, skipna=True) == "decimal"
+
+
 class QueryContextProcessor:
     """
     The query context contains the query object and additional fields necessary
@@ -602,9 +620,7 @@ class QueryContextProcessor:
         result = self._query_context.get_query_result(totals_query)
         df = result.df
 
-        totals = {
-            col: df[col].sum() for col in df.columns if df[col].dtype.kind in "biufc"
-        }
+        totals = {col: df[col].sum() for col in df.columns if is_summable(df[col])}
 
         for idx in queries_needing_totals:
             query = self._query_context.queries[idx]
diff --git a/superset/tasks/async_queries.py b/superset/tasks/async_queries.py
index f9eb65204ff..71436da5241 100644
--- a/superset/tasks/async_queries.py
+++ b/superset/tasks/async_queries.py
@@ -181,6 +181,7 @@ def _inject_contribution_totals(
     populated instead of re-running the totals query. ``contribution_totals`` is
     stripped from the cache key, so this affects only the result, not the key.
     """
+    from superset.common.query_context_processor import is_summable
     from superset.common.utils.query_cache_manager import QueryCacheManager
 
     cache = QueryCacheManager.get(key=totals_cache_key, region=CacheRegion.DATA)
@@ -195,7 +196,7 @@ def _inject_contribution_totals(
             f"Contribution totals not found in cache under {totals_cache_key}"
         )
     df = cache.df
-    totals = {col: df[col].sum() for col in df.columns if df[col].dtype.kind in "biufc"}
+    totals = {col: df[col].sum() for col in df.columns if is_summable(df[col])}
     for post_processing in query_obj.post_processing or []:
         if post_processing.get("operation") == "contribution":
             post_processing.setdefault("options", {})["contribution_totals"] = totals
diff --git a/tests/unit_tests/common/test_query_context_processor.py b/tests/unit_tests/common/test_query_context_processor.py
index 613e2faf72b..5dc21d12b85 100644
--- a/tests/unit_tests/common/test_query_context_processor.py
+++ b/tests/unit_tests/common/test_query_context_processor.py
@@ -2625,3 +2625,120 @@ def test_gauge_json_metric_label_ignores_verbose_name(
         )
         is None
     )
+
+
+def test_is_summable_accepts_decimal_columns():
+    """Decimal metrics must be summable for the contribution totals.
+
+    `decimal.Decimal` values -- how drivers such as psycopg2 hand back
+    NUMERIC/DECIMAL columns -- live in an object-dtype column, so the
+    `dtype.kind in "biufc"` test dropped them even though they sum and
+    divide fine. Columns holding anything else non-numeric must stay out.
+    """
+    from decimal import Decimal
+
+    from superset.common.query_context_processor import is_summable
+
+    assert is_summable(pd.Series([1.0, 2.0]))
+    assert is_summable(pd.Series([1, 2]))
+    assert is_summable(pd.Series([Decimal("1.5"), Decimal("2.5")]))
+    # a Decimal column that also carries nulls is still a Decimal column
+    assert is_summable(pd.Series([Decimal("1.5"), None]))
+
+    assert not is_summable(pd.Series(["a", "b"]))
+    assert not is_summable(pd.Series([{"a": 1}, {"b": 2}]))
+    assert not is_summable(pd.Series(pd.to_datetime(["2021-01-01", "2021-01-02"])))
+
+
+def test_ensure_totals_available_includes_decimal_metrics():
+    """A Decimal metric must reach `contribution_totals`.
+
+    When it is missing, `contribution()` looks the metric up, gets `None`
+    back and writes a zero contribution -- so the chart silently renders 0%
+    for every row of that metric rather than erroring.
+    """
+    from decimal import Decimal
+
+    from superset.common.query_object import QueryObject
+
+    mock_datasource = MagicMock()
+    mock_datasource.uid = "test_datasource"
+    mock_datasource.database.db_engine_spec.engine = "postgresql"
+    mock_datasource.cache_timeout = None
+    mock_datasource.changed_on = None
+
+    main_query = QueryObject(
+        datasource=mock_datasource,
+        columns=["brokerage"],
+        metrics=["decimal_metric", "float_metric"],
+        post_processing=[
+            {
+                "operation": "contribution",
+                "options": {"columns": ["decimal_metric", "float_metric"]},
+            }
+        ],
+    )
+    totals_query = QueryObject(
+        datasource=mock_datasource,
+        columns=[],
+        metrics=["decimal_metric", "float_metric"],
+        post_processing=[],
+    )
+
+    mock_query_context = MagicMock()
+    mock_query_context.queries = [main_query, totals_query]
+    mock_query_context.cache_values = {}
+    _wire_contribution_totals(mock_query_context)
+
+    mock_query_result = MagicMock()
+    mock_query_result.df = pd.DataFrame(
+        {
+            # what psycopg2 hands back for a NUMERIC column
+            "decimal_metric": [Decimal("40.0")],
+            "float_metric": [10.0],
+            # a non-numeric column must still be left out
+            "label": ["total"],
+        }
+    )
+
+    processor = QueryContextProcessor(mock_query_context)
+    processor._qc_datasource = mock_datasource
+
+    with patch.object(
+        mock_query_context, "get_query_result", return_value=mock_query_result
+    ):
+        processor.ensure_totals_available()
+
+    totals = main_query.post_processing[0]["options"]["contribution_totals"]
+    assert totals == {"decimal_metric": Decimal("40.0"), "float_metric": 10.0}
+    assert "label" not in totals
+
+
+def test_contribution_uses_decimal_totals_rather_than_zero():
+    """End to end: the totals a Decimal metric produces yield real percentages."""
+    from decimal import Decimal
+
+    from superset.utils.core import PostProcessingContributionOrientation
+    from superset.utils.pandas_postprocessing import contribution
+
+    df = pd.DataFrame({"decimal_metric": [Decimal("10.0"), Decimal("30.0")]})
+
+    # totals as built by `ensure_totals_available`
+    processed = contribution(
+        df,
+        orientation=PostProcessingContributionOrientation.COLUMN,
+        columns=["decimal_metric"],
+        rename_columns=["%decimal_metric"],
+        contribution_totals={"decimal_metric": Decimal("40.0")},
+    )
+    assert processed["%decimal_metric"].tolist() == [0.25, 0.75]
+
+    # the pre-fix behaviour: the metric absent from totals collapses to zero
+    collapsed = contribution(
+        df,
+        orientation=PostProcessingContributionOrientation.COLUMN,
+        columns=["decimal_metric"],
+        rename_columns=["%decimal_metric"],
+        contribution_totals={"unrelated_metric": Decimal("40.0")},
+    )
+    assert collapsed["%decimal_metric"].tolist() == [0, 0]
diff --git a/tests/unit_tests/tasks/test_async_queries.py b/tests/unit_tests/tasks/test_async_queries.py
index 9f75dd7072a..1641e7829ff 100644
--- a/tests/unit_tests/tasks/test_async_queries.py
+++ b/tests/unit_tests/tasks/test_async_queries.py
@@ -16,10 +16,12 @@
 # under the License.
 """Unit tests for the GTF chart-data fan-out orchestrator."""
 
+from decimal import Decimal
 from typing import TYPE_CHECKING
 from unittest import mock
 from uuid import uuid4
 
+import pandas as pd
 import pytest
 from pytest_mock import MockerFixture
 
@@ -484,3 +486,44 @@ def test_consumer_policy_routing_channels_are_the_consumers() -> None:
     policy.on_subscribe(task, principal="user:5", client_ref="A")
     policy.on_subscribe(task, principal="user:7", client_ref="B")
     assert policy.routing_channels(task) == ["user:5:A", "user:7:B"]
+
+
+def test_inject_contribution_totals_includes_decimal_metrics(
+    mocker: MockerFixture,
+) -> None:
+    """The cached totals must sum Decimal metrics, as the synchronous path does.
+
+    ``_inject_contribution_totals`` exists to reproduce what
+    ``ensure_totals_available`` computes, reading the prerequisite task's cached
+    dataframe instead of re-running the totals query. A driver that returns
+    NUMERIC as ``decimal.Decimal`` gives that dataframe an object-dtype column,
+    so a dtype-kind test would drop the metric here and leave ``contribution()``
+    writing a zero for every row -- the two paths would disagree on the same
+    data.
+    """
+    from superset.tasks.async_queries import _inject_contribution_totals
+
+    cache = mocker.MagicMock()
+    cache.is_loaded = True
+    cache.df = pd.DataFrame(
+        {
+            "decimal_metric": [Decimal("40.0")],
+            "float_metric": [10.0],
+            "label": ["total"],
+        }
+    )
+    mocker.patch(
+        "superset.common.utils.query_cache_manager.QueryCacheManager.get",
+        return_value=cache,
+    )
+
+    query_obj = mocker.MagicMock()
+    query_obj.post_processing = [
+        {"operation": "contribution", "options": {"columns": ["decimal_metric"]}}
+    ]
+
+    _inject_contribution_totals(query_obj, "totals-cache-key")
+
+    totals = query_obj.post_processing[0]["options"]["contribution_totals"]
+    assert totals == {"decimal_metric": Decimal("40.0"), "float_metric": 10.0}
+    assert "label" not in totals