codeant-ai-for-open-source[bot] commented on code in PR #38638: URL: https://github.com/apache/superset/pull/38638#discussion_r2955588876
########## superset/charts/data/dashboard_filter_context.py: ########## @@ -0,0 +1,288 @@ +# 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) and overriding scalar keys (like granularity_sqla, time_range). + """ + append_keys = EXTRA_FORM_DATA_APPEND_KEYS + override_keys = ( + set(EXTRA_FORM_DATA_OVERRIDE_REGULAR_MAPPINGS.keys()) + | EXTRA_FORM_DATA_OVERRIDE_EXTRA_KEYS Review Comment: **Suggestion:** `EXTRA_FORM_DATA_APPEND_KEYS` includes `custom_form_data`, which is a dict-type payload, but this merge function appends keys by casting values with `list(...)`. That converts dicts into a list of their keys and corrupts `extra_form_data`, so downstream query building receives the wrong type. Exclude `custom_form_data` from append merging and treat it as an override key. [type error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ GET chart data misbuilds custom_form_data payload. - ⚠️ GroupBy native filter defaults lose object values. ``` </details> ```suggestion 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 | {"custom_form_data"} ``` <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Configure a native GroupBy filter with default mask data where `extraFormData.custom_form_data` is an object (frontend writes this shape at `superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterControls/GroupByFilterCard.tsx:387`). 2. Call `GET /api/v1/chart/<id>/data?filters_dashboard_id=<dashboard_id>`; this endpoint invokes `get_dashboard_filter_context(...)` at `superset/charts/data/api.py:198-201`. 3. In `get_dashboard_filter_context` (`superset/charts/data/dashboard_filter_context.py:226-277`), applied filter defaults are merged via `_merge_extra_form_data(...)` (`:274-277`), which iterates append keys (`:136`) including `custom_form_data` from `EXTRA_FORM_DATA_APPEND_KEYS` (`superset/constants.py:179-186`). 4. `_merge_extra_form_data` executes `list(base_val) + list(new_val)` (`dashboard_filter_context.py:139`); for dict-valued `custom_form_data`, this converts to key lists, corrupting payload type before attaching to query context (`superset/charts/data/api.py:63`). ``` </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:** 128:131 **Comment:** *Type Error: `EXTRA_FORM_DATA_APPEND_KEYS` includes `custom_form_data`, which is a dict-type payload, but this merge function appends keys by casting values with `list(...)`. That converts dicts into a list of their keys and corrupts `extra_form_data`, so downstream query building receives the wrong type. Exclude `custom_form_data` from append merging and treat it as an override key. 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=6cf5f16c56c842259b95c2825b0f6dc0fed833cce947a19fd60dfc70242b1fad&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F38638&comment_hash=6cf5f16c56c842259b95c2825b0f6dc0fed833cce947a19fd60dfc70242b1fad&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]
