codeant-ai-for-open-source[bot] commented on code in PR #41028:
URL: https://github.com/apache/superset/pull/41028#discussion_r3505505113


##########
superset/utils/number_format.py:
##########
@@ -0,0 +1,333 @@
+# 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.
+"""
+Server-side port of the d3-format based number and currency formatters used by
+the Table and Pivot Table chart plugins.
+
+Report notifications that embed a chart as text build the table in Python and
+have no access to the frontend formatters, so chart number/currency format
+configuration has to be reproduced here to render the same values an end user
+sees in the browser.
+
+Only d3-format specifiers (and the ``SMART_NUMBER`` pseudo-formats) are ported.
+Non-d3 presets such as ``DURATION``, ``DURATION_SUB`` and the ``MEMORY_*``
+formatters are not supported: they do not parse as a d3 specifier and fall back
+to the raw value, so a column using one of those renders unformatted in 
reports.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from decimal import Decimal, ROUND_HALF_UP
+from typing import Any
+
+from babel.numbers import get_currency_symbol
+
+SMART_NUMBER = "SMART_NUMBER"
+SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED"
+AUTO_CURRENCY = "AUTO"
+
+LOCALE = "en_US"
+
+# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format.
+SI_PREFIXES = {
+    -8: "y",
+    -7: "z",
+    -6: "a",
+    -5: "f",
+    -4: "p",
+    -3: "n",
+    -2: "µ",
+    -1: "m",
+    0: "",
+    1: "k",
+    2: "M",
+    3: "G",
+    4: "T",
+    5: "P",
+    6: "E",
+    7: "Z",
+    8: "Y",
+}
+
+# d3-format specifier grammar:
+# [[fill]align][sign][symbol][0][width][,][.precision][~][type]
+D3_FORMAT_RE = re.compile(
+    r"^(?:(.)?([<>=^]))?([+\-( 
])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$",
+    re.IGNORECASE,
+)
+
+
+def format_number_with_config(
+    d3_format: str | None,
+    currency: dict[str, Any] | None,
+    value: Any,
+) -> Any:
+    """
+    Format ``value`` using a d3-format string and optional currency config.
+
+    :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or 
``SMART_NUMBER``
+    :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": 
"prefix"|"suffix"}``
+    :param value: the raw value to format
+    :return: the formatted string, or the value unchanged when it is not a
+        number that can be formatted
+    """
+    if value is None:
+        return ""
+    if isinstance(value, bool) or not isinstance(value, (int, float)):
+        return value
+    if math.isnan(value) or math.isinf(value):
+        return ""
+
+    try:
+        if currency and currency.get("symbol"):
+            # the frontend strips the currency symbol from the d3 format and
+            # falls back to SMART_NUMBER when no explicit format is set
+            number_format = (d3_format or SMART_NUMBER).replace("$", "")
+            formatted = format_numeric(number_format, value)
+            if currency["symbol"] == AUTO_CURRENCY:
+                return formatted
+            return apply_currency(formatted, currency)
+        if not d3_format:
+            return raw_string(value)
+        return format_numeric(d3_format, value)
+    except Exception:  # pylint: disable=broad-except  # noqa: BLE001
+        # never let an unexpected value break a whole report table
+        return raw_string(value)
+
+
+def format_numeric(d3_format: str, value: float) -> str:
+    """
+    Format ``value`` according to a d3 number format.
+
+    Delegates to the smart-number formatter for the ``SMART_NUMBER`` and
+    ``SMART_NUMBER_SIGNED`` pseudo-formats, and to the d3 specifier parser for
+    every other format string.
+    """
+    if d3_format in (SMART_NUMBER, SMART_NUMBER_SIGNED):
+        return format_smart_number(value, signed=d3_format == 
SMART_NUMBER_SIGNED)
+    return format_d3(d3_format, value)
+
+
+def format_d3(d3_format: str, value: float) -> str:
+    """
+    Format ``value`` with a d3-format specifier.
+
+    Supports the subset of the specifier grammar the Table/Pivot plugins emit:
+    the ``+ - ( space`` sign modes, the ``$`` currency prefix, the ``,`` group
+    separator, ``.precision``, the ``~`` trim flag, and the ``s`` (SI), ``r``
+    (significant), ``d`` (integer), ``f``/``e``/``g``/``%`` numeric types.
+    Returns the formatted string and raises ``ValueError`` for an unparseable
+    specifier.
+    """
+    match = D3_FORMAT_RE.match(d3_format)
+    if not match:
+        raise ValueError(d3_format)
+
+    sign_mode = match.group(3) or "-"
+    currency_symbol = match.group(4) == "$"
+    comma = "," if match.group(7) else ""
+    precision = int(match.group(8)) if match.group(8) is not None else None
+    trim = bool(match.group(9))
+    type_ = (match.group(10) or "").lower()

Review Comment:
   **Suggestion:** The parser reads full d3 specifier grammar, but 
width/padding/alignment flags are ignored during rendering, so valid 
user-entered d3 formats (for example zero-padded width formats) will not match 
frontend output. Either implement these parsed flags or reject unsupported 
specifiers explicitly to avoid silent mis-formatting. [incomplete 
implementation]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Width-padded d3 formats lose padding in reports.
   - ⚠️ Aligned numeric formats differ between Explore and alerts.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. In `superset/utils/number_format.py`, inspect the d3 specifier regex and 
parser:
   `D3_FORMAT_RE` at lines 29–33 accepts the full d3-format grammar, including 
optional fill,
   alignment, zero-padding, and width
   (`[[fill]align][sign][symbol][0][width][,][.precision][~][type]` as per the 
comment at
   lines 29–30).
   
   2. Still in `format_d3` (lines 29–78 of the same file), after matching the 
specifier, the
   code extracts only `sign_mode` (group 3), `currency_symbol` (group 4), 
`comma` (group 7),
   `precision` (group 8), `trim` (group 9), and `type_` (group 10) at lines 
44–49; it
   completely ignores the parsed fill character (group 1), alignment (group 2), 
the
   zero-padding flag (group 5), and field width (group 6).
   
   3. Consider a user-configured d3 format such as `"08.2f"` or `"^10.3f"` 
entered in the
   Table or Pivot chart number format control; this string is stored in 
`form_data` as
   `d3NumberFormat`/`valueFormat`, then passed from 
`superset/charts/client_processing.py`
   via `format_column` (lines 62–69) into `format_number_with_config`, which 
calls
   `format_d3` when `d3_format` is not SMART or None.
   
   4. When `format_d3` formats a value with such a specifier, the regex 
successfully matches
   and `type_` is `"f"` with `precision` set, but since width, zero-padding, 
and alignment
   are ignored, the function ultimately formats the magnitude using 
`format(magnitude,
   f"{comma}.{precision}f")` (lines 63–69) producing a plain fixed-point number 
without the
   requested field width or padding. On the frontend, d3-format honours these 
width and
   alignment flags, so the Explore view shows padded/aligned numbers while the 
server-side
   path used for Alerts/Reports silently drops those aspects, causing a 
formatting mismatch
   for users who rely on these d3 options.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cb5b690aa4b44481b8291577ec29c31a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=cb5b690aa4b44481b8291577ec29c31a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/utils/number_format.py
   **Line:** 142:147
   **Comment:**
        *Incomplete Implementation: The parser reads full d3 specifier grammar, 
but width/padding/alignment flags are ignored during rendering, so valid 
user-entered d3 formats (for example zero-padded width formats) will not match 
frontend output. Either implement these parsed flags or reject unsupported 
specifiers explicitly to avoid silent mis-formatting.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=7e2f638ae9fb784c2212d081b9894c58f31240f2de402cf2514fb7500100e4b7&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=7e2f638ae9fb784c2212d081b9894c58f31240f2de402cf2514fb7500100e4b7&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to