You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "FrancescoCastaldi (via GitHub)" <gi...@apache.org> on 2026/10/06 22:35:04 UTC
[PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
FrancescoCastaldi opened a new pull request, #45038:
URL: https://github.com/apache/superset/pull/45038
### SUMMARY
Fixes #44983.
When saving a dashboard as a copy with duplicated charts (duplicate_slices=True), chartsInScope and scope.excluded within native filters metadata continued to reference the old chart slice IDs, breaking filter scope bindings on the new dashboard.
This change:
1. Implements _remap_filter_scopes and _remap_filter_scope in DashboardDAO (superset/daos/dashboard.py).
2. Remaps chart IDs in chartsInScope and scope.excluded across native_filter_configuration, global_chart_configuration, and chart_configuration using old_to_new_slice_ids.
3. Handles dividers and non-dictionary elements gracefully without raising errors.
### TESTING INSTRUCTIONS
Run the dashboard DAO unit tests:
pytest tests/unit_tests/dao/dashboard_test.py
All tests pass, confirming correct slice ID remapping for single and multi-filter dashboards.
### ADDITIONAL INFORMATION
- [x] Has associated issue: fixes #44983
- [x] Changes UI: No
- [x] Requires DB Migration: No
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4210827556
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
Review Comment:
Agreed—a filter scoped to a single layer keeps `selectedLayers` entries like `chart-<old_id>-layer-0`, so on the copied dashboard the layer scope is looked up under the original chart ID and the cloned chart gets no layer-specific scope, so the filter can hit every layer of the copy. Should the chart-ID part of each `selectedLayers` entry be remapped (keeping the layer index) alongside `excluded` and `chartsInScope`?
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
+
+ if isinstance(container.get("chartsInScope"), list):
+ remapped_in_scope: list[int] = []
+ for cid in container["chartsInScope"]:
+ try:
+ int_id = int(cid)
+ remapped_in_scope.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_in_scope.append(cid)
+ container["chartsInScope"] = remapped_in_scope
+
+ @classmethod
+ def _remap_filter_scopes(
+ cls,
+ metadata: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap filter scopes and cross-filter references in dashboard metadata.
+
+ Mutates metadata in-place to redirect slice ID references across:
+ 1. native_filter_configuration: list of native filter definitions.
+ 2. global_chart_configuration: dashboard-wide cross-filter scoping.
+ 3. chart_configuration: per-chart cross-filter scopes, keys, and chart IDs.
+
+ This ensures that after duplicating dashboard charts, all filter
+ scopes remain bound to the new chart copies instead of the originals.
+
+ :param metadata: Deserialized dashboard json_metadata dictionary.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(metadata, dict) or not old_to_new_slice_ids:
+ return
+
+ if isinstance(metadata.get("native_filter_configuration"), list):
+ for native_filter in metadata["native_filter_configuration"]:
+ cls._remap_filter_scope(native_filter, old_to_new_slice_ids)
Review Comment:
Agreed—`chart_customization_config` uses the same `scope.excluded`/`chartsInScope` shape and is skipped by `_remap_filter_scopes`. A Dynamic Group By control that excludes chart B still lists B's original ID after Save As, so scope recomputation includes the copied B and the control changes it unexpectedly. Should the customization entries go through `_remap_filter_scope` as well?
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4217841317
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
Review Comment:
✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `d7e799a`.
Added `_remap_selected_layers`, which extracts chart IDs from `selectedLayers` keys, maps them to the duplicated chart IDs, and preserves each key’s suffix.
<sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
<!-- codeant-auto-resolve-reply -->
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
+
+ if isinstance(container.get("chartsInScope"), list):
+ remapped_in_scope: list[int] = []
+ for cid in container["chartsInScope"]:
+ try:
+ int_id = int(cid)
+ remapped_in_scope.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_in_scope.append(cid)
+ container["chartsInScope"] = remapped_in_scope
+
+ @classmethod
+ def _remap_filter_scopes(
+ cls,
+ metadata: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap filter scopes and cross-filter references in dashboard metadata.
+
+ Mutates metadata in-place to redirect slice ID references across:
+ 1. native_filter_configuration: list of native filter definitions.
+ 2. global_chart_configuration: dashboard-wide cross-filter scoping.
+ 3. chart_configuration: per-chart cross-filter scopes, keys, and chart IDs.
+
+ This ensures that after duplicating dashboard charts, all filter
+ scopes remain bound to the new chart copies instead of the originals.
+
+ :param metadata: Deserialized dashboard json_metadata dictionary.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(metadata, dict) or not old_to_new_slice_ids:
+ return
+
+ if isinstance(metadata.get("native_filter_configuration"), list):
+ for native_filter in metadata["native_filter_configuration"]:
+ cls._remap_filter_scope(native_filter, old_to_new_slice_ids)
Review Comment:
✅ **CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved** as of `d7e799a`.
The metadata traversal now applies `_remap_filter_scope` to entries in both `native_filter_configuration` and `chart_customization_config`, remapping their exclusions, selected layers, and chart-scope references.
<sub>If that's not right, unresolve this thread and CodeAnt will leave it open.</sub>
<!-- codeant-auto-resolve-reply -->
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6180688342
### Rebase & Verification Update
The PR branch has been rebased cleanly onto latest `master` (`upstream/master`), reconciling with recent changes in `superset/daos/dashboard.py` and `tests/unit_tests/dao/dashboard_test.py`:
- **Mergeable Status**: `MERGEABLE` (zero conflicts).
- **Evidence Gate**:
- `pytest tests/unit_tests/dao/dashboard_test.py`: 62 passed in 4.23s (100% PASS).
- `ruff check`: All checks passed.
- `ruff format`: Formatted cleanly to 88 columns.
The PR is up to date and ready for review.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6114720813
Hi @sadpandajoe @rusackas,
Pushed commit `0786da887f` adding `test_set_dash_metadata_does_not_double_remap_overlapping_ids` in `tests/unit_tests/dao/dashboard_test.py`.
The test feeds overlapping mapping `{1: 2, 2: 3}` through `DashboardDAO.set_dash_metadata` with `chartsInScope=[1, 2]`, `excluded=[1]`, and `selectedLayers=["chart-1-layer-0"]`. It asserts `[2, 3]`, `[2]`, and `["chart-2-layer-0"]`, verifying that single-pass remapping holds and preventing chained remapping (1 -> 2 -> 3).
All 20 unit tests in `tests/unit_tests/dao/dashboard_test.py` pass cleanly. Ready for final review and merge.
@coderabbitai review
@bito-code-review
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6132994098
Thanks for the follow-up review @sadpandajoe! I have pushed commit `d07e3bbbed` addressing both comments:
1. **Legacy `chart_customization_config` top-level `chartId` remapping**: `DashboardDAO._remap_filter_scope` now remaps top-level `chartId` entries (guarded with `not isinstance(..., bool)`) alongside `scope` and `chartsInScope`, and unit tests now cover legacy `chart_customization_config` entries in both `copy_dashboard` and `set_dash_metadata`.
2. **Pre-commit / Ruff formatting**: Restored the two-blank-line separation before `test_set_dash_metadata_does_not_double_remap_overlapping_ids`, normalized the trailing newline, and verified `ruff check` and `ruff format` pass cleanly on both touched files.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6058329378
Hi @sadpandajoe,
Addressed both scope remapping gaps in commits `d7e799a54f` and `2813150228`:
1. `scope.selectedLayers` remapping:
Updated `_remap_filter_scope` in `superset/daos/dashboard.py` to inspect `scope.selectedLayers`. Handled both standard frontend list format (`string[]`) and dictionary configurations. Keys matching `chart-<old_id>-layer-<idx>` have their chart ID segment remapped using `old_to_new_slice_ids` while preserving the layer suffix. Unmapped or unrecognized keys remain untouched.
2. `chart_customization_config` remapping:
In `_remap_filter_scopes`, `metadata["chart_customization_config"]` entries are now passed through `_remap_filter_scope` alongside native filter configurations and global cross-filter scopes, ensuring chart exclusions and target references point to the duplicated chart copies. Added divider detection for `CHART_CUSTOMIZATION_DIVIDER`.
3. Single-pass remapping:
Consolidated scope remapping strictly through `set_dash_metadata` to prevent double remapping on overlapping chart IDs.
Added regression unit tests in `tests/unit_tests/dao/dashboard_test.py` covering `selectedLayers` list and dict remapping, helper edge cases, and `chart_customization_config` scope remapping during dashboard duplication. All 19 unit tests and Astral Ruff pass cleanly.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6026944205
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/45038?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `13.46154%` with `45 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 66.24%. Comparing base ([`a5ffac5`](https://app.codecov.io/gh/apache/superset/commit/a5ffac58f44527607a7937c01b4b21eb989ebf49?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`0556fb9`](https://app.codecov.io/gh/apache/superset/commit/0556fb97963a3c1ce3393e04c0233ecd5040a022?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 10 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/45038?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [superset/daos/dashboard.py](https://app.codecov.io/gh/apache/superset/pull/45038?src=pr&el=tree&filepath=superset%2Fdaos%2Fdashboard.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGFvcy9kYXNoYm9hcmQucHk=) | 13.46% | [40 Missing and 5 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/45038?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
> :exclamation: There is a different number of reports uploaded between BASE (a5ffac5) and HEAD (0556fb9). Click for more details.
>
> <details><summary>HEAD has 5 uploads less than BASE</summary>
>
>| Flag | BASE (a5ffac5) | HEAD (0556fb9) |
>|------|------|------|
>|python|7|3|
>|postgres|2|1|
></details>
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #45038 +/- ##
===========================================
- Coverage 82.47% 66.24% -16.24%
===========================================
Files 3002 3004 +2
Lines 186172 186565 +393
Branches 43128 43208 +80
===========================================
- Hits 153550 123592 -29958
- Misses 29867 60277 +30410
+ Partials 2755 2696 -59
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `36.24% <7.69%> (-0.03%)` | :arrow_down: |
| [mysql](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [postgres](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.14% <13.46%> (-0.10%)` | :arrow_down: |
| [presto](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `38.10% <7.69%> (-0.04%)` | :arrow_down: |
| [python](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.23% <13.46%> (-31.10%)` | :arrow_down: |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [unit](https://app.codecov.io/gh/apache/superset/pull/45038/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/45038?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4218084737
##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -552,3 +552,534 @@ def test_set_dash_metadata_keeps_archived_trapped_chart_through_resave(
with skip_visibility_filter(db.session, Slice):
db.session.expire(dashboard, ["slices"])
assert {chart.id for chart in dashboard.slices} == {placed.id, trapped.id}
+
+
+def _make_dashboard_with_slices(
+ session: Session,
+ slice_names: list[str] | None = None,
+ dashboard_title: str = "original_dash",
+) -> tuple[Dashboard, list[Slice]]:
+ Dashboard.metadata.create_all(session.get_bind())
+ dataset = SqlaTable(
+ table_name="dao_test_table",
+ database=Database(database_name="dao_test_db", sqlalchemy_uri="sqlite://"),
+ )
+ db.session.add(dataset)
+ db.session.flush()
+
+ names = slice_names or ["chart_1", "chart_2"]
+ slices = [
+ Slice(
+ slice_name=name,
+ datasource_id=dataset.id,
+ datasource_type="table",
+ )
+ for name in names
+ ]
+ dashboard = Dashboard(
+ dashboard_title=dashboard_title,
+ slices=slices,
+ published=True,
+ )
+ db.session.add_all([*slices, dashboard])
+ db.session.flush()
+ return dashboard, slices
+
+
+def _make_sample_native_filter_metadata(
+ slices: list[Slice],
+ excluded_slices: list[Slice] | None = None,
+ extra_filters: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ positions = {
+ f"CHART-{slc.id}": {
+ "type": "CHART",
+ "id": f"CHART-{slc.id}",
+ "children": [],
+ "meta": {"chartId": slc.id, "width": 4, "height": 50},
+ }
+ for slc in slices
+ }
+ excluded_ids = [s.id for s in excluded_slices] if excluded_slices else []
+ filters: list[dict[str, Any]] = [
+ {
+ "id": "NATIVE_FILTER-1",
+ "name": "Filter 1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": excluded_ids},
+ "chartsInScope": [s.id for s in slices],
+ }
+ ]
+ if extra_filters:
+ filters.extend(extra_filters)
+ return {
+ "positions": positions,
+ "native_filter_configuration": filters,
+ }
+
+
+def test_copy_dashboard_duplicate_slices_remaps_native_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ json_metadata = _make_sample_native_filter_metadata(
+ slices=[chart1, chart2],
+ excluded_slices=[chart2],
+ )
+
+ copy_data = {
+ "dashboard_title": "copied_dash",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ assert len(copied_slices) == 2
+ assert copied_slices["chart_1"] != chart1.id
+ assert copied_slices["chart_2"] != chart2.id
+
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+ assert len(copied_filters) == 1
+
+ assert copied_filters[0]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ assert copied_filters[0]["scope"]["excluded"] == [copied_slices["chart_2"]]
+
+
+def test_copy_dashboard_handles_dividers_and_unscoped_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ filters: list[Any] = [
+ {"id": "NATIVE_FILTER_DIVIDER-1", "type": "DIVIDER", "title": "Group A"},
+ "invalid_filter_entry",
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ },
+ {"id": "DIVIDER-2", "type": "DIVIDER"},
+ ]
+ json_metadata = {
+ "positions": {
+ f"CHART-{chart1.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart1.id}",
+ "children": [],
+ "meta": {"chartId": chart1.id, "width": 4, "height": 50},
+ },
+ f"CHART-{chart2.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart2.id}",
+ "children": [],
+ "meta": {"chartId": chart2.id, "width": 4, "height": 50},
+ },
+ },
+ "native_filter_configuration": filters,
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_with_dividers",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+
+ # Divider preserved untouched
+ assert copied_filters[0] == {
+ "id": "NATIVE_FILTER_DIVIDER-1",
+ "type": "DIVIDER",
+ "title": "Group A",
+ }
+ # Non-dict element preserved untouched
+ assert copied_filters[1] == "invalid_filter_entry"
+ # Normal native filter remapped
+ assert copied_filters[2]["scope"]["excluded"] == [copied_slices["chart_1"]]
+ assert copied_filters[2]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ # Trailing divider preserved untouched
+ assert copied_filters[3] == {"id": "DIVIDER-2", "type": "DIVIDER"}
+
+
+def test_copy_dashboard_remaps_cross_filters_and_chart_configuration(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session, slice_names=["c1", "c2", "c3"]
+ )
+ json_metadata = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_cross_filters",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+
+ # Verify global_chart_configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slices["c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slices["c1"],
+ copied_slices["c2"],
+ ]
+
+ # Verify chart_configuration key, id, and crossFilters remapping
+ new_c1_key = str(copied_slices["c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ c1_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert c1_cfg["id"] == copied_slices["c1"]
+ assert c1_cfg["crossFilters"]["scope"]["excluded"] == [copied_slices["c2"]]
+ assert c1_cfg["crossFilters"]["chartsInScope"] == [copied_slices["c3"]]
+
+
+def test_set_dash_metadata_remaps_native_filters_when_slice_ids_provided(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ metadata_payload = {
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ }
+ ],
+ "chart_configuration": {
+ str(chart1.id): {
+ "id": chart1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+ "chartsInScope": [chart2.id],
+ },
+ }
+ },
+ }
+ old_to_new = {chart1.id: 991, chart2.id: 992}
+
+ DashboardDAO.set_dash_metadata(
+ dashboard,
+ metadata_payload,
+ old_to_new_slice_ids=old_to_new,
+ )
+
+ saved_metadata = json.loads(dashboard.json_metadata)
+ saved_filter = saved_metadata["native_filter_configuration"][0]
+ assert saved_filter["scope"]["excluded"] == [991]
+ assert saved_filter["chartsInScope"] == [991, 992]
+
+ saved_chart_cfg = saved_metadata["chart_configuration"]["991"]
+ assert saved_chart_cfg["id"] == 991
+ assert saved_chart_cfg["crossFilters"]["chartsInScope"] == [992]
+
+
+def test_issue_44983_consolidated_evidence_gate(session: Session) -> None:
+ """Consolidated evidence gate for Issue 44983.
+
+ Verifies end-to-end that duplicating a dashboard with duplicate_slices=True:
+ 1. Duplicates all slices and registers them to the new dashboard.
+ 2. Completely remaps native_filter_configuration chartsInScope and scope.excluded.
+ 3. Leaves visual divider entities and non-dictionary entries uncorrupted.
+ 4. Remaps global_chart_configuration scope.excluded and chartsInScope.
+ 5. Remaps chart_configuration keys, chart IDs, and crossFilters scopes.
+ 6. Preserves the original dashboard and slice references intact.
+ """
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session,
+ slice_names=["gate_c1", "gate_c2", "gate_c3"],
+ dashboard_title="gate_source_dashboard",
+ )
+ original_c1_id = c1.id
+ original_c2_id = c2.id
+ original_c3_id = c3.id
+
+ metadata_payload = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-gate",
+ "name": "Gate Filter",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c2.id],
+ "selectedLayers": [
+ f"chart-{c2.id}-layer-0",
+ f"chart-{c3.id}-layer-1",
+ ],
+ },
+ "chartsInScope": [c1.id, c2.id, c3.id],
+ },
+ {
+ "id": "NATIVE_FILTER_DIVIDER-gate",
+ "type": "DIVIDER",
+ "title": "Gate Divider",
+ },
+ ],
+ "chart_customization_config": [
+ {
+ "id": "CUSTOMIZATION-gate",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-custom"],
+ },
+ "chartsInScope": [c2.id],
+ },
+ {
+ "id": "CUSTOMIZATION-divider",
+ "type": "CHART_CUSTOMIZATION_DIVIDER",
+ },
+ ],
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+
+ copy_data = {
+ "dashboard_title": "gate_copied_dashboard",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(metadata_payload),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dashboard = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ # 1. Duplicated slices are distinct from originals
+ copied_slice_map = {s.slice_name: s.id for s in copied_dashboard.slices}
+ assert len(copied_slice_map) == 3
+ for gate_key in ("gate_c1", "gate_c2", "gate_c3"):
+ assert copied_slice_map[gate_key] not in {
+ original_c1_id,
+ original_c2_id,
+ original_c3_id,
+ }
+
+ copied_metadata = json.loads(copied_dashboard.json_metadata)
+
+ # 2. Native filter remapping
+ gate_filter = copied_metadata["native_filter_configuration"][0]
+ assert gate_filter["scope"]["excluded"] == [copied_slice_map["gate_c2"]]
+ assert gate_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c2']}-layer-0",
+ f"chart-{copied_slice_map['gate_c3']}-layer-1",
+ ]
+ assert gate_filter["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ copied_slice_map["gate_c3"],
+ ]
+
+ # 3. Divider preservation
+ gate_divider = copied_metadata["native_filter_configuration"][1]
+ assert gate_divider["id"] == "NATIVE_FILTER_DIVIDER-gate"
+ assert gate_divider["type"] == "DIVIDER"
+ assert "scope" not in gate_divider
+
+ # 3b. Chart customization configuration remapping
+ custom_cfg = copied_metadata["chart_customization_config"][0]
+ assert custom_cfg["id"] == "CUSTOMIZATION-gate"
+ assert custom_cfg["scope"]["excluded"] == [copied_slice_map["gate_c1"]]
+ assert custom_cfg["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c1']}-layer-custom"
+ ]
+ assert custom_cfg["chartsInScope"] == [copied_slice_map["gate_c2"]]
+
+ custom_divider = copied_metadata["chart_customization_config"][1]
+ assert custom_divider["id"] == "CUSTOMIZATION-divider"
+ assert custom_divider["type"] == "CHART_CUSTOMIZATION_DIVIDER"
+ assert "scope" not in custom_divider
+
+ # 4. Global chart configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slice_map["gate_c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ ]
+
+ # 5. Per-chart configuration remapping
+ new_c1_key = str(copied_slice_map["gate_c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ chart_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert chart_cfg["id"] == copied_slice_map["gate_c1"]
+ assert chart_cfg["crossFilters"]["scope"]["excluded"] == [
+ copied_slice_map["gate_c2"]
+ ]
+ assert chart_cfg["crossFilters"]["chartsInScope"] == [copied_slice_map["gate_c3"]]
+
+ # 6. Original dashboard slices preserved untouched
+ original_slice_ids = {s.id for s in dashboard.slices}
+ assert original_slice_ids == {original_c1_id, original_c2_id, original_c3_id}
+
+
+def test_remap_selected_layers_edge_cases() -> None:
+ old_to_new = {10: 100, 20: 200}
+ # Test dictionary format
+ layers_dict = {
+ "chart-10-layer-0": True,
+ "chart-20-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+ remapped_dict = DashboardDAO._remap_selected_layers(layers_dict, old_to_new)
+ assert remapped_dict == {
+ "chart-100-layer-0": True,
+ "chart-200-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+
+ # Test list format (Superset frontend string[] standard)
+ layers_list = [
+ "chart-10-layer-0",
+ "chart-20-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+ remapped_list = DashboardDAO._remap_selected_layers(layers_list, old_to_new)
+ assert remapped_list == [
+ "chart-100-layer-0",
+ "chart-200-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+
+
+def test_remap_slice_id_list_edge_cases() -> None:
+ old_to_new = {1: 10, 2: 20}
+ raw = [1, "2", "3", "invalid", None]
+ assert DashboardDAO._remap_slice_id_list(raw, old_to_new) == [
+ 10,
+ 20,
+ "3",
+ "invalid",
+ None,
+ ]
+
+
+def test_copy_dashboard_does_not_double_remap_overlapping_ids(
Review Comment:
This test is named and commented as covering overlapping IDs, but the clones get fresh primary keys while both originals still exist, so no new ID ever equals an old mapping key. A regression that remapped twice would still pass these assertions. Could you drive a mapping like `{1: 2, 2: 3}` through `set_dash_metadata` (with `chartsInScope=[1, 2]`, `excluded=[1]`, `selectedLayers=["chart-1-layer-0"]`) and assert `[2, 3]`, `[2]` and `"chart-2-layer-0"`?
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4252508526
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +536,137 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_slice_id_list(
+ slice_ids: list[Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> list[Any]:
+ remapped: list[Any] = []
+ for cid in slice_ids:
+ try:
+ int_id = int(cid)
+ remapped.append(old_to_new_slice_ids.get(int_id, cid))
+ except (ValueError, TypeError):
+ remapped.append(cid)
+ return remapped
+
+ @staticmethod
+ def _remap_layer_key(layer_key: Any, old_to_new_slice_ids: dict[int, int]) -> Any:
+ if not isinstance(layer_key, str):
+ return layer_key
+ match = re.match(r"^chart-(\d+)(.*)$", layer_key)
+ if match:
+ old_id = int(match.group(1))
+ suffix = match.group(2)
+ new_id = old_to_new_slice_ids.get(old_id, old_id)
+ return f"chart-{new_id}{suffix}"
+ return layer_key
+
+ @classmethod
+ def _remap_selected_layers(
+ cls,
+ selected_layers: Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> Any:
+ if isinstance(selected_layers, list):
+ return [
+ cls._remap_layer_key(k, old_to_new_slice_ids)
+ for k in selected_layers
+ ]
+ if isinstance(selected_layers, dict):
+ return {
+ cls._remap_layer_key(k, old_to_new_slice_ids): v
+ for k, v in selected_layers.items()
+ }
+ if isinstance(selected_layers, set):
+ return {
+ cls._remap_layer_key(k, old_to_new_slice_ids)
+ for k in selected_layers
+ }
+ return selected_layers
+
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded, selectedLayers and chartsInScope of a container."""
+ if not isinstance(container, dict):
+ return
+
+ if container.get("type") in ("DIVIDER", "CHART_CUSTOMIZATION_DIVIDER") or str(
+ container.get("id", "")
+ ).startswith(
+ ("NATIVE_FILTER_DIVIDER", "DIVIDER", "CHART_CUSTOMIZATION_DIVIDER")
+ ):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict):
+ if isinstance(scope.get("excluded"), list):
+ scope["excluded"] = DashboardDAO._remap_slice_id_list(
+ scope["excluded"], old_to_new_slice_ids
+ )
+ if isinstance(scope.get("selectedLayers"), (list, dict, set)):
+ scope["selectedLayers"] = DashboardDAO._remap_selected_layers(
+ scope["selectedLayers"], old_to_new_slice_ids
+ )
+
+ if isinstance(container.get("chartsInScope"), list):
+ container["chartsInScope"] = DashboardDAO._remap_slice_id_list(
+ container["chartsInScope"], old_to_new_slice_ids
+ )
+
+ @classmethod
+ def _remap_chart_configuration(
+ cls,
+ chart_configuration: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> dict[str, Any]:
+ new_chart_configuration: dict[str, Any] = {}
+ for old_key, chart_config in chart_configuration.items():
+ try:
+ int_key = int(old_key)
+ new_key = str(old_to_new_slice_ids.get(int_key, int_key))
+ except (ValueError, TypeError):
+ new_key = str(old_key)
+
+ if isinstance(chart_config, dict):
+ if isinstance(chart_config.get("id"), int):
+ chart_config["id"] = old_to_new_slice_ids.get(
+ chart_config["id"], chart_config["id"]
+ )
+ cls._remap_filter_scope(
+ chart_config.get("crossFilters"), old_to_new_slice_ids
+ )
+ new_chart_configuration[new_key] = chart_config
+ return new_chart_configuration
+
+ @classmethod
+ def _remap_filter_scopes(
+ cls,
+ metadata: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap filter scopes and cross-filter references in dashboard metadata."""
+ if not isinstance(metadata, dict) or not old_to_new_slice_ids:
+ return
+
+ for key in ("native_filter_configuration", "chart_customization_config"):
+ if isinstance(metadata.get(key), list):
+ for item in metadata[key]:
+ cls._remap_filter_scope(item, old_to_new_slice_ids)
Review Comment:
Good catch @sadpandajoe! Updated `DashboardDAO._remap_filter_scope` in commit `d07e3bbbed` so legacy `chart_customization_config` entries with a top-level `chartId` (with a `not isinstance(..., bool)` guard) are remapped through `old_to_new_slice_ids` alongside `scope` and `chartsInScope`. Also added legacy `chartId` coverage in `test_issue_44983_consolidated_evidence_gate` and `test_set_dash_metadata_does_not_double_remap_overlapping_ids`.
##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -552,3 +552,567 @@ def test_set_dash_metadata_keeps_archived_trapped_chart_through_resave(
with skip_visibility_filter(db.session, Slice):
db.session.expire(dashboard, ["slices"])
assert {chart.id for chart in dashboard.slices} == {placed.id, trapped.id}
+
+
+def _make_dashboard_with_slices(
+ session: Session,
+ slice_names: list[str] | None = None,
+ dashboard_title: str = "original_dash",
+) -> tuple[Dashboard, list[Slice]]:
+ Dashboard.metadata.create_all(session.get_bind())
+ dataset = SqlaTable(
+ table_name="dao_test_table",
+ database=Database(database_name="dao_test_db", sqlalchemy_uri="sqlite://"),
+ )
+ db.session.add(dataset)
+ db.session.flush()
+
+ names = slice_names or ["chart_1", "chart_2"]
+ slices = [
+ Slice(
+ slice_name=name,
+ datasource_id=dataset.id,
+ datasource_type="table",
+ )
+ for name in names
+ ]
+ dashboard = Dashboard(
+ dashboard_title=dashboard_title,
+ slices=slices,
+ published=True,
+ )
+ db.session.add_all([*slices, dashboard])
+ db.session.flush()
+ return dashboard, slices
+
+
+def _make_sample_native_filter_metadata(
+ slices: list[Slice],
+ excluded_slices: list[Slice] | None = None,
+ extra_filters: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ positions = {
+ f"CHART-{slc.id}": {
+ "type": "CHART",
+ "id": f"CHART-{slc.id}",
+ "children": [],
+ "meta": {"chartId": slc.id, "width": 4, "height": 50},
+ }
+ for slc in slices
+ }
+ excluded_ids = [s.id for s in excluded_slices] if excluded_slices else []
+ filters: list[dict[str, Any]] = [
+ {
+ "id": "NATIVE_FILTER-1",
+ "name": "Filter 1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": excluded_ids},
+ "chartsInScope": [s.id for s in slices],
+ }
+ ]
+ if extra_filters:
+ filters.extend(extra_filters)
+ return {
+ "positions": positions,
+ "native_filter_configuration": filters,
+ }
+
+
+def test_copy_dashboard_duplicate_slices_remaps_native_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ json_metadata = _make_sample_native_filter_metadata(
+ slices=[chart1, chart2],
+ excluded_slices=[chart2],
+ )
+
+ copy_data = {
+ "dashboard_title": "copied_dash",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ assert len(copied_slices) == 2
+ assert copied_slices["chart_1"] != chart1.id
+ assert copied_slices["chart_2"] != chart2.id
+
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+ assert len(copied_filters) == 1
+
+ assert copied_filters[0]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ assert copied_filters[0]["scope"]["excluded"] == [copied_slices["chart_2"]]
+
+
+def test_copy_dashboard_handles_dividers_and_unscoped_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ filters: list[Any] = [
+ {"id": "NATIVE_FILTER_DIVIDER-1", "type": "DIVIDER", "title": "Group A"},
+ "invalid_filter_entry",
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ },
+ {"id": "DIVIDER-2", "type": "DIVIDER"},
+ ]
+ json_metadata = {
+ "positions": {
+ f"CHART-{chart1.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart1.id}",
+ "children": [],
+ "meta": {"chartId": chart1.id, "width": 4, "height": 50},
+ },
+ f"CHART-{chart2.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart2.id}",
+ "children": [],
+ "meta": {"chartId": chart2.id, "width": 4, "height": 50},
+ },
+ },
+ "native_filter_configuration": filters,
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_with_dividers",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+
+ # Divider preserved untouched
+ assert copied_filters[0] == {
+ "id": "NATIVE_FILTER_DIVIDER-1",
+ "type": "DIVIDER",
+ "title": "Group A",
+ }
+ # Non-dict element preserved untouched
+ assert copied_filters[1] == "invalid_filter_entry"
+ # Normal native filter remapped
+ assert copied_filters[2]["scope"]["excluded"] == [copied_slices["chart_1"]]
+ assert copied_filters[2]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ # Trailing divider preserved untouched
+ assert copied_filters[3] == {"id": "DIVIDER-2", "type": "DIVIDER"}
+
+
+def test_copy_dashboard_remaps_cross_filters_and_chart_configuration(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session, slice_names=["c1", "c2", "c3"]
+ )
+ json_metadata = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_cross_filters",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+
+ # Verify global_chart_configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slices["c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slices["c1"],
+ copied_slices["c2"],
+ ]
+
+ # Verify chart_configuration key, id, and crossFilters remapping
+ new_c1_key = str(copied_slices["c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ c1_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert c1_cfg["id"] == copied_slices["c1"]
+ assert c1_cfg["crossFilters"]["scope"]["excluded"] == [copied_slices["c2"]]
+ assert c1_cfg["crossFilters"]["chartsInScope"] == [copied_slices["c3"]]
+
+
+def test_set_dash_metadata_remaps_native_filters_when_slice_ids_provided(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ metadata_payload = {
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ }
+ ],
+ "chart_configuration": {
+ str(chart1.id): {
+ "id": chart1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+ "chartsInScope": [chart2.id],
+ },
+ }
+ },
+ }
+ old_to_new = {chart1.id: 991, chart2.id: 992}
+
+ DashboardDAO.set_dash_metadata(
+ dashboard,
+ metadata_payload,
+ old_to_new_slice_ids=old_to_new,
+ )
+
+ saved_metadata = json.loads(dashboard.json_metadata)
+ saved_filter = saved_metadata["native_filter_configuration"][0]
+ assert saved_filter["scope"]["excluded"] == [991]
+ assert saved_filter["chartsInScope"] == [991, 992]
+
+ saved_chart_cfg = saved_metadata["chart_configuration"]["991"]
+ assert saved_chart_cfg["id"] == 991
+ assert saved_chart_cfg["crossFilters"]["chartsInScope"] == [992]
+
+
+def test_issue_44983_consolidated_evidence_gate(session: Session) -> None:
+ """Consolidated evidence gate for Issue 44983.
+
+ Verifies end-to-end that duplicating a dashboard with duplicate_slices=True:
+ 1. Duplicates all slices and registers them to the new dashboard.
+ 2. Completely remaps native_filter_configuration chartsInScope and scope.excluded.
+ 3. Leaves visual divider entities and non-dictionary entries uncorrupted.
+ 4. Remaps global_chart_configuration scope.excluded and chartsInScope.
+ 5. Remaps chart_configuration keys, chart IDs, and crossFilters scopes.
+ 6. Preserves the original dashboard and slice references intact.
+ """
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session,
+ slice_names=["gate_c1", "gate_c2", "gate_c3"],
+ dashboard_title="gate_source_dashboard",
+ )
+ original_c1_id = c1.id
+ original_c2_id = c2.id
+ original_c3_id = c3.id
+
+ metadata_payload = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-gate",
+ "name": "Gate Filter",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c2.id],
+ "selectedLayers": [
+ f"chart-{c2.id}-layer-0",
+ f"chart-{c3.id}-layer-1",
+ ],
+ },
+ "chartsInScope": [c1.id, c2.id, c3.id],
+ },
+ {
+ "id": "NATIVE_FILTER_DIVIDER-gate",
+ "type": "DIVIDER",
+ "title": "Gate Divider",
+ },
+ ],
+ "chart_customization_config": [
+ {
+ "id": "CUSTOMIZATION-gate",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-custom"],
+ },
+ "chartsInScope": [c2.id],
+ },
+ {
+ "id": "CUSTOMIZATION-divider",
+ "type": "CHART_CUSTOMIZATION_DIVIDER",
+ },
+ ],
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+
+ copy_data = {
+ "dashboard_title": "gate_copied_dashboard",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(metadata_payload),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dashboard = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ # 1. Duplicated slices are distinct from originals
+ copied_slice_map = {s.slice_name: s.id for s in copied_dashboard.slices}
+ assert len(copied_slice_map) == 3
+ for gate_key in ("gate_c1", "gate_c2", "gate_c3"):
+ assert copied_slice_map[gate_key] not in {
+ original_c1_id,
+ original_c2_id,
+ original_c3_id,
+ }
+
+ copied_metadata = json.loads(copied_dashboard.json_metadata)
+
+ # 2. Native filter remapping
+ gate_filter = copied_metadata["native_filter_configuration"][0]
+ assert gate_filter["scope"]["excluded"] == [copied_slice_map["gate_c2"]]
+ assert gate_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c2']}-layer-0",
+ f"chart-{copied_slice_map['gate_c3']}-layer-1",
+ ]
+ assert gate_filter["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ copied_slice_map["gate_c3"],
+ ]
+
+ # 3. Divider preservation
+ gate_divider = copied_metadata["native_filter_configuration"][1]
+ assert gate_divider["id"] == "NATIVE_FILTER_DIVIDER-gate"
+ assert gate_divider["type"] == "DIVIDER"
+ assert "scope" not in gate_divider
+
+ # 3b. Chart customization configuration remapping
+ custom_cfg = copied_metadata["chart_customization_config"][0]
+ assert custom_cfg["id"] == "CUSTOMIZATION-gate"
+ assert custom_cfg["scope"]["excluded"] == [copied_slice_map["gate_c1"]]
+ assert custom_cfg["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c1']}-layer-custom"
+ ]
+ assert custom_cfg["chartsInScope"] == [copied_slice_map["gate_c2"]]
+
+ custom_divider = copied_metadata["chart_customization_config"][1]
+ assert custom_divider["id"] == "CUSTOMIZATION-divider"
+ assert custom_divider["type"] == "CHART_CUSTOMIZATION_DIVIDER"
+ assert "scope" not in custom_divider
+
+ # 4. Global chart configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slice_map["gate_c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ ]
+
+ # 5. Per-chart configuration remapping
+ new_c1_key = str(copied_slice_map["gate_c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ chart_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert chart_cfg["id"] == copied_slice_map["gate_c1"]
+ assert chart_cfg["crossFilters"]["scope"]["excluded"] == [
+ copied_slice_map["gate_c2"]
+ ]
+ assert chart_cfg["crossFilters"]["chartsInScope"] == [copied_slice_map["gate_c3"]]
+
+ # 6. Original dashboard slices preserved untouched
+ original_slice_ids = {s.id for s in dashboard.slices}
+ assert original_slice_ids == {original_c1_id, original_c2_id, original_c3_id}
+
+
+def test_remap_selected_layers_edge_cases() -> None:
+ old_to_new = {10: 100, 20: 200}
+ # Test dictionary format
+ layers_dict = {
+ "chart-10-layer-0": True,
+ "chart-20-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+ remapped_dict = DashboardDAO._remap_selected_layers(layers_dict, old_to_new)
+ assert remapped_dict == {
+ "chart-100-layer-0": True,
+ "chart-200-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+
+ # Test list format (Superset frontend string[] standard)
+ layers_list = [
+ "chart-10-layer-0",
+ "chart-20-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+ remapped_list = DashboardDAO._remap_selected_layers(layers_list, old_to_new)
+ assert remapped_list == [
+ "chart-100-layer-0",
+ "chart-200-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+
+
+def test_remap_slice_id_list_edge_cases() -> None:
+ old_to_new = {1: 10, 2: 20}
+ raw = [1, "2", "3", "invalid", None]
+ assert DashboardDAO._remap_slice_id_list(raw, old_to_new) == [
+ 10,
+ 20,
+ "3",
+ "invalid",
+ None,
+ ]
+
+
+def test_copy_dashboard_does_not_double_remap_overlapping_ids(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2) = _make_dashboard_with_slices(session)
+ # Simulate overlapping IDs where old_to_new_slice_ids has old ID matching new ID
+ metadata = {
+ "positions": {
+ "CHART-1": {"type": "CHART", "meta": {"chartId": c1.id}},
+ "CHART-2": {"type": "CHART", "meta": {"chartId": c2.id}},
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-overlap",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-0"],
+ },
+ "chartsInScope": [c1.id, c2.id],
+ }
+ ],
+ }
+ dashboard.json_metadata = json.dumps(metadata)
+ dashboard.params = json.dumps(metadata)
+ session.commit()
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(
+ dashboard,
+ {
+ "dashboard_title": "Copied Dash",
+ "json_metadata": json.dumps(metadata),
+ "duplicate_slices": True,
+ },
+ )
+ copied_meta = json.loads(copied_dash.json_metadata)
+ copied_filter = copied_meta["native_filter_configuration"][0]
+ # Each cloned slice must have a distinct new id; remapped exactly once
+ new_slice_ids = [s.id for s in copied_dash.slices]
+ assert len(new_slice_ids) == 2
+ assert len(set(copied_filter["chartsInScope"])) == 2
+ assert set(copied_filter["chartsInScope"]) == set(new_slice_ids)
+ copied_c1_id = next(
+ s.id for s in copied_dash.slices if s.slice_name == c1.slice_name
+ )
+ assert copied_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_c1_id}-layer-0"
+ ]
+
+def test_set_dash_metadata_does_not_double_remap_overlapping_ids(
Review Comment:
Fixed in commit `d07e3bbbed`. Restored the two-blank-line separation before `test_set_dash_metadata_does_not_double_remap_overlapping_ids`, normalized the trailing newline, and verified `ruff check` and `ruff format` pass cleanly on both files.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6026735654
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 0556fb97963a3c1ce3393e04c0233ecd5040a022 |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6ac57799d6447b0008433f34 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-45038--superset-docs-preview.netlify.app](https://deploy-preview-45038--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DctBDgIhDADAv_RsIwl1WfyBz2ChaJNdaACNxvh3uc1lvqCtHjrgCnCCrYUSH9NZ3mfp_clI5FeLJQx5MWbZB7eOPVZlbHwEVSn3ORPrXj-3NO8S4sU579NC5DZjzErWZkvw-wM) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-45038--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #45038:
URL: https://github.com/apache/superset/pull/45038#issuecomment-6026786025
## CodeAnt PR Risk: Medium Risk
- The PR needs attention before merging.
- Layer-scoped filter references in scope.selectedLayers are not remapped, so those settings may still target source charts after duplication.
- Chart customization scope references may also remain pointed at original charts because chart_customization_config is not handled.
**Assessed commit:** `0556fb97963a`
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4243543975
##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -552,3 +552,534 @@ def test_set_dash_metadata_keeps_archived_trapped_chart_through_resave(
with skip_visibility_filter(db.session, Slice):
db.session.expire(dashboard, ["slices"])
assert {chart.id for chart in dashboard.slices} == {placed.id, trapped.id}
+
+
+def _make_dashboard_with_slices(
+ session: Session,
+ slice_names: list[str] | None = None,
+ dashboard_title: str = "original_dash",
+) -> tuple[Dashboard, list[Slice]]:
+ Dashboard.metadata.create_all(session.get_bind())
+ dataset = SqlaTable(
+ table_name="dao_test_table",
+ database=Database(database_name="dao_test_db", sqlalchemy_uri="sqlite://"),
+ )
+ db.session.add(dataset)
+ db.session.flush()
+
+ names = slice_names or ["chart_1", "chart_2"]
+ slices = [
+ Slice(
+ slice_name=name,
+ datasource_id=dataset.id,
+ datasource_type="table",
+ )
+ for name in names
+ ]
+ dashboard = Dashboard(
+ dashboard_title=dashboard_title,
+ slices=slices,
+ published=True,
+ )
+ db.session.add_all([*slices, dashboard])
+ db.session.flush()
+ return dashboard, slices
+
+
+def _make_sample_native_filter_metadata(
+ slices: list[Slice],
+ excluded_slices: list[Slice] | None = None,
+ extra_filters: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ positions = {
+ f"CHART-{slc.id}": {
+ "type": "CHART",
+ "id": f"CHART-{slc.id}",
+ "children": [],
+ "meta": {"chartId": slc.id, "width": 4, "height": 50},
+ }
+ for slc in slices
+ }
+ excluded_ids = [s.id for s in excluded_slices] if excluded_slices else []
+ filters: list[dict[str, Any]] = [
+ {
+ "id": "NATIVE_FILTER-1",
+ "name": "Filter 1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": excluded_ids},
+ "chartsInScope": [s.id for s in slices],
+ }
+ ]
+ if extra_filters:
+ filters.extend(extra_filters)
+ return {
+ "positions": positions,
+ "native_filter_configuration": filters,
+ }
+
+
+def test_copy_dashboard_duplicate_slices_remaps_native_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ json_metadata = _make_sample_native_filter_metadata(
+ slices=[chart1, chart2],
+ excluded_slices=[chart2],
+ )
+
+ copy_data = {
+ "dashboard_title": "copied_dash",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ assert len(copied_slices) == 2
+ assert copied_slices["chart_1"] != chart1.id
+ assert copied_slices["chart_2"] != chart2.id
+
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+ assert len(copied_filters) == 1
+
+ assert copied_filters[0]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ assert copied_filters[0]["scope"]["excluded"] == [copied_slices["chart_2"]]
+
+
+def test_copy_dashboard_handles_dividers_and_unscoped_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ filters: list[Any] = [
+ {"id": "NATIVE_FILTER_DIVIDER-1", "type": "DIVIDER", "title": "Group A"},
+ "invalid_filter_entry",
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ },
+ {"id": "DIVIDER-2", "type": "DIVIDER"},
+ ]
+ json_metadata = {
+ "positions": {
+ f"CHART-{chart1.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart1.id}",
+ "children": [],
+ "meta": {"chartId": chart1.id, "width": 4, "height": 50},
+ },
+ f"CHART-{chart2.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart2.id}",
+ "children": [],
+ "meta": {"chartId": chart2.id, "width": 4, "height": 50},
+ },
+ },
+ "native_filter_configuration": filters,
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_with_dividers",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+
+ # Divider preserved untouched
+ assert copied_filters[0] == {
+ "id": "NATIVE_FILTER_DIVIDER-1",
+ "type": "DIVIDER",
+ "title": "Group A",
+ }
+ # Non-dict element preserved untouched
+ assert copied_filters[1] == "invalid_filter_entry"
+ # Normal native filter remapped
+ assert copied_filters[2]["scope"]["excluded"] == [copied_slices["chart_1"]]
+ assert copied_filters[2]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ # Trailing divider preserved untouched
+ assert copied_filters[3] == {"id": "DIVIDER-2", "type": "DIVIDER"}
+
+
+def test_copy_dashboard_remaps_cross_filters_and_chart_configuration(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session, slice_names=["c1", "c2", "c3"]
+ )
+ json_metadata = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_cross_filters",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+
+ # Verify global_chart_configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slices["c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slices["c1"],
+ copied_slices["c2"],
+ ]
+
+ # Verify chart_configuration key, id, and crossFilters remapping
+ new_c1_key = str(copied_slices["c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ c1_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert c1_cfg["id"] == copied_slices["c1"]
+ assert c1_cfg["crossFilters"]["scope"]["excluded"] == [copied_slices["c2"]]
+ assert c1_cfg["crossFilters"]["chartsInScope"] == [copied_slices["c3"]]
+
+
+def test_set_dash_metadata_remaps_native_filters_when_slice_ids_provided(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ metadata_payload = {
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ }
+ ],
+ "chart_configuration": {
+ str(chart1.id): {
+ "id": chart1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+ "chartsInScope": [chart2.id],
+ },
+ }
+ },
+ }
+ old_to_new = {chart1.id: 991, chart2.id: 992}
+
+ DashboardDAO.set_dash_metadata(
+ dashboard,
+ metadata_payload,
+ old_to_new_slice_ids=old_to_new,
+ )
+
+ saved_metadata = json.loads(dashboard.json_metadata)
+ saved_filter = saved_metadata["native_filter_configuration"][0]
+ assert saved_filter["scope"]["excluded"] == [991]
+ assert saved_filter["chartsInScope"] == [991, 992]
+
+ saved_chart_cfg = saved_metadata["chart_configuration"]["991"]
+ assert saved_chart_cfg["id"] == 991
+ assert saved_chart_cfg["crossFilters"]["chartsInScope"] == [992]
+
+
+def test_issue_44983_consolidated_evidence_gate(session: Session) -> None:
+ """Consolidated evidence gate for Issue 44983.
+
+ Verifies end-to-end that duplicating a dashboard with duplicate_slices=True:
+ 1. Duplicates all slices and registers them to the new dashboard.
+ 2. Completely remaps native_filter_configuration chartsInScope and scope.excluded.
+ 3. Leaves visual divider entities and non-dictionary entries uncorrupted.
+ 4. Remaps global_chart_configuration scope.excluded and chartsInScope.
+ 5. Remaps chart_configuration keys, chart IDs, and crossFilters scopes.
+ 6. Preserves the original dashboard and slice references intact.
+ """
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session,
+ slice_names=["gate_c1", "gate_c2", "gate_c3"],
+ dashboard_title="gate_source_dashboard",
+ )
+ original_c1_id = c1.id
+ original_c2_id = c2.id
+ original_c3_id = c3.id
+
+ metadata_payload = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-gate",
+ "name": "Gate Filter",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c2.id],
+ "selectedLayers": [
+ f"chart-{c2.id}-layer-0",
+ f"chart-{c3.id}-layer-1",
+ ],
+ },
+ "chartsInScope": [c1.id, c2.id, c3.id],
+ },
+ {
+ "id": "NATIVE_FILTER_DIVIDER-gate",
+ "type": "DIVIDER",
+ "title": "Gate Divider",
+ },
+ ],
+ "chart_customization_config": [
+ {
+ "id": "CUSTOMIZATION-gate",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-custom"],
+ },
+ "chartsInScope": [c2.id],
+ },
+ {
+ "id": "CUSTOMIZATION-divider",
+ "type": "CHART_CUSTOMIZATION_DIVIDER",
+ },
+ ],
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+
+ copy_data = {
+ "dashboard_title": "gate_copied_dashboard",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(metadata_payload),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dashboard = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ # 1. Duplicated slices are distinct from originals
+ copied_slice_map = {s.slice_name: s.id for s in copied_dashboard.slices}
+ assert len(copied_slice_map) == 3
+ for gate_key in ("gate_c1", "gate_c2", "gate_c3"):
+ assert copied_slice_map[gate_key] not in {
+ original_c1_id,
+ original_c2_id,
+ original_c3_id,
+ }
+
+ copied_metadata = json.loads(copied_dashboard.json_metadata)
+
+ # 2. Native filter remapping
+ gate_filter = copied_metadata["native_filter_configuration"][0]
+ assert gate_filter["scope"]["excluded"] == [copied_slice_map["gate_c2"]]
+ assert gate_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c2']}-layer-0",
+ f"chart-{copied_slice_map['gate_c3']}-layer-1",
+ ]
+ assert gate_filter["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ copied_slice_map["gate_c3"],
+ ]
+
+ # 3. Divider preservation
+ gate_divider = copied_metadata["native_filter_configuration"][1]
+ assert gate_divider["id"] == "NATIVE_FILTER_DIVIDER-gate"
+ assert gate_divider["type"] == "DIVIDER"
+ assert "scope" not in gate_divider
+
+ # 3b. Chart customization configuration remapping
+ custom_cfg = copied_metadata["chart_customization_config"][0]
+ assert custom_cfg["id"] == "CUSTOMIZATION-gate"
+ assert custom_cfg["scope"]["excluded"] == [copied_slice_map["gate_c1"]]
+ assert custom_cfg["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c1']}-layer-custom"
+ ]
+ assert custom_cfg["chartsInScope"] == [copied_slice_map["gate_c2"]]
+
+ custom_divider = copied_metadata["chart_customization_config"][1]
+ assert custom_divider["id"] == "CUSTOMIZATION-divider"
+ assert custom_divider["type"] == "CHART_CUSTOMIZATION_DIVIDER"
+ assert "scope" not in custom_divider
+
+ # 4. Global chart configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slice_map["gate_c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ ]
+
+ # 5. Per-chart configuration remapping
+ new_c1_key = str(copied_slice_map["gate_c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ chart_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert chart_cfg["id"] == copied_slice_map["gate_c1"]
+ assert chart_cfg["crossFilters"]["scope"]["excluded"] == [
+ copied_slice_map["gate_c2"]
+ ]
+ assert chart_cfg["crossFilters"]["chartsInScope"] == [copied_slice_map["gate_c3"]]
+
+ # 6. Original dashboard slices preserved untouched
+ original_slice_ids = {s.id for s in dashboard.slices}
+ assert original_slice_ids == {original_c1_id, original_c2_id, original_c3_id}
+
+
+def test_remap_selected_layers_edge_cases() -> None:
+ old_to_new = {10: 100, 20: 200}
+ # Test dictionary format
+ layers_dict = {
+ "chart-10-layer-0": True,
+ "chart-20-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+ remapped_dict = DashboardDAO._remap_selected_layers(layers_dict, old_to_new)
+ assert remapped_dict == {
+ "chart-100-layer-0": True,
+ "chart-200-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+
+ # Test list format (Superset frontend string[] standard)
+ layers_list = [
+ "chart-10-layer-0",
+ "chart-20-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+ remapped_list = DashboardDAO._remap_selected_layers(layers_list, old_to_new)
+ assert remapped_list == [
+ "chart-100-layer-0",
+ "chart-200-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+
+
+def test_remap_slice_id_list_edge_cases() -> None:
+ old_to_new = {1: 10, 2: 20}
+ raw = [1, "2", "3", "invalid", None]
+ assert DashboardDAO._remap_slice_id_list(raw, old_to_new) == [
+ 10,
+ 20,
+ "3",
+ "invalid",
+ None,
+ ]
+
+
+def test_copy_dashboard_does_not_double_remap_overlapping_ids(
Review Comment:
Added in commit `0786da887f`:
`test_set_dash_metadata_does_not_double_remap_overlapping_ids` drives `{1: 2, 2: 3}` through `set_dash_metadata` with `chartsInScope=[1, 2]`, `excluded=[1]`, and `selectedLayers=["chart-1-layer-0"]`. It asserts that the saved metadata produces `[2, 3]`, `[2]`, and `["chart-2-layer-0"]`, verifying that single-pass atomic remapping is preserved and no chained remapping (1 -> 2 -> 3) occurs.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4243610343
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +536,137 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_slice_id_list(
+ slice_ids: list[Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> list[Any]:
+ remapped: list[Any] = []
+ for cid in slice_ids:
+ try:
+ int_id = int(cid)
+ remapped.append(old_to_new_slice_ids.get(int_id, cid))
+ except (ValueError, TypeError):
+ remapped.append(cid)
+ return remapped
+
+ @staticmethod
+ def _remap_layer_key(layer_key: Any, old_to_new_slice_ids: dict[int, int]) -> Any:
+ if not isinstance(layer_key, str):
+ return layer_key
+ match = re.match(r"^chart-(\d+)(.*)$", layer_key)
+ if match:
+ old_id = int(match.group(1))
+ suffix = match.group(2)
+ new_id = old_to_new_slice_ids.get(old_id, old_id)
+ return f"chart-{new_id}{suffix}"
+ return layer_key
+
+ @classmethod
+ def _remap_selected_layers(
+ cls,
+ selected_layers: Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> Any:
+ if isinstance(selected_layers, list):
+ return [
+ cls._remap_layer_key(k, old_to_new_slice_ids)
+ for k in selected_layers
+ ]
+ if isinstance(selected_layers, dict):
+ return {
+ cls._remap_layer_key(k, old_to_new_slice_ids): v
+ for k, v in selected_layers.items()
+ }
+ if isinstance(selected_layers, set):
+ return {
+ cls._remap_layer_key(k, old_to_new_slice_ids)
+ for k in selected_layers
+ }
+ return selected_layers
+
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded, selectedLayers and chartsInScope of a container."""
+ if not isinstance(container, dict):
+ return
+
+ if container.get("type") in ("DIVIDER", "CHART_CUSTOMIZATION_DIVIDER") or str(
+ container.get("id", "")
+ ).startswith(
+ ("NATIVE_FILTER_DIVIDER", "DIVIDER", "CHART_CUSTOMIZATION_DIVIDER")
+ ):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict):
+ if isinstance(scope.get("excluded"), list):
+ scope["excluded"] = DashboardDAO._remap_slice_id_list(
+ scope["excluded"], old_to_new_slice_ids
+ )
+ if isinstance(scope.get("selectedLayers"), (list, dict, set)):
+ scope["selectedLayers"] = DashboardDAO._remap_selected_layers(
+ scope["selectedLayers"], old_to_new_slice_ids
+ )
+
+ if isinstance(container.get("chartsInScope"), list):
+ container["chartsInScope"] = DashboardDAO._remap_slice_id_list(
+ container["chartsInScope"], old_to_new_slice_ids
+ )
+
+ @classmethod
+ def _remap_chart_configuration(
+ cls,
+ chart_configuration: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> dict[str, Any]:
+ new_chart_configuration: dict[str, Any] = {}
+ for old_key, chart_config in chart_configuration.items():
+ try:
+ int_key = int(old_key)
+ new_key = str(old_to_new_slice_ids.get(int_key, int_key))
+ except (ValueError, TypeError):
+ new_key = str(old_key)
+
+ if isinstance(chart_config, dict):
+ if isinstance(chart_config.get("id"), int):
+ chart_config["id"] = old_to_new_slice_ids.get(
+ chart_config["id"], chart_config["id"]
+ )
+ cls._remap_filter_scope(
+ chart_config.get("crossFilters"), old_to_new_slice_ids
+ )
+ new_chart_configuration[new_key] = chart_config
+ return new_chart_configuration
+
+ @classmethod
+ def _remap_filter_scopes(
+ cls,
+ metadata: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap filter scopes and cross-filter references in dashboard metadata."""
+ if not isinstance(metadata, dict) or not old_to_new_slice_ids:
+ return
+
+ for key in ("native_filter_configuration", "chart_customization_config"):
+ if isinstance(metadata.get(key), list):
+ for item in metadata[key]:
+ cls._remap_filter_scope(item, old_to_new_slice_ids)
Review Comment:
Legacy `chart_customization_config` entries carry their target in a top-level `chartId` (no `type` key), and `migrateChartCustomization` rebuilds `chartsInScope` from it on load. Nothing here remaps that field, so after Save As with duplicated charts a legacy `{chartId: 10, customization: {...}}` keeps pointing at the original chart 10 even though the copy only contains the new chart. The control then won't show for the copied chart. Should `_remap_filter_scope` also map `chartId` for these items?
##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -552,3 +552,567 @@ def test_set_dash_metadata_keeps_archived_trapped_chart_through_resave(
with skip_visibility_filter(db.session, Slice):
db.session.expire(dashboard, ["slices"])
assert {chart.id for chart in dashboard.slices} == {placed.id, trapped.id}
+
+
+def _make_dashboard_with_slices(
+ session: Session,
+ slice_names: list[str] | None = None,
+ dashboard_title: str = "original_dash",
+) -> tuple[Dashboard, list[Slice]]:
+ Dashboard.metadata.create_all(session.get_bind())
+ dataset = SqlaTable(
+ table_name="dao_test_table",
+ database=Database(database_name="dao_test_db", sqlalchemy_uri="sqlite://"),
+ )
+ db.session.add(dataset)
+ db.session.flush()
+
+ names = slice_names or ["chart_1", "chart_2"]
+ slices = [
+ Slice(
+ slice_name=name,
+ datasource_id=dataset.id,
+ datasource_type="table",
+ )
+ for name in names
+ ]
+ dashboard = Dashboard(
+ dashboard_title=dashboard_title,
+ slices=slices,
+ published=True,
+ )
+ db.session.add_all([*slices, dashboard])
+ db.session.flush()
+ return dashboard, slices
+
+
+def _make_sample_native_filter_metadata(
+ slices: list[Slice],
+ excluded_slices: list[Slice] | None = None,
+ extra_filters: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ positions = {
+ f"CHART-{slc.id}": {
+ "type": "CHART",
+ "id": f"CHART-{slc.id}",
+ "children": [],
+ "meta": {"chartId": slc.id, "width": 4, "height": 50},
+ }
+ for slc in slices
+ }
+ excluded_ids = [s.id for s in excluded_slices] if excluded_slices else []
+ filters: list[dict[str, Any]] = [
+ {
+ "id": "NATIVE_FILTER-1",
+ "name": "Filter 1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": excluded_ids},
+ "chartsInScope": [s.id for s in slices],
+ }
+ ]
+ if extra_filters:
+ filters.extend(extra_filters)
+ return {
+ "positions": positions,
+ "native_filter_configuration": filters,
+ }
+
+
+def test_copy_dashboard_duplicate_slices_remaps_native_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ json_metadata = _make_sample_native_filter_metadata(
+ slices=[chart1, chart2],
+ excluded_slices=[chart2],
+ )
+
+ copy_data = {
+ "dashboard_title": "copied_dash",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ assert len(copied_slices) == 2
+ assert copied_slices["chart_1"] != chart1.id
+ assert copied_slices["chart_2"] != chart2.id
+
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+ assert len(copied_filters) == 1
+
+ assert copied_filters[0]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ assert copied_filters[0]["scope"]["excluded"] == [copied_slices["chart_2"]]
+
+
+def test_copy_dashboard_handles_dividers_and_unscoped_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ filters: list[Any] = [
+ {"id": "NATIVE_FILTER_DIVIDER-1", "type": "DIVIDER", "title": "Group A"},
+ "invalid_filter_entry",
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ },
+ {"id": "DIVIDER-2", "type": "DIVIDER"},
+ ]
+ json_metadata = {
+ "positions": {
+ f"CHART-{chart1.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart1.id}",
+ "children": [],
+ "meta": {"chartId": chart1.id, "width": 4, "height": 50},
+ },
+ f"CHART-{chart2.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart2.id}",
+ "children": [],
+ "meta": {"chartId": chart2.id, "width": 4, "height": 50},
+ },
+ },
+ "native_filter_configuration": filters,
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_with_dividers",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+
+ # Divider preserved untouched
+ assert copied_filters[0] == {
+ "id": "NATIVE_FILTER_DIVIDER-1",
+ "type": "DIVIDER",
+ "title": "Group A",
+ }
+ # Non-dict element preserved untouched
+ assert copied_filters[1] == "invalid_filter_entry"
+ # Normal native filter remapped
+ assert copied_filters[2]["scope"]["excluded"] == [copied_slices["chart_1"]]
+ assert copied_filters[2]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ # Trailing divider preserved untouched
+ assert copied_filters[3] == {"id": "DIVIDER-2", "type": "DIVIDER"}
+
+
+def test_copy_dashboard_remaps_cross_filters_and_chart_configuration(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session, slice_names=["c1", "c2", "c3"]
+ )
+ json_metadata = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_cross_filters",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+
+ # Verify global_chart_configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slices["c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slices["c1"],
+ copied_slices["c2"],
+ ]
+
+ # Verify chart_configuration key, id, and crossFilters remapping
+ new_c1_key = str(copied_slices["c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ c1_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert c1_cfg["id"] == copied_slices["c1"]
+ assert c1_cfg["crossFilters"]["scope"]["excluded"] == [copied_slices["c2"]]
+ assert c1_cfg["crossFilters"]["chartsInScope"] == [copied_slices["c3"]]
+
+
+def test_set_dash_metadata_remaps_native_filters_when_slice_ids_provided(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ metadata_payload = {
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ }
+ ],
+ "chart_configuration": {
+ str(chart1.id): {
+ "id": chart1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+ "chartsInScope": [chart2.id],
+ },
+ }
+ },
+ }
+ old_to_new = {chart1.id: 991, chart2.id: 992}
+
+ DashboardDAO.set_dash_metadata(
+ dashboard,
+ metadata_payload,
+ old_to_new_slice_ids=old_to_new,
+ )
+
+ saved_metadata = json.loads(dashboard.json_metadata)
+ saved_filter = saved_metadata["native_filter_configuration"][0]
+ assert saved_filter["scope"]["excluded"] == [991]
+ assert saved_filter["chartsInScope"] == [991, 992]
+
+ saved_chart_cfg = saved_metadata["chart_configuration"]["991"]
+ assert saved_chart_cfg["id"] == 991
+ assert saved_chart_cfg["crossFilters"]["chartsInScope"] == [992]
+
+
+def test_issue_44983_consolidated_evidence_gate(session: Session) -> None:
+ """Consolidated evidence gate for Issue 44983.
+
+ Verifies end-to-end that duplicating a dashboard with duplicate_slices=True:
+ 1. Duplicates all slices and registers them to the new dashboard.
+ 2. Completely remaps native_filter_configuration chartsInScope and scope.excluded.
+ 3. Leaves visual divider entities and non-dictionary entries uncorrupted.
+ 4. Remaps global_chart_configuration scope.excluded and chartsInScope.
+ 5. Remaps chart_configuration keys, chart IDs, and crossFilters scopes.
+ 6. Preserves the original dashboard and slice references intact.
+ """
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session,
+ slice_names=["gate_c1", "gate_c2", "gate_c3"],
+ dashboard_title="gate_source_dashboard",
+ )
+ original_c1_id = c1.id
+ original_c2_id = c2.id
+ original_c3_id = c3.id
+
+ metadata_payload = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-gate",
+ "name": "Gate Filter",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c2.id],
+ "selectedLayers": [
+ f"chart-{c2.id}-layer-0",
+ f"chart-{c3.id}-layer-1",
+ ],
+ },
+ "chartsInScope": [c1.id, c2.id, c3.id],
+ },
+ {
+ "id": "NATIVE_FILTER_DIVIDER-gate",
+ "type": "DIVIDER",
+ "title": "Gate Divider",
+ },
+ ],
+ "chart_customization_config": [
+ {
+ "id": "CUSTOMIZATION-gate",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-custom"],
+ },
+ "chartsInScope": [c2.id],
+ },
+ {
+ "id": "CUSTOMIZATION-divider",
+ "type": "CHART_CUSTOMIZATION_DIVIDER",
+ },
+ ],
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+
+ copy_data = {
+ "dashboard_title": "gate_copied_dashboard",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(metadata_payload),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dashboard = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ # 1. Duplicated slices are distinct from originals
+ copied_slice_map = {s.slice_name: s.id for s in copied_dashboard.slices}
+ assert len(copied_slice_map) == 3
+ for gate_key in ("gate_c1", "gate_c2", "gate_c3"):
+ assert copied_slice_map[gate_key] not in {
+ original_c1_id,
+ original_c2_id,
+ original_c3_id,
+ }
+
+ copied_metadata = json.loads(copied_dashboard.json_metadata)
+
+ # 2. Native filter remapping
+ gate_filter = copied_metadata["native_filter_configuration"][0]
+ assert gate_filter["scope"]["excluded"] == [copied_slice_map["gate_c2"]]
+ assert gate_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c2']}-layer-0",
+ f"chart-{copied_slice_map['gate_c3']}-layer-1",
+ ]
+ assert gate_filter["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ copied_slice_map["gate_c3"],
+ ]
+
+ # 3. Divider preservation
+ gate_divider = copied_metadata["native_filter_configuration"][1]
+ assert gate_divider["id"] == "NATIVE_FILTER_DIVIDER-gate"
+ assert gate_divider["type"] == "DIVIDER"
+ assert "scope" not in gate_divider
+
+ # 3b. Chart customization configuration remapping
+ custom_cfg = copied_metadata["chart_customization_config"][0]
+ assert custom_cfg["id"] == "CUSTOMIZATION-gate"
+ assert custom_cfg["scope"]["excluded"] == [copied_slice_map["gate_c1"]]
+ assert custom_cfg["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c1']}-layer-custom"
+ ]
+ assert custom_cfg["chartsInScope"] == [copied_slice_map["gate_c2"]]
+
+ custom_divider = copied_metadata["chart_customization_config"][1]
+ assert custom_divider["id"] == "CUSTOMIZATION-divider"
+ assert custom_divider["type"] == "CHART_CUSTOMIZATION_DIVIDER"
+ assert "scope" not in custom_divider
+
+ # 4. Global chart configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slice_map["gate_c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ ]
+
+ # 5. Per-chart configuration remapping
+ new_c1_key = str(copied_slice_map["gate_c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ chart_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert chart_cfg["id"] == copied_slice_map["gate_c1"]
+ assert chart_cfg["crossFilters"]["scope"]["excluded"] == [
+ copied_slice_map["gate_c2"]
+ ]
+ assert chart_cfg["crossFilters"]["chartsInScope"] == [copied_slice_map["gate_c3"]]
+
+ # 6. Original dashboard slices preserved untouched
+ original_slice_ids = {s.id for s in dashboard.slices}
+ assert original_slice_ids == {original_c1_id, original_c2_id, original_c3_id}
+
+
+def test_remap_selected_layers_edge_cases() -> None:
+ old_to_new = {10: 100, 20: 200}
+ # Test dictionary format
+ layers_dict = {
+ "chart-10-layer-0": True,
+ "chart-20-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+ remapped_dict = DashboardDAO._remap_selected_layers(layers_dict, old_to_new)
+ assert remapped_dict == {
+ "chart-100-layer-0": True,
+ "chart-200-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+
+ # Test list format (Superset frontend string[] standard)
+ layers_list = [
+ "chart-10-layer-0",
+ "chart-20-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+ remapped_list = DashboardDAO._remap_selected_layers(layers_list, old_to_new)
+ assert remapped_list == [
+ "chart-100-layer-0",
+ "chart-200-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+
+
+def test_remap_slice_id_list_edge_cases() -> None:
+ old_to_new = {1: 10, 2: 20}
+ raw = [1, "2", "3", "invalid", None]
+ assert DashboardDAO._remap_slice_id_list(raw, old_to_new) == [
+ 10,
+ 20,
+ "3",
+ "invalid",
+ None,
+ ]
+
+
+def test_copy_dashboard_does_not_double_remap_overlapping_ids(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2) = _make_dashboard_with_slices(session)
+ # Simulate overlapping IDs where old_to_new_slice_ids has old ID matching new ID
+ metadata = {
+ "positions": {
+ "CHART-1": {"type": "CHART", "meta": {"chartId": c1.id}},
+ "CHART-2": {"type": "CHART", "meta": {"chartId": c2.id}},
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-overlap",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-0"],
+ },
+ "chartsInScope": [c1.id, c2.id],
+ }
+ ],
+ }
+ dashboard.json_metadata = json.dumps(metadata)
+ dashboard.params = json.dumps(metadata)
+ session.commit()
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(
+ dashboard,
+ {
+ "dashboard_title": "Copied Dash",
+ "json_metadata": json.dumps(metadata),
+ "duplicate_slices": True,
+ },
+ )
+ copied_meta = json.loads(copied_dash.json_metadata)
+ copied_filter = copied_meta["native_filter_configuration"][0]
+ # Each cloned slice must have a distinct new id; remapped exactly once
+ new_slice_ids = [s.id for s in copied_dash.slices]
+ assert len(new_slice_ids) == 2
+ assert len(set(copied_filter["chartsInScope"])) == 2
+ assert set(copied_filter["chartsInScope"]) == set(new_slice_ids)
+ copied_c1_id = next(
+ s.id for s in copied_dash.slices if s.slice_name == c1.slice_name
+ )
+ assert copied_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_c1_id}-layer-0"
+ ]
+
+def test_set_dash_metadata_does_not_double_remap_overlapping_ids(
Review Comment:
Only one blank line separates this def from the previous test, and the file ends with an extra blank line. The pre-commit job fails on `ruff-format` and `fix end of files` for this PR. Could you run `pre-commit run --files superset/daos/dashboard.py tests/unit_tests/dao/dashboard_test.py` and push the result?
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #45038:
URL: https://github.com/apache/superset/pull/45038
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4210832025
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
Review Comment:
Yes. If `scope.selectedLayers` uses keys such as `chart-<old_id>-layer-0`, those keys need the same chart-ID remapping; otherwise the copied filter’s layer selection remains associated with the original chart. Remap only the chart-ID portion and preserve the layer suffix, leaving unrecognized or unmapped entries unchanged. Add a test asserting that `chart-<old_id>-layer-0` becomes `chart-<new_id>-layer-0`. This complements the existing `excluded` and `chartsInScope` remapping.
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
+
+ if isinstance(container.get("chartsInScope"), list):
+ remapped_in_scope: list[int] = []
+ for cid in container["chartsInScope"]:
+ try:
+ int_id = int(cid)
+ remapped_in_scope.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_in_scope.append(cid)
+ container["chartsInScope"] = remapped_in_scope
+
+ @classmethod
+ def _remap_filter_scopes(
+ cls,
+ metadata: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap filter scopes and cross-filter references in dashboard metadata.
+
+ Mutates metadata in-place to redirect slice ID references across:
+ 1. native_filter_configuration: list of native filter definitions.
+ 2. global_chart_configuration: dashboard-wide cross-filter scoping.
+ 3. chart_configuration: per-chart cross-filter scopes, keys, and chart IDs.
+
+ This ensures that after duplicating dashboard charts, all filter
+ scopes remain bound to the new chart copies instead of the originals.
+
+ :param metadata: Deserialized dashboard json_metadata dictionary.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(metadata, dict) or not old_to_new_slice_ids:
+ return
+
+ if isinstance(metadata.get("native_filter_configuration"), list):
+ for native_filter in metadata["native_filter_configuration"]:
+ cls._remap_filter_scope(native_filter, old_to_new_slice_ids)
Review Comment:
Yes. Since `chart_customization_config` entries use the same `scope.excluded` and `chartsInScope` fields, they should also be passed through `_remap_filter_scope` during duplication. Otherwise, those references remain pointed at the original charts, and scope recomputation can behave differently on the copied dashboard. Handle the configuration’s entries defensively, as with native filters, and add a test for a customization that excludes a duplicated chart. The omission is a valid gap in the current remapping.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4201123889
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
Review Comment:
**Suggestion:** `scope.selectedLayers` encodes chart IDs in its keys, but this only remaps `excluded`. After duplication, layer-scoped filters still target the original chart IDs.
**Assessment:** 🟠 `Major` · 🔁 `Occurrence: Sometimes` · 🏷️ `Incomplete implementation`
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=607105ac5dca4282a46d9f5c8a089906&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=607105ac5dca4282a46d9f5c8a089906&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/daos/dashboard.py
**Line:** 568:577
**Comment:**
*Incomplete Implementation: `scope.selectedLayers` encodes chart IDs in its keys, but this only remaps `excluded`. After duplication, layer-scoped filters still target the original chart IDs.
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%2F45038&comment_hash=5274f8bf12c4aa1c6f4074071f42b996dc973fba81284fe2133679df61eb8fa4&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45038&comment_hash=5274f8bf12c4aa1c6f4074071f42b996dc973fba81284fe2133679df61eb8fa4&reaction=dislike'>👎</a>
##########
superset/daos/dashboard.py:
##########
@@ -531,6 +535,109 @@ def favorited_ids(dashboards: list[Dashboard]) -> list[FavStar]:
.all()
]
+ @staticmethod
+ def _remap_filter_scope(
+ container: dict[str, Any] | Any,
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap scope.excluded and chartsInScope of a filter container.
+
+ This method updates in-place the chart ID references stored inside
+ a filter configuration container. Both native filters and cross-filter
+ scopes store denormalized lists of chart IDs in chartsInScope and
+ scope.excluded. When duplicate_slices is requested during dashboard
+ copy, these identifiers must point to the newly cloned slice IDs.
+
+ Non-dictionary elements, visual dividers (type DIVIDER or IDs starting
+ with NATIVE_FILTER_DIVIDER), and non-list attributes are skipped safely.
+
+ :param container: Dictionary holding filter scope or cross-filter
+ configuration.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(container, dict):
+ return
+
+ # Skip divider entities which represent visual section dividers in filter bar
+ if container.get("type") == "DIVIDER" or str(
+ container.get("id", "")
+ ).startswith(("NATIVE_FILTER_DIVIDER", "DIVIDER")):
+ return
+
+ scope = container.get("scope")
+ if isinstance(scope, dict) and isinstance(scope.get("excluded"), list):
+ remapped_excluded: list[int] = []
+ for cid in scope["excluded"]:
+ try:
+ int_id = int(cid)
+ remapped_excluded.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_excluded.append(cid)
+ scope["excluded"] = remapped_excluded
+
+ if isinstance(container.get("chartsInScope"), list):
+ remapped_in_scope: list[int] = []
+ for cid in container["chartsInScope"]:
+ try:
+ int_id = int(cid)
+ remapped_in_scope.append(old_to_new_slice_ids.get(int_id, int_id))
+ except (ValueError, TypeError):
+ remapped_in_scope.append(cid)
+ container["chartsInScope"] = remapped_in_scope
+
+ @classmethod
+ def _remap_filter_scopes(
+ cls,
+ metadata: dict[str, Any],
+ old_to_new_slice_ids: dict[int, int],
+ ) -> None:
+ """Remap filter scopes and cross-filter references in dashboard metadata.
+
+ Mutates metadata in-place to redirect slice ID references across:
+ 1. native_filter_configuration: list of native filter definitions.
+ 2. global_chart_configuration: dashboard-wide cross-filter scoping.
+ 3. chart_configuration: per-chart cross-filter scopes, keys, and chart IDs.
+
+ This ensures that after duplicating dashboard charts, all filter
+ scopes remain bound to the new chart copies instead of the originals.
+
+ :param metadata: Deserialized dashboard json_metadata dictionary.
+ :param old_to_new_slice_ids: Mapping from original chart ID to
+ duplicated chart ID.
+ """
+ if not isinstance(metadata, dict) or not old_to_new_slice_ids:
+ return
+
+ if isinstance(metadata.get("native_filter_configuration"), list):
+ for native_filter in metadata["native_filter_configuration"]:
+ cls._remap_filter_scope(native_filter, old_to_new_slice_ids)
Review Comment:
**Suggestion:** `chart_customization_config` also stores scope references, but this remaps only native filters. Customization exclusions and cached targets can therefore still point to original charts after duplication.
**Assessment:** 🟠 `Major` · 🔁 `Occurrence: Sometimes` · 🏷️ `Incomplete implementation`
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b41675985bdb4043ba7950da44d46d70&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b41675985bdb4043ba7950da44d46d70&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/daos/dashboard.py
**Line:** 612:614
**Comment:**
*Incomplete Implementation: `chart_customization_config` also stores scope references, but this remaps only native filters. Customization exclusions and cached targets can therefore still point to original charts after duplication.
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%2F45038&comment_hash=4e0cb4ffa3fbdce66ec11fca7abcc337da1cc661e89385a201caaded88020359&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F45038&comment_hash=4e0cb4ffa3fbdce66ec11fca7abcc337da1cc661e89385a201caaded88020359&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4253919423
##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -552,3 +552,567 @@ def test_set_dash_metadata_keeps_archived_trapped_chart_through_resave(
with skip_visibility_filter(db.session, Slice):
db.session.expire(dashboard, ["slices"])
assert {chart.id for chart in dashboard.slices} == {placed.id, trapped.id}
+
+
+def _make_dashboard_with_slices(
+ session: Session,
+ slice_names: list[str] | None = None,
+ dashboard_title: str = "original_dash",
+) -> tuple[Dashboard, list[Slice]]:
+ Dashboard.metadata.create_all(session.get_bind())
+ dataset = SqlaTable(
+ table_name="dao_test_table",
+ database=Database(database_name="dao_test_db", sqlalchemy_uri="sqlite://"),
+ )
+ db.session.add(dataset)
+ db.session.flush()
+
+ names = slice_names or ["chart_1", "chart_2"]
+ slices = [
+ Slice(
+ slice_name=name,
+ datasource_id=dataset.id,
+ datasource_type="table",
+ )
+ for name in names
+ ]
+ dashboard = Dashboard(
+ dashboard_title=dashboard_title,
+ slices=slices,
+ published=True,
+ )
+ db.session.add_all([*slices, dashboard])
+ db.session.flush()
+ return dashboard, slices
+
+
+def _make_sample_native_filter_metadata(
+ slices: list[Slice],
+ excluded_slices: list[Slice] | None = None,
+ extra_filters: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ positions = {
+ f"CHART-{slc.id}": {
+ "type": "CHART",
+ "id": f"CHART-{slc.id}",
+ "children": [],
+ "meta": {"chartId": slc.id, "width": 4, "height": 50},
+ }
+ for slc in slices
+ }
+ excluded_ids = [s.id for s in excluded_slices] if excluded_slices else []
+ filters: list[dict[str, Any]] = [
+ {
+ "id": "NATIVE_FILTER-1",
+ "name": "Filter 1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": excluded_ids},
+ "chartsInScope": [s.id for s in slices],
+ }
+ ]
+ if extra_filters:
+ filters.extend(extra_filters)
+ return {
+ "positions": positions,
+ "native_filter_configuration": filters,
+ }
+
+
+def test_copy_dashboard_duplicate_slices_remaps_native_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ json_metadata = _make_sample_native_filter_metadata(
+ slices=[chart1, chart2],
+ excluded_slices=[chart2],
+ )
+
+ copy_data = {
+ "dashboard_title": "copied_dash",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ assert len(copied_slices) == 2
+ assert copied_slices["chart_1"] != chart1.id
+ assert copied_slices["chart_2"] != chart2.id
+
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+ assert len(copied_filters) == 1
+
+ assert copied_filters[0]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ assert copied_filters[0]["scope"]["excluded"] == [copied_slices["chart_2"]]
+
+
+def test_copy_dashboard_handles_dividers_and_unscoped_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ filters: list[Any] = [
+ {"id": "NATIVE_FILTER_DIVIDER-1", "type": "DIVIDER", "title": "Group A"},
+ "invalid_filter_entry",
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ },
+ {"id": "DIVIDER-2", "type": "DIVIDER"},
+ ]
+ json_metadata = {
+ "positions": {
+ f"CHART-{chart1.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart1.id}",
+ "children": [],
+ "meta": {"chartId": chart1.id, "width": 4, "height": 50},
+ },
+ f"CHART-{chart2.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart2.id}",
+ "children": [],
+ "meta": {"chartId": chart2.id, "width": 4, "height": 50},
+ },
+ },
+ "native_filter_configuration": filters,
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_with_dividers",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+
+ # Divider preserved untouched
+ assert copied_filters[0] == {
+ "id": "NATIVE_FILTER_DIVIDER-1",
+ "type": "DIVIDER",
+ "title": "Group A",
+ }
+ # Non-dict element preserved untouched
+ assert copied_filters[1] == "invalid_filter_entry"
+ # Normal native filter remapped
+ assert copied_filters[2]["scope"]["excluded"] == [copied_slices["chart_1"]]
+ assert copied_filters[2]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ # Trailing divider preserved untouched
+ assert copied_filters[3] == {"id": "DIVIDER-2", "type": "DIVIDER"}
+
+
+def test_copy_dashboard_remaps_cross_filters_and_chart_configuration(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session, slice_names=["c1", "c2", "c3"]
+ )
+ json_metadata = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_cross_filters",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+
+ # Verify global_chart_configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slices["c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slices["c1"],
+ copied_slices["c2"],
+ ]
+
+ # Verify chart_configuration key, id, and crossFilters remapping
+ new_c1_key = str(copied_slices["c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ c1_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert c1_cfg["id"] == copied_slices["c1"]
+ assert c1_cfg["crossFilters"]["scope"]["excluded"] == [copied_slices["c2"]]
+ assert c1_cfg["crossFilters"]["chartsInScope"] == [copied_slices["c3"]]
+
+
+def test_set_dash_metadata_remaps_native_filters_when_slice_ids_provided(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ metadata_payload = {
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ }
+ ],
+ "chart_configuration": {
+ str(chart1.id): {
+ "id": chart1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+ "chartsInScope": [chart2.id],
+ },
+ }
+ },
+ }
+ old_to_new = {chart1.id: 991, chart2.id: 992}
+
+ DashboardDAO.set_dash_metadata(
+ dashboard,
+ metadata_payload,
+ old_to_new_slice_ids=old_to_new,
+ )
+
+ saved_metadata = json.loads(dashboard.json_metadata)
+ saved_filter = saved_metadata["native_filter_configuration"][0]
+ assert saved_filter["scope"]["excluded"] == [991]
+ assert saved_filter["chartsInScope"] == [991, 992]
+
+ saved_chart_cfg = saved_metadata["chart_configuration"]["991"]
+ assert saved_chart_cfg["id"] == 991
+ assert saved_chart_cfg["crossFilters"]["chartsInScope"] == [992]
+
+
+def test_issue_44983_consolidated_evidence_gate(session: Session) -> None:
+ """Consolidated evidence gate for Issue 44983.
+
+ Verifies end-to-end that duplicating a dashboard with duplicate_slices=True:
+ 1. Duplicates all slices and registers them to the new dashboard.
+ 2. Completely remaps native_filter_configuration chartsInScope and scope.excluded.
+ 3. Leaves visual divider entities and non-dictionary entries uncorrupted.
+ 4. Remaps global_chart_configuration scope.excluded and chartsInScope.
+ 5. Remaps chart_configuration keys, chart IDs, and crossFilters scopes.
+ 6. Preserves the original dashboard and slice references intact.
+ """
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session,
+ slice_names=["gate_c1", "gate_c2", "gate_c3"],
+ dashboard_title="gate_source_dashboard",
+ )
+ original_c1_id = c1.id
+ original_c2_id = c2.id
+ original_c3_id = c3.id
+
+ metadata_payload = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-gate",
+ "name": "Gate Filter",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c2.id],
+ "selectedLayers": [
+ f"chart-{c2.id}-layer-0",
+ f"chart-{c3.id}-layer-1",
+ ],
+ },
+ "chartsInScope": [c1.id, c2.id, c3.id],
+ },
+ {
+ "id": "NATIVE_FILTER_DIVIDER-gate",
+ "type": "DIVIDER",
+ "title": "Gate Divider",
+ },
+ ],
+ "chart_customization_config": [
+ {
+ "id": "CUSTOMIZATION-gate",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-custom"],
+ },
+ "chartsInScope": [c2.id],
+ },
+ {
+ "id": "CUSTOMIZATION-divider",
+ "type": "CHART_CUSTOMIZATION_DIVIDER",
+ },
+ ],
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+
+ copy_data = {
+ "dashboard_title": "gate_copied_dashboard",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(metadata_payload),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dashboard = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ # 1. Duplicated slices are distinct from originals
+ copied_slice_map = {s.slice_name: s.id for s in copied_dashboard.slices}
+ assert len(copied_slice_map) == 3
+ for gate_key in ("gate_c1", "gate_c2", "gate_c3"):
+ assert copied_slice_map[gate_key] not in {
+ original_c1_id,
+ original_c2_id,
+ original_c3_id,
+ }
+
+ copied_metadata = json.loads(copied_dashboard.json_metadata)
+
+ # 2. Native filter remapping
+ gate_filter = copied_metadata["native_filter_configuration"][0]
+ assert gate_filter["scope"]["excluded"] == [copied_slice_map["gate_c2"]]
+ assert gate_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c2']}-layer-0",
+ f"chart-{copied_slice_map['gate_c3']}-layer-1",
+ ]
+ assert gate_filter["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ copied_slice_map["gate_c3"],
+ ]
+
+ # 3. Divider preservation
+ gate_divider = copied_metadata["native_filter_configuration"][1]
+ assert gate_divider["id"] == "NATIVE_FILTER_DIVIDER-gate"
+ assert gate_divider["type"] == "DIVIDER"
+ assert "scope" not in gate_divider
+
+ # 3b. Chart customization configuration remapping
+ custom_cfg = copied_metadata["chart_customization_config"][0]
+ assert custom_cfg["id"] == "CUSTOMIZATION-gate"
+ assert custom_cfg["scope"]["excluded"] == [copied_slice_map["gate_c1"]]
+ assert custom_cfg["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c1']}-layer-custom"
+ ]
+ assert custom_cfg["chartsInScope"] == [copied_slice_map["gate_c2"]]
+
+ custom_divider = copied_metadata["chart_customization_config"][1]
+ assert custom_divider["id"] == "CUSTOMIZATION-divider"
+ assert custom_divider["type"] == "CHART_CUSTOMIZATION_DIVIDER"
+ assert "scope" not in custom_divider
+
+ # 4. Global chart configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slice_map["gate_c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ ]
+
+ # 5. Per-chart configuration remapping
+ new_c1_key = str(copied_slice_map["gate_c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ chart_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert chart_cfg["id"] == copied_slice_map["gate_c1"]
+ assert chart_cfg["crossFilters"]["scope"]["excluded"] == [
+ copied_slice_map["gate_c2"]
+ ]
+ assert chart_cfg["crossFilters"]["chartsInScope"] == [copied_slice_map["gate_c3"]]
+
+ # 6. Original dashboard slices preserved untouched
+ original_slice_ids = {s.id for s in dashboard.slices}
+ assert original_slice_ids == {original_c1_id, original_c2_id, original_c3_id}
+
+
+def test_remap_selected_layers_edge_cases() -> None:
+ old_to_new = {10: 100, 20: 200}
+ # Test dictionary format
+ layers_dict = {
+ "chart-10-layer-0": True,
+ "chart-20-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+ remapped_dict = DashboardDAO._remap_selected_layers(layers_dict, old_to_new)
+ assert remapped_dict == {
+ "chart-100-layer-0": True,
+ "chart-200-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+
+ # Test list format (Superset frontend string[] standard)
+ layers_list = [
+ "chart-10-layer-0",
+ "chart-20-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+ remapped_list = DashboardDAO._remap_selected_layers(layers_list, old_to_new)
+ assert remapped_list == [
+ "chart-100-layer-0",
+ "chart-200-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+
+
+def test_remap_slice_id_list_edge_cases() -> None:
+ old_to_new = {1: 10, 2: 20}
+ raw = [1, "2", "3", "invalid", None]
+ assert DashboardDAO._remap_slice_id_list(raw, old_to_new) == [
+ 10,
+ 20,
+ "3",
+ "invalid",
+ None,
+ ]
+
+
+def test_copy_dashboard_does_not_double_remap_overlapping_ids(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2) = _make_dashboard_with_slices(session)
+ # Simulate overlapping IDs where old_to_new_slice_ids has old ID matching new ID
+ metadata = {
+ "positions": {
+ "CHART-1": {"type": "CHART", "meta": {"chartId": c1.id}},
+ "CHART-2": {"type": "CHART", "meta": {"chartId": c2.id}},
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-overlap",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-0"],
+ },
+ "chartsInScope": [c1.id, c2.id],
+ }
+ ],
+ }
+ dashboard.json_metadata = json.dumps(metadata)
+ dashboard.params = json.dumps(metadata)
+ session.commit()
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(
+ dashboard,
+ {
+ "dashboard_title": "Copied Dash",
+ "json_metadata": json.dumps(metadata),
+ "duplicate_slices": True,
+ },
+ )
+ copied_meta = json.loads(copied_dash.json_metadata)
+ copied_filter = copied_meta["native_filter_configuration"][0]
+ # Each cloned slice must have a distinct new id; remapped exactly once
+ new_slice_ids = [s.id for s in copied_dash.slices]
+ assert len(new_slice_ids) == 2
+ assert len(set(copied_filter["chartsInScope"])) == 2
+ assert set(copied_filter["chartsInScope"]) == set(new_slice_ids)
+ copied_c1_id = next(
+ s.id for s in copied_dash.slices if s.slice_name == c1.slice_name
+ )
+ assert copied_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_c1_id}-layer-0"
+ ]
+
+def test_set_dash_metadata_does_not_double_remap_overlapping_ids(
Review Comment:
The `pre-commit (current)` job is still red on this head: `auto-walrus` rewrites the `re.match` assignment and `if` in `_remap_layer_key`, and `ruff-format` reformats both files (the `_remap_selected_layers` list comprehension in `superset/daos/dashboard.py` and the end of the new overlap test here), so the check keeps failing. Could you run `pre-commit run --files superset/daos/dashboard.py tests/unit_tests/dao/dashboard_test.py` and push the result?
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(dashboard): remap native filter scopes when duplicating charts on save as [superset]
Posted by "FrancescoCastaldi (via GitHub)" <gi...@apache.org>.
FrancescoCastaldi commented on code in PR #45038:
URL: https://github.com/apache/superset/pull/45038#discussion_r4256382832
##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -552,3 +552,567 @@ def test_set_dash_metadata_keeps_archived_trapped_chart_through_resave(
with skip_visibility_filter(db.session, Slice):
db.session.expire(dashboard, ["slices"])
assert {chart.id for chart in dashboard.slices} == {placed.id, trapped.id}
+
+
+def _make_dashboard_with_slices(
+ session: Session,
+ slice_names: list[str] | None = None,
+ dashboard_title: str = "original_dash",
+) -> tuple[Dashboard, list[Slice]]:
+ Dashboard.metadata.create_all(session.get_bind())
+ dataset = SqlaTable(
+ table_name="dao_test_table",
+ database=Database(database_name="dao_test_db", sqlalchemy_uri="sqlite://"),
+ )
+ db.session.add(dataset)
+ db.session.flush()
+
+ names = slice_names or ["chart_1", "chart_2"]
+ slices = [
+ Slice(
+ slice_name=name,
+ datasource_id=dataset.id,
+ datasource_type="table",
+ )
+ for name in names
+ ]
+ dashboard = Dashboard(
+ dashboard_title=dashboard_title,
+ slices=slices,
+ published=True,
+ )
+ db.session.add_all([*slices, dashboard])
+ db.session.flush()
+ return dashboard, slices
+
+
+def _make_sample_native_filter_metadata(
+ slices: list[Slice],
+ excluded_slices: list[Slice] | None = None,
+ extra_filters: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ positions = {
+ f"CHART-{slc.id}": {
+ "type": "CHART",
+ "id": f"CHART-{slc.id}",
+ "children": [],
+ "meta": {"chartId": slc.id, "width": 4, "height": 50},
+ }
+ for slc in slices
+ }
+ excluded_ids = [s.id for s in excluded_slices] if excluded_slices else []
+ filters: list[dict[str, Any]] = [
+ {
+ "id": "NATIVE_FILTER-1",
+ "name": "Filter 1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": excluded_ids},
+ "chartsInScope": [s.id for s in slices],
+ }
+ ]
+ if extra_filters:
+ filters.extend(extra_filters)
+ return {
+ "positions": positions,
+ "native_filter_configuration": filters,
+ }
+
+
+def test_copy_dashboard_duplicate_slices_remaps_native_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ json_metadata = _make_sample_native_filter_metadata(
+ slices=[chart1, chart2],
+ excluded_slices=[chart2],
+ )
+
+ copy_data = {
+ "dashboard_title": "copied_dash",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ assert len(copied_slices) == 2
+ assert copied_slices["chart_1"] != chart1.id
+ assert copied_slices["chart_2"] != chart2.id
+
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+ assert len(copied_filters) == 1
+
+ assert copied_filters[0]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ assert copied_filters[0]["scope"]["excluded"] == [copied_slices["chart_2"]]
+
+
+def test_copy_dashboard_handles_dividers_and_unscoped_filters(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ filters: list[Any] = [
+ {"id": "NATIVE_FILTER_DIVIDER-1", "type": "DIVIDER", "title": "Group A"},
+ "invalid_filter_entry",
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ },
+ {"id": "DIVIDER-2", "type": "DIVIDER"},
+ ]
+ json_metadata = {
+ "positions": {
+ f"CHART-{chart1.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart1.id}",
+ "children": [],
+ "meta": {"chartId": chart1.id, "width": 4, "height": 50},
+ },
+ f"CHART-{chart2.id}": {
+ "type": "CHART",
+ "id": f"CHART-{chart2.id}",
+ "children": [],
+ "meta": {"chartId": chart2.id, "width": 4, "height": 50},
+ },
+ },
+ "native_filter_configuration": filters,
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_with_dividers",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+ copied_filters = copied_metadata["native_filter_configuration"]
+
+ # Divider preserved untouched
+ assert copied_filters[0] == {
+ "id": "NATIVE_FILTER_DIVIDER-1",
+ "type": "DIVIDER",
+ "title": "Group A",
+ }
+ # Non-dict element preserved untouched
+ assert copied_filters[1] == "invalid_filter_entry"
+ # Normal native filter remapped
+ assert copied_filters[2]["scope"]["excluded"] == [copied_slices["chart_1"]]
+ assert copied_filters[2]["chartsInScope"] == [
+ copied_slices["chart_1"],
+ copied_slices["chart_2"],
+ ]
+ # Trailing divider preserved untouched
+ assert copied_filters[3] == {"id": "DIVIDER-2", "type": "DIVIDER"}
+
+
+def test_copy_dashboard_remaps_cross_filters_and_chart_configuration(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session, slice_names=["c1", "c2", "c3"]
+ )
+ json_metadata = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+ copy_data = {
+ "dashboard_title": "copied_dash_cross_filters",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(json_metadata),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ copied_slices = {s.slice_name: s.id for s in copied_dash.slices}
+ copied_metadata = json.loads(copied_dash.json_metadata)
+
+ # Verify global_chart_configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slices["c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slices["c1"],
+ copied_slices["c2"],
+ ]
+
+ # Verify chart_configuration key, id, and crossFilters remapping
+ new_c1_key = str(copied_slices["c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ c1_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert c1_cfg["id"] == copied_slices["c1"]
+ assert c1_cfg["crossFilters"]["scope"]["excluded"] == [copied_slices["c2"]]
+ assert c1_cfg["crossFilters"]["chartsInScope"] == [copied_slices["c3"]]
+
+
+def test_set_dash_metadata_remaps_native_filters_when_slice_ids_provided(
+ session: Session,
+) -> None:
+ dashboard, (chart1, chart2) = _make_dashboard_with_slices(session)
+ metadata_payload = {
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-1",
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [chart1.id]},
+ "chartsInScope": [chart1.id, chart2.id],
+ }
+ ],
+ "chart_configuration": {
+ str(chart1.id): {
+ "id": chart1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": []},
+ "chartsInScope": [chart2.id],
+ },
+ }
+ },
+ }
+ old_to_new = {chart1.id: 991, chart2.id: 992}
+
+ DashboardDAO.set_dash_metadata(
+ dashboard,
+ metadata_payload,
+ old_to_new_slice_ids=old_to_new,
+ )
+
+ saved_metadata = json.loads(dashboard.json_metadata)
+ saved_filter = saved_metadata["native_filter_configuration"][0]
+ assert saved_filter["scope"]["excluded"] == [991]
+ assert saved_filter["chartsInScope"] == [991, 992]
+
+ saved_chart_cfg = saved_metadata["chart_configuration"]["991"]
+ assert saved_chart_cfg["id"] == 991
+ assert saved_chart_cfg["crossFilters"]["chartsInScope"] == [992]
+
+
+def test_issue_44983_consolidated_evidence_gate(session: Session) -> None:
+ """Consolidated evidence gate for Issue 44983.
+
+ Verifies end-to-end that duplicating a dashboard with duplicate_slices=True:
+ 1. Duplicates all slices and registers them to the new dashboard.
+ 2. Completely remaps native_filter_configuration chartsInScope and scope.excluded.
+ 3. Leaves visual divider entities and non-dictionary entries uncorrupted.
+ 4. Remaps global_chart_configuration scope.excluded and chartsInScope.
+ 5. Remaps chart_configuration keys, chart IDs, and crossFilters scopes.
+ 6. Preserves the original dashboard and slice references intact.
+ """
+ dashboard, (c1, c2, c3) = _make_dashboard_with_slices(
+ session,
+ slice_names=["gate_c1", "gate_c2", "gate_c3"],
+ dashboard_title="gate_source_dashboard",
+ )
+ original_c1_id = c1.id
+ original_c2_id = c2.id
+ original_c3_id = c3.id
+
+ metadata_payload = {
+ "positions": {
+ f"CHART-{c.id}": {
+ "type": "CHART",
+ "id": f"CHART-{c.id}",
+ "children": [],
+ "meta": {"chartId": c.id, "width": 4, "height": 50},
+ }
+ for c in (c1, c2, c3)
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-gate",
+ "name": "Gate Filter",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c2.id],
+ "selectedLayers": [
+ f"chart-{c2.id}-layer-0",
+ f"chart-{c3.id}-layer-1",
+ ],
+ },
+ "chartsInScope": [c1.id, c2.id, c3.id],
+ },
+ {
+ "id": "NATIVE_FILTER_DIVIDER-gate",
+ "type": "DIVIDER",
+ "title": "Gate Divider",
+ },
+ ],
+ "chart_customization_config": [
+ {
+ "id": "CUSTOMIZATION-gate",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-custom"],
+ },
+ "chartsInScope": [c2.id],
+ },
+ {
+ "id": "CUSTOMIZATION-divider",
+ "type": "CHART_CUSTOMIZATION_DIVIDER",
+ },
+ ],
+ "global_chart_configuration": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c3.id]},
+ "chartsInScope": [c1.id, c2.id],
+ },
+ "chart_configuration": {
+ str(c1.id): {
+ "id": c1.id,
+ "crossFilters": {
+ "scope": {"rootPath": ["ROOT_ID"], "excluded": [c2.id]},
+ "chartsInScope": [c3.id],
+ },
+ }
+ },
+ }
+
+ copy_data = {
+ "dashboard_title": "gate_copied_dashboard",
+ "duplicate_slices": True,
+ "json_metadata": json.dumps(metadata_payload),
+ }
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dashboard = DashboardDAO.copy_dashboard(dashboard, copy_data)
+
+ # 1. Duplicated slices are distinct from originals
+ copied_slice_map = {s.slice_name: s.id for s in copied_dashboard.slices}
+ assert len(copied_slice_map) == 3
+ for gate_key in ("gate_c1", "gate_c2", "gate_c3"):
+ assert copied_slice_map[gate_key] not in {
+ original_c1_id,
+ original_c2_id,
+ original_c3_id,
+ }
+
+ copied_metadata = json.loads(copied_dashboard.json_metadata)
+
+ # 2. Native filter remapping
+ gate_filter = copied_metadata["native_filter_configuration"][0]
+ assert gate_filter["scope"]["excluded"] == [copied_slice_map["gate_c2"]]
+ assert gate_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c2']}-layer-0",
+ f"chart-{copied_slice_map['gate_c3']}-layer-1",
+ ]
+ assert gate_filter["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ copied_slice_map["gate_c3"],
+ ]
+
+ # 3. Divider preservation
+ gate_divider = copied_metadata["native_filter_configuration"][1]
+ assert gate_divider["id"] == "NATIVE_FILTER_DIVIDER-gate"
+ assert gate_divider["type"] == "DIVIDER"
+ assert "scope" not in gate_divider
+
+ # 3b. Chart customization configuration remapping
+ custom_cfg = copied_metadata["chart_customization_config"][0]
+ assert custom_cfg["id"] == "CUSTOMIZATION-gate"
+ assert custom_cfg["scope"]["excluded"] == [copied_slice_map["gate_c1"]]
+ assert custom_cfg["scope"]["selectedLayers"] == [
+ f"chart-{copied_slice_map['gate_c1']}-layer-custom"
+ ]
+ assert custom_cfg["chartsInScope"] == [copied_slice_map["gate_c2"]]
+
+ custom_divider = copied_metadata["chart_customization_config"][1]
+ assert custom_divider["id"] == "CUSTOMIZATION-divider"
+ assert custom_divider["type"] == "CHART_CUSTOMIZATION_DIVIDER"
+ assert "scope" not in custom_divider
+
+ # 4. Global chart configuration remapping
+ global_cfg = copied_metadata["global_chart_configuration"]
+ assert global_cfg["scope"]["excluded"] == [copied_slice_map["gate_c3"]]
+ assert global_cfg["chartsInScope"] == [
+ copied_slice_map["gate_c1"],
+ copied_slice_map["gate_c2"],
+ ]
+
+ # 5. Per-chart configuration remapping
+ new_c1_key = str(copied_slice_map["gate_c1"])
+ assert new_c1_key in copied_metadata["chart_configuration"]
+ chart_cfg = copied_metadata["chart_configuration"][new_c1_key]
+ assert chart_cfg["id"] == copied_slice_map["gate_c1"]
+ assert chart_cfg["crossFilters"]["scope"]["excluded"] == [
+ copied_slice_map["gate_c2"]
+ ]
+ assert chart_cfg["crossFilters"]["chartsInScope"] == [copied_slice_map["gate_c3"]]
+
+ # 6. Original dashboard slices preserved untouched
+ original_slice_ids = {s.id for s in dashboard.slices}
+ assert original_slice_ids == {original_c1_id, original_c2_id, original_c3_id}
+
+
+def test_remap_selected_layers_edge_cases() -> None:
+ old_to_new = {10: 100, 20: 200}
+ # Test dictionary format
+ layers_dict = {
+ "chart-10-layer-0": True,
+ "chart-20-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+ remapped_dict = DashboardDAO._remap_selected_layers(layers_dict, old_to_new)
+ assert remapped_dict == {
+ "chart-100-layer-0": True,
+ "chart-200-layer-sub1": False,
+ "chart-30-layer-0": "unmapped",
+ "custom-key": 123,
+ }
+
+ # Test list format (Superset frontend string[] standard)
+ layers_list = [
+ "chart-10-layer-0",
+ "chart-20-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+ remapped_list = DashboardDAO._remap_selected_layers(layers_list, old_to_new)
+ assert remapped_list == [
+ "chart-100-layer-0",
+ "chart-200-layer-sub1",
+ "chart-30-layer-0",
+ "custom-key",
+ ]
+
+
+def test_remap_slice_id_list_edge_cases() -> None:
+ old_to_new = {1: 10, 2: 20}
+ raw = [1, "2", "3", "invalid", None]
+ assert DashboardDAO._remap_slice_id_list(raw, old_to_new) == [
+ 10,
+ 20,
+ "3",
+ "invalid",
+ None,
+ ]
+
+
+def test_copy_dashboard_does_not_double_remap_overlapping_ids(
+ session: Session,
+) -> None:
+ dashboard, (c1, c2) = _make_dashboard_with_slices(session)
+ # Simulate overlapping IDs where old_to_new_slice_ids has old ID matching new ID
+ metadata = {
+ "positions": {
+ "CHART-1": {"type": "CHART", "meta": {"chartId": c1.id}},
+ "CHART-2": {"type": "CHART", "meta": {"chartId": c2.id}},
+ },
+ "native_filter_configuration": [
+ {
+ "id": "NATIVE_FILTER-overlap",
+ "scope": {
+ "rootPath": ["ROOT_ID"],
+ "excluded": [c1.id],
+ "selectedLayers": [f"chart-{c1.id}-layer-0"],
+ },
+ "chartsInScope": [c1.id, c2.id],
+ }
+ ],
+ }
+ dashboard.json_metadata = json.dumps(metadata)
+ dashboard.params = json.dumps(metadata)
+ session.commit()
+
+ with (
+ patch.object(security_manager, "is_editor", return_value=True),
+ patch("superset.daos.dashboard.g") as mock_g,
+ ):
+ mock_g.user = None
+ copied_dash = DashboardDAO.copy_dashboard(
+ dashboard,
+ {
+ "dashboard_title": "Copied Dash",
+ "json_metadata": json.dumps(metadata),
+ "duplicate_slices": True,
+ },
+ )
+ copied_meta = json.loads(copied_dash.json_metadata)
+ copied_filter = copied_meta["native_filter_configuration"][0]
+ # Each cloned slice must have a distinct new id; remapped exactly once
+ new_slice_ids = [s.id for s in copied_dash.slices]
+ assert len(new_slice_ids) == 2
+ assert len(set(copied_filter["chartsInScope"])) == 2
+ assert set(copied_filter["chartsInScope"]) == set(new_slice_ids)
+ copied_c1_id = next(
+ s.id for s in copied_dash.slices if s.slice_name == c1.slice_name
+ )
+ assert copied_filter["scope"]["selectedLayers"] == [
+ f"chart-{copied_c1_id}-layer-0"
+ ]
+
+def test_set_dash_metadata_does_not_double_remap_overlapping_ids(
Review Comment:
Applied auto-walrus syntax in _remap_layer_key and formatted both superset/daos/dashboard.py and tests/unit_tests/dao/dashboard_test.py with ruff-format in commit efe8edf.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org