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


##########
superset/charts/data/dashboard_filter_context.py:
##########
@@ -0,0 +1,297 @@
+# 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.
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any
+
+from flask_babel import gettext as _
+
+from superset import db, security_manager
+from superset.constants import (
+    EXTRA_FORM_DATA_APPEND_KEYS,
+    EXTRA_FORM_DATA_OVERRIDE_EXTRA_KEYS,
+    EXTRA_FORM_DATA_OVERRIDE_REGULAR_MAPPINGS,
+)
+from superset.models.dashboard import Dashboard
+from superset.utils import json
+
+logger = logging.getLogger(__name__)
+
+CHART_TYPE = "CHART"
+
+
+class DashboardFilterStatus(str, Enum):
+    APPLIED = "applied"
+    NOT_APPLIED = "not_applied"
+    NOT_APPLIED_USES_DEFAULT_TO_FIRST_ITEM_PREQUERY = (
+        "not_applied_uses_default_to_first_item_prequery"
+    )
+
+
+@dataclass
+class DashboardFilterInfo:
+    id: str
+    name: str
+    status: DashboardFilterStatus
+    column: str | None = None
+
+
+@dataclass
+class DashboardFilterContext:
+    extra_form_data: dict[str, Any] = field(default_factory=dict)
+    filters: list[DashboardFilterInfo] = field(default_factory=list)
+
+    def to_dict(self) -> dict[str, Any]:
+        return {
+            "filters": [
+                {
+                    "id": f.id,
+                    "name": f.name,
+                    "status": f.status.value,
+                    **({"column": f.column} if f.column else {}),
+                }
+                for f in self.filters
+            ],
+        }
+
+
+def _is_filter_in_scope_for_chart(
+    filter_config: dict[str, Any],
+    chart_id: int,
+    position_json: dict[str, Any],
+) -> bool:
+    """
+    Determines whether a native filter applies to a given chart. When
+    chartsInScope is present on the filter config, uses that directly.
+    Otherwise falls back to scope.rootPath and scope.excluded with
+    the dashboard layout.
+    """
+    if (charts_in_scope := filter_config.get("chartsInScope")) is not None:
+        return chart_id in charts_in_scope
+
+    scope = filter_config.get("scope", {})
+    root_path: list[str] = scope.get("rootPath", [])
+    excluded: list[int] = scope.get("excluded", [])
+
+    if chart_id in excluded:
+        return False
+
+    chart_layout_item = _find_chart_layout_item(chart_id, position_json)
+    if not chart_layout_item:
+        return False
+
+    parents: list[str] = chart_layout_item.get("parents", [])
+    return any(parent in root_path for parent in parents)
+
+
+def _find_chart_layout_item(
+    chart_id: int,
+    position_json: dict[str, Any],
+) -> dict[str, Any] | None:
+    """Find the layout item for a chart in the dashboard position JSON."""
+    for item in position_json.values():
+        if not isinstance(item, dict):
+            continue
+        if (
+            item.get("type") == CHART_TYPE
+            and item.get("meta", {}).get("chartId") == chart_id
+        ):
+            return item
+    return None
+
+
+def _merge_extra_form_data(
+    base: dict[str, Any],
+    new: dict[str, Any],
+) -> dict[str, Any]:
+    """
+    Merge two extra_form_data dicts, appending list-type keys (like filters,
+    adhoc_filters), merging dict-type keys (like custom_form_data), and 
overriding
+    scalar keys (like granularity_sqla, time_range).
+    """
+    append_keys = EXTRA_FORM_DATA_APPEND_KEYS - {"custom_form_data"}
+    override_keys = (
+        set(EXTRA_FORM_DATA_OVERRIDE_REGULAR_MAPPINGS.keys())
+        | EXTRA_FORM_DATA_OVERRIDE_EXTRA_KEYS
+    )
+
+    merged: dict[str, Any] = {}
+
+    for key in append_keys:
+        base_val = base.get(key, [])
+        new_val = new.get(key, [])
+        combined = list(base_val) + list(new_val)
+        if combined:
+            merged[key] = combined
+
+    # Merge custom_form_data as dicts so multiple filters' contributions 
combine
+    base_custom = base.get("custom_form_data") or {}
+    new_custom = new.get("custom_form_data") or {}
+    if isinstance(base_custom, dict) and isinstance(new_custom, dict):
+        merged_custom = {**base_custom, **new_custom}

Review Comment:
   **Suggestion:** The `custom_form_data` merge is currently shallow, so when 
two in-scope filters write the same key (for example both provide `groupby` 
lists), the later filter silently overwrites the earlier one. This drops part 
of the dashboard filter context and can produce incomplete query behavior. 
Merge overlapping list values per key instead of replacing them wholesale. 
[logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Chart data GET can drop earlier custom groupby defaults.
   - ⚠️ Multiple in-scope customization defaults merge incompletely.
   - ⚠️ Returned applied status may not match effective query context.
   ```
   </details>
   
   ```suggestion
           merged_custom = dict(base_custom)
           for key, value in new_custom.items():
               if (
                   key in merged_custom
                   and isinstance(merged_custom[key], list)
                   and isinstance(value, list)
               ):
                   merged_custom[key] = merged_custom[key] + value
               else:
                   merged_custom[key] = value
   ```
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Call `GET /api/v1/chart/<pk>/data?filters_dashboard_id=<id>`; this path 
always invokes
   `get_dashboard_filter_context(...)` from 
`superset/charts/data/api.py:198-201` when
   `filters_dashboard_id` is present.
   
   2. Use a dashboard whose native filter defaults include
   `extraFormData.custom_form_data.groupby` from chart customization filters 
(same structure
   emitted in frontend at
   
`superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.tsx:387-390`
   and
   
`superset-frontend/src/chartCustomizations/components/DynamicGroupBy/DynamicGroupByPlugin.tsx:61-64`).
   
   3. Ensure two in-scope filters both provide `custom_form_data` with 
overlapping key
   `groupby` (e.g., first `["country"]`, second `["state"]`); 
`_merge_extra_form_data` in
   `superset/charts/data/dashboard_filter_context.py:147-150` does 
`{**base_custom,
   **new_custom}`, so the second list replaces the first.
   
   4. The merged context is attached to query payload via 
`query["extra_form_data"] = efd` in
   `superset/charts/data/api.py:83`, so the request executes with incomplete 
customization
   context (earlier `groupby` contribution lost).
   ```
   </details>
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/charts/data/dashboard_filter_context.py
   **Line:** 148:148
   **Comment:**
        *Logic Error: The `custom_form_data` merge is currently shallow, so 
when two in-scope filters write the same key (for example both provide 
`groupby` lists), the later filter silently overwrites the earlier one. This 
drops part of the dashboard filter context and can produce incomplete query 
behavior. Merge overlapping list values per key instead of replacing them 
wholesale.
   
   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.
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38638&comment_hash=889e65671662c1b724900d53f3a4362585f43af66f85c899f1137444c52284a9&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38638&comment_hash=889e65671662c1b724900d53f3a4362585f43af66f85c899f1137444c52284a9&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