You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "mikebridge (via GitHub)" <gi...@apache.org> on 2026/05/14 22:04:19 UTC

[PR] feat(charts): soft-delete and restore (sc-106189) [superset]

mikebridge opened a new pull request, #40129:
URL: https://github.com/apache/superset/pull/40129

   ### SUMMARY
   
   Wire **charts** to the soft-delete infrastructure shipped in #39977 (sc-106188). One of three entity rollouts (charts / dashboards / datasets) decomposing the soft-delete work per [SIP-208](https://github.com/apache/superset/issues/39464) (passed 2026-05-08).
   
   **Depends on #39977 — do not merge until that PR is in master.** This PR consumes the abstractions (`SoftDeleteMixin`, `BaseRestoreCommand`, `BaseDeletedStateFilter`, `SoftDeleteApiMixin`, `find_existing_for_import` / `clear_soft_deleted_for_import`) and wires them to `Slice`.
   
   #### What this PR ships
   
   **Migration** (`superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py`)
   
   - `revision = 7c4a8d09ca37`, `down_revision = 33d7e0e21daa`. Adds a nullable `deleted_at` column and `ix_slices_deleted_at` index to `slices`. Reversible. Uses `superset.migrations.shared.utils` helpers so the migration is idempotent.
   - **Note**: this PR shares `down_revision = 33d7e0e21daa` with the dashboards (sc-106190 / #40128) and datasets (sc-106191) sibling PRs. Whichever lands second/third will need a rebase or merge migration.
   
   **Model + DAO**
   
   - `Slice` inherits `SoftDeleteMixin` (`superset/models/slice.py`). The `do_orm_execute` listener from the infrastructure PR begins filtering `Slice` queries (including relationship lazy loads, via `with_loader_criteria(..., propagate_to_loaders=True)`).
   - `DeleteChartCommand` routes through `BaseDAO.delete()` — which now detects the mixin and dispatches to `soft_delete()` — so no source change to the delete command is needed.
   
   **API**
   
   - `RestoreChartCommand` (`superset/commands/chart/restore.py`) — 4 ClassVar declarations subclassing `BaseRestoreCommand[Slice]`. No method overrides; the base class owns validation, ownership checks, and the transactional wrapper.
   - `POST /api/v1/chart/<uuid>/restore` endpoint (`superset/charts/api.py`) with the standard decorator stack (`@protect`, `@safe`, `@statsd_metrics`, `@event_logger.log_this_with_context`). Permission model mirrors delete exactly: endpoint-level `can_write`, resource-level `raise_for_ownership`. UUIDs in the path per the new-endpoints convention.
   - `ChartDeletedStateFilter` (`superset/charts/filters.py`) — 2-line subclass of `BaseDeletedStateFilter` setting `arg_name = "chart_deleted_state"` and `model = Slice`. Wired into `search_filters` on `ChartRestApi`.
   - `ChartRestApi` gains `SoftDeleteApiMixin` and `"restore"` is added to `include_route_methods`.
   - `ChartRestoreFailedError` exception type added (`superset/commands/chart/exceptions.py`).
   
   **Import pipeline** (`superset/commands/chart/importers/v1/utils.py`)
   
   - Updates `import_chart` to use the infrastructure's `find_existing_for_import` (pure lookup) + `clear_soft_deleted_for_import` (explicit destructive cleanup). The destructive call happens **after** the overwrite + permission check passes, so a soft-deleted match can't be quietly hard-deleted before the import command decides whether it has the right to proceed.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   No UI changes in this PR — REST endpoints only. The frontend "Restore" button is a follow-up PR.
   
   | Endpoint | Before | After |
   |---|---|---|
   | `DELETE /api/v1/chart/<pk>` | Hard-deletes the row | Sets `deleted_at`; row remains but is hidden from default queries |
   | `GET /api/v1/chart/?...&chart_deleted_state=only` | Filter doesn't exist (400) | Returns soft-deleted charts with `deleted_at` populated |
   | `GET /api/v1/chart/?...&chart_deleted_state=include` | Filter doesn't exist (400) | Returns live + soft-deleted; `deleted_at` populated on deleted rows |
   | `POST /api/v1/chart/<uuid>/restore` | 404 (no such endpoint) | Clears `deleted_at` on the soft-deleted row |
   
   ### TESTING INSTRUCTIONS
   
   ```bash
   # Unit tests
   pytest tests/unit_tests/commands/chart/restore_test.py -v
   
   # Integration tests
   pytest tests/integration_tests/charts/soft_delete_tests.py -v
   ```
   
   The integration suite covers:
   
   - DELETE sets `deleted_at` instead of removing the row
   - Soft-deleted charts excluded from default list and from individual GET (404)
   - `chart_deleted_state=only` returns soft-deleted with `deleted_at` populated
   - `chart_deleted_state=include` returns both, response augmented
   - POST restore clears `deleted_at` (admin and owner paths)
   - Restore returns 403 for non-owners (via `raise_for_ownership`)
   - Restore returns 404 for non-existent or already-live charts
   - Re-import of a soft-deleted UUID via the v1 importer succeeds (and only after permission check)
   - Charts blocked by an active alert/report don't get soft-deleted (existing protection still applies)
   
   ### ADDITIONAL INFORMATION
   
   - [X] Has associated issue: [sc-106189](https://app.shortcut.com/preset/story/106189), [SIP-208 #39464](https://github.com/apache/superset/issues/39464)
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [X] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [X] Migration is atomic, supports rollback & is backwards-compatible (nullable column + index; downgrade reverses both)
     - [X] Confirm DB migration upgrade and downgrade tested
     - [X] Runtime estimates and downtime expectations provided — *additive only: nullable column with no default + a single-column index on the `slices` table. Even on large deployments, adding a nullable column with no default is instant on Postgres 11+ and MySQL 8+. The index build is the only meaningful cost; on a 1M-row `slices` table, expect a few seconds with `ALGORITHM=INPLACE, LOCK=NONE` (MySQL/InnoDB) or non-blocking on Postgres for a small column. No lock-holding for typical deployments.*
   - [X] Introduces new feature or API — soft-delete behaviour, `chart_deleted_state` rison filter, `POST /api/v1/chart/<uuid>/restore` endpoint, `deleted_at` field on list responses when augmentation is opted into
   - [ ] Removes existing feature or API
   
   #### Behaviour changes worth flagging
   
   - **`DELETE /api/v1/chart/<pk>` is now soft.** Existing API consumers that called DELETE expecting permanent removal will see the chart reappear if it's restored. The row is no longer findable via the default API after DELETE (the listener hides it), so most downstream behaviour is preserved — but anyone doing direct DB queries on the `slices` table will see the row.
   - **Dashboards referencing a soft-deleted chart** still render their chart slots; the slot shows a missing-chart placeholder (the existing behaviour for any unfound chart). Soft-delete does **not** cascade per SIP-208 V1.
   
   #### Depends on
   
   - #39977 (infrastructure)
   
   #### Coordination with sibling PRs
   
   This PR's migration shares `down_revision = 33d7e0e21daa` with:
   
   - #40128 (sc-106190 dashboards) — `9e1f3b8c4d2a`
   - sc-106191 datasets — `3a8e6f2c1b95`
   
   The first of the three to merge keeps its `down_revision`; the others will need a rebase or a merge migration.
   


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4848685264

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510307878


##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = None  # not soft-deleted
+
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=chart):
+        cmd = RestoreChartCommand("1")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_chart_forbidden_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartForbiddenError on permission check."""
+    chart = MagicMock()

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy.orm.session import Session
+
+
+def test_set_dash_metadata_preserves_soft_deleted_members(
+    session: Session,
+) -> None:
+    """Saving a dashboard must not sever a soft-deleted member chart.
+
+    ``set_dash_metadata`` rebuilds ``dashboard.slices`` wholesale from the
+    incoming position data. The slice-resolution query must bypass the
+    soft-delete visibility filter: with the filter active, a member chart
+    sitting in the trash would be silently dropped from the assignment —
+    deleting its ``dashboard_slices`` junction row (breaking the
+    restore-reattach contract) and writing ``uuid: None`` into its
+    position slot. This test fails if the bypass is removed.
+    """
+    from superset import db
+    from superset.connectors.sqla.models import Database, SqlaTable
+    from superset.daos.dashboard import DashboardDAO
+    from superset.models.dashboard import Dashboard
+    from superset.models.slice import Slice
+
+    Dashboard.metadata.create_all(session.get_bind())
+
+    dataset = SqlaTable(
+        table_name="dash_meta_table",
+        database=Database(database_name="dash_meta_db", sqlalchemy_uri="sqlite://"),
+    )
+    db.session.add(dataset)
+    db.session.flush()
+
+    live_chart = Slice(
+        slice_name="live_chart",
+        datasource_id=dataset.id,
+        datasource_type="table",
+    )
+    trashed_chart = Slice(
+        slice_name="trashed_chart",
+        datasource_id=dataset.id,
+        datasource_type="table",
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )
+    dashboard = Dashboard(
+        dashboard_title="meta_test_dash",
+        slices=[live_chart, trashed_chart],
+        published=True,
+    )
+    db.session.add_all([live_chart, trashed_chart, dashboard])
+    db.session.flush()
+
+    positions: dict[str, dict[str, Any]] = {
+        "CHART-live": {
+            "type": "CHART",
+            "id": "CHART-live",
+            "children": [],
+            "meta": {"chartId": live_chart.id, "width": 4, "height": 50},
+        },
+        "CHART-trashed": {
+            "type": "CHART",
+            "id": "CHART-trashed",
+            "children": [],
+            "meta": {"chartId": trashed_chart.id, "width": 4, "height": 50},
+        },
+    }
+
+    DashboardDAO.set_dash_metadata(dashboard, {"positions": positions})
+
+    member_ids = {chart.id for chart in dashboard.slices}

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
superset/models/slice.py:
##########
@@ -67,7 +71,7 @@
 
 
 class Slice(  # pylint: disable=too-many-public-methods
-    CoreChart, AuditMixinNullable, ImportExportMixin
+    CoreChart, SoftDeleteMixin, AuditMixinNullable, ImportExportMixin

Review Comment:
   Factually out of date: `BaseDAO.delete` routes to `soft_delete()` **only when** `is_feature_enabled("SOFT_DELETE")` — the gate merged to master via #41166 (2026-07-01) and this branch is rebased onto it. With the flag off (the default), chart deletes remain permanent hard deletes; adding `SoftDeleteMixin` alone changes nothing. The UPDATING.md section and the delete/bulk_delete OpenAPI docstrings now state the flag gate explicitly. Declining.



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,21 +49,107 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    # `user` is None for background / example-loader paths (no Flask request
+    # user). Combined with ``can_write=True`` (typically from
+    # ``ignore_permissions=True``), the ownership checks in the restore /
+    # overwrite branches below are intentionally skipped because the caller has
+    # already established trust at the command level.
     user = get_user()
-    if existing:
-        if overwrite and can_write and user:
-            if not security_manager.can_access_chart(existing) or (
-                user not in existing.owners and not security_manager.is_admin()
+
+    if existing := find_existing_for_import(Slice, config["uuid"]):

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
superset/translations/pt_BR/LC_MESSAGES/messages.po:
##########
@@ -3194,6 +3194,9 @@ msgstr "Alterações no gráfico"
 msgid "Chart could not be created."
 msgstr "Não foi possível criar o gráfico."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/commands/report/exceptions.py:
##########
@@ -225,6 +225,13 @@ class ReportScheduleExecuteUnexpectedError(CommandException):
     message = _("Report Schedule execution got an unexpected error.")
 
 
+class ReportScheduleTargetChartDeletedError(CommandException):

Review Comment:
   Deliberate, matching the documented precedent on `ReportScheduleExecutorNotFoundError` in this same file: this exception is raised inside the Celery report executor (not an HTTP route), where the status drives `get_logger_from_status` — 5xx marks the task FAILURE and keeps the broken report visible to ops task-state alerting, while 4xx would log a WARNING and hide it. A report that will fail every scheduled run until the chart is restored/re-pointed should surface as FAILURE. Declining.



##########
superset/translations/fr/LC_MESSAGES/messages.po:
##########
@@ -3117,6 +3117,9 @@ msgstr "Changements de graphique"
 msgid "Chart could not be created."
 msgstr "Le graphique n'a pas pu être créé."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/daos/dashboard.py:
##########
@@ -276,11 +277,30 @@ def set_dash_metadata(
                 if isinstance(value, dict)
             ]
 
-            current_slices = (
-                db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
-            )
-
-            dashboard.slices = current_slices
+            # Bypass the soft-delete visibility filter when resolving the
+            # incoming chart ids: a dashboard's ``position_json`` may still
+            # reference a chart that is currently soft-deleted, and this
+            # assignment REBUILDS ``dashboard.slices`` wholesale. With the
+            # filter active, the hidden member would be silently dropped —
+            # deleting its ``dashboard_slices`` junction row (breaking the
+            # documented restore-reattach contract) and writing
+            # ``uuid: None`` into its position slot via ``uuid_map`` below.
+            #
+            # The bypass must be session-scoped and cover the ASSIGNMENT,
+            # not just the resolution query: assigning to
+            # ``dashboard.slices`` makes the unit of work diff the new
+            # collection against the existing one, which it lazy-loads at
+            # that moment. A filtered baseline load would exclude the
+            # trashed member, so the diff would treat it as net-new and
+            # INSERT a ``dashboard_slices`` row that still exists (soft
+            # delete never removes junction rows) — an IntegrityError on
+            # the composite primary key on every save of a dashboard
+            # containing a trashed chart.
+            with skip_visibility_filter(db.session, Slice):
+                current_slices = (
+                    db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
+                )

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342334884


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   **BLOCKER — inline import without circular-import justification (Scan 1, Rule 6)**
   
   `from superset.commands.importers.v1.utils import find_existing_for_import` is placed inside the function body with no comment.
   
   I traced the full import chain: `superset.commands.importers.v1.utils` imports only `superset.{db, models.core, models.dashboard, models.helpers, tags.models, utils, commands.importers.exceptions, databases.ssh_tunnel.models, extensions}` — none of which import from `superset.commands.chart.importers.v1.utils`. **No cycle exists.**
   
   Move to module top-level alongside the existing imports at lines 19–28.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4607708863

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3390998336


##########
superset/translations/uk/LC_MESSAGES/messages.po:
##########
@@ -3052,6 +3052,9 @@ msgstr "Зміни діаграми"
 msgid "Chart could not be created."
 msgstr "Не вдалося створити діаграму."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Ukrainian translation</b></div>
   <div id="fix">
   
   The new `msgid "Chart could not be restored."` at line 3055 has an empty `msgstr ""` at line 3056. Ukrainian users will see the untranslated English error message. Following the established pattern (e.g., line 3053: "Не вдалося створити діаграму."), the translation should be "Не вдалося відновити діаграму.".
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #5efa5f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342339912


##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,406 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import ADMIN_USERNAME, ALPHA_USERNAME
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self):

Review Comment:
   **NIT (×2) — missing `-> None` on all test methods + cleanup not guarded against failure**
   
   **1. Missing return types (Scan 11)**
   All 12 test methods in this file are missing `-> None`. Affected lines: 58, 81, 95, 111, 135, 159, 174, 240, 258, 266, 280, 378.
   Example fix: `def test_delete_chart_soft_deletes(self) -> None:`
   The unit tests in `restore_test.py` already follow this convention.
   
   **2. Cleanup not guarded against assertion failure**
   Each test calls `_hard_delete_chart(chart_id)` as a trailing statement. If any assertion fails beforehand, the chart is orphaned in the test DB.
   
   Pattern: add `self.addCleanup(_hard_delete_chart, chart.id)` immediately after creating the chart so cleanup runs unconditionally even when the test raises. Applies to every test method in both `TestChartSoftDelete` and `TestChartRestore`.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342338608


##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 33d7e0e21daa
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "33d7e0e21daa"

Review Comment:
   **MEDIUM — sibling `down_revision` conflict must be resolved before any two of the three PRs land together**
   
   This migration shares `down_revision = "33d7e0e21daa"` with #40128 (dashboards) and #40130 (datasets). When any two of the three land in the same DB, Alembic raises `ValueError: Multiple head revisions` on the third.
   
   A merge migration is required — e.g.:
   ```python
   # merge_charts_dashboards_soft_delete.py
   down_revision = ("7c4a8d09ca37", "9e1f3b8c4d2a")  # charts + dashboards (example)
   revision = "<new_hash>"
   ```
   Please write and land the merge migration alongside whichever of the three PRs merges second. The PR description documents the need but does not include a plan or PR link for the merge migration.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342757698


##########
superset/charts/api.py:
##########
@@ -122,6 +129,7 @@ def ensure_thumbnails_enabled(self) -> Optional[Response]:
         RouteMethod.IMPORT,
         RouteMethod.RELATED,
         "bulk_delete",  # not using RouteMethod since locally defined
+        "restore",

Review Comment:
   Confirmed and fixed in 6a4ebdfdc7. The substance was right: FAB's `@protect()` decorator resolves `method_permission_name.get(method_name, method_name)`, so without an entry for `restore` the gate was falling back to `can_restore_Chart` — a permission no standard role carries. Admin-only integration tests masked the gap because Admin bypasses FAB permission checks entirely.
   
   Fix mirrors the suggested diff and the existing `themes/api.py` pattern: spread `MODEL_API_RW_METHOD_PERMISSION_MAP` into a new dict and add `"restore": "write"`.
   
   Regression test added (`test_restore_uses_can_write_permission`) that logs in as Alpha, who carries `can_write_Chart` but not `can_restore_Chart`. Soft-deletes an Alpha-owned chart, hits the restore endpoint, expects 200. If anyone removes the mapping later, the test fails with a 403 from FAB before reaching the command layer.
   
   The same gap existed on the dashboards (#40128) and datasets (#40130) sibling PRs and is fixed in companion commits there. Thanks for the catch.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4686426415

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4665439196

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore (sc-106189) [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4455183044

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/40129?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 `54.01786%` with `103 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 55.90%. Comparing base ([`823eb90`](https://app.codecov.io/gh/apache/superset/commit/823eb905d3f4e1b2444ffbbebe4e7a74673903e1?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`e53c17e`](https://app.codecov.io/gh/apache/superset/commit/e53c17e93aba7acccfc9e5b77c25a59e7e246d58?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 9 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/40129?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/views/filters.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fviews%2Ffilters.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdmlld3MvZmlsdGVycy5weQ==) | 42.30% | [30 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/models/helpers.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fmodels%2Fhelpers.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbW9kZWxzL2hlbHBlcnMucHk=) | 68.96% | [15 Missing and 3 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/restore.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fcommands%2Frestore.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvcmVzdG9yZS5weQ==) | 50.00% | [16 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/daos/base.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fdaos%2Fbase.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGFvcy9iYXNlLnB5) | 28.57% | [15 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/charts/api.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fcharts%2Fapi.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY2hhcnRzL2FwaS5weQ==) | 47.36% | [10 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/chart/importers/v1/utils.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fcommands%2Fchart%2Fimporters%2Fv1%2Futils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvY2hhcnQvaW1wb3J0ZXJzL3YxL3V0aWxzLnB5) | 0.00% | [6 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/importers/v1/utils.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fcommands%2Fimporters%2Fv1%2Futils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvaW1wb3J0ZXJzL3YxL3V0aWxzLnB5) | 50.00% | [3 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/daos/database.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fdaos%2Fdatabase.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGFvcy9kYXRhYmFzZS5weQ==) | 33.33% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/security/manager.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Fsecurity%2Fmanager.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvc2VjdXJpdHkvbWFuYWdlci5weQ==) | 0.00% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/initialization/\_\_init\_\_.py](https://app.codecov.io/gh/apache/superset/pull/40129?src=pr&el=tree&filepath=superset%2Finitialization%2F__init__.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvaW5pdGlhbGl6YXRpb24vX19pbml0X18ucHk=) | 85.71% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/40129?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 (823eb90) and HEAD (e53c17e). Click for more details.
   > 
   > <details><summary>HEAD has 39 uploads less than BASE</summary>
   >
   >| Flag | BASE (823eb90) | HEAD (e53c17e) |
   >|------|------|------|
   >|hive|3|1|
   >|python|30|3|
   >|presto|3|1|
   >|unit|9|1|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #40129      +/-   ##
   ==========================================
   - Coverage   64.15%   55.90%   -8.25%     
   ==========================================
     Files        2590     2592       +2     
     Lines      138104   138295     +191     
     Branches    32039    32060      +21     
   ==========================================
   - Hits        88594    77316   -11278     
   - Misses      47989    60313   +12324     
   + Partials     1521      666     -855     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/40129/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/40129/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.52% <54.01%> (+0.08%)` | :arrow_up: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/40129/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/40129/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/40129/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.20% <54.01%> (+0.08%)` | :arrow_up: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/40129/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `42.46% <54.01%> (-18.19%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/40129/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/40129/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `100.00% <ø> (ø)` | |
   
   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 Sentry](https://app.codecov.io/gh/apache/superset/pull/40129?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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342337449


##########
UPDATING.md:
##########
@@ -30,6 +30,18 @@ Importing a dataset now validates the `catalog` field against the target databas
 
 If you relied on importing datasets with a non-default catalog, enable "Allow changing catalogs" on the target connection, or set the dataset's catalog to the connection's default before importing.
 
+### Soft delete and restore for charts
+
+`DELETE /api/v1/chart/<id>` no longer hard-deletes the chart. The row is marked with a `deleted_at` timestamp and hidden from all list, detail, and lookup endpoints. Charts in this state are excluded from default queries and from relationship loads (e.g. `dashboard.slices`).
+
+**New endpoint** — `POST /api/v1/chart/<uuid>/restore` clears `deleted_at` and returns the chart to active state. Requires `can_write on Chart` and ownership of the row (or admin). Soft-deleted charts can also be surfaced in the list endpoint via the new `chart_deleted_state` rison filter: `include` returns both live and soft-deleted rows, `only` returns just the soft-deleted ones. Any other value is ignored.
+
+**Permissions migration:** existing role grants of `can_write on Chart` cover the new restore endpoint automatically; no role migration is required.
+
+**Schema migration:** the migration adds a nullable `deleted_at` column and an index on it (`ix_slices_deleted_at`) to the `slices` table. The column add is instant; the index build runs inline (no `CONCURRENTLY`) and may briefly block reads on the `slices` table for the duration of the build on large Postgres deployments. MySQL InnoDB builds the index online (no blocking).

Review Comment:
   **HIGH — factual error: PostgreSQL `CREATE INDEX` blocks writes, not reads**
   
   > *may briefly block reads on the `slices` table for the duration of the build on large Postgres deployments*
   
   `CREATE INDEX` (non-CONCURRENT) acquires a `ShareLock`, which conflicts with `RowExclusiveLock` (INSERT/UPDATE/DELETE) but **not** with `AccessShareLock` (SELECT). Reads continue uninterrupted during the build; it is writes that are queued.
   
   This also contradicts the PR description, which says *"non-blocking on Postgres."*
   
   Suggested correction:
   > *the index build runs inline (no `CONCURRENTLY`) and may briefly block writes on the `slices` table (INSERT/UPDATE/DELETE are queued while the index builds; reads are unaffected) on large Postgres deployments. MySQL InnoDB builds the index online (no blocking).*



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4606594982

   Follow-up correction: I reverted the `down_revision` change in 4a80c6a567.
   
   When I traced the alembic chain to verify the CI failure ("Multiple head revisions present"), I found I'd been reading the chain inverted. Tracing each `down_revision` link directly:
   
   ```
   4b2a8c9d3e1f → a1b2c3d4e5f6 → ce6bd21901ab → 33d7e0e21daa
   ```
   
   - `33d7e0e21daa.down_revision = ce6bd21901ab`
   - `ce6bd21901ab.down_revision = a1b2c3d4e5f6`
   - Nothing chains off `33d7e0e21daa`
   
   So `33d7e0e21daa` is the actual master head, not `a1b2c3d4e5f6`. The original `down_revision = "33d7e0e21daa"` was correct all along. The file-creation dates were misleading me: `33d7e0e21daa` (filename dated 2025-11-04) was merged into master *after* the 2026-03-02 batch via a feature branch, so the file date doesn't reflect alembic chain order.
   
   Reverting restored the chain. CI re-running on 4a80c6a567.
   
   Apologies for the noise on the previous round — and thanks @aminghadersohi for flagging that the migration needed attention; the *signal* (CI would break) was correct even though the specific cause was the inverse of what we both concluded at the time.


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4772816179

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore (sc-106189) [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4455103111

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3500128698


##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")

Review Comment:
   **Suggestion:** Add an explicit type annotation for this command variable so the newly introduced local variable is fully typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This local variable is introduced in new Python code without a type hint, and it is a straightforward candidate for annotation. That is a real violation of the type-hint rule.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cfbb54b283a045bfa2590c4e8cf218dd&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=cfbb54b283a045bfa2590c4e8cf218dd&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/commands/chart/restore_test.py
   **Line:** 48:48
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this command variable so the newly introduced local variable is fully typed.
   
   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%2F40129&comment_hash=152e9b504d6fa9a51e36fa7f1aff66806587997a1e8a7d9554888d52c8e0d78b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=152e9b504d6fa9a51e36fa7f1aff66806587997a1e8a7d9554888d52c8e0d78b&reaction=dislike'>👎</a>



##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy.orm.session import Session
+
+
+def test_set_dash_metadata_preserves_soft_deleted_members(
+    session: Session,
+) -> None:
+    """Saving a dashboard must not sever a soft-deleted member chart.
+
+    ``set_dash_metadata`` rebuilds ``dashboard.slices`` wholesale from the
+    incoming position data. The slice-resolution query must bypass the
+    soft-delete visibility filter: with the filter active, a member chart
+    sitting in the trash would be silently dropped from the assignment —
+    deleting its ``dashboard_slices`` junction row (breaking the
+    restore-reattach contract) and writing ``uuid: None`` into its
+    position slot. This test fails if the bypass is removed.
+    """
+    from superset import db
+    from superset.connectors.sqla.models import Database, SqlaTable
+    from superset.daos.dashboard import DashboardDAO
+    from superset.models.dashboard import Dashboard
+    from superset.models.slice import Slice
+
+    Dashboard.metadata.create_all(session.get_bind())
+
+    dataset = SqlaTable(
+        table_name="dash_meta_table",
+        database=Database(database_name="dash_meta_db", sqlalchemy_uri="sqlite://"),
+    )
+    db.session.add(dataset)
+    db.session.flush()
+
+    live_chart = Slice(
+        slice_name="live_chart",
+        datasource_id=dataset.id,
+        datasource_type="table",
+    )
+    trashed_chart = Slice(
+        slice_name="trashed_chart",
+        datasource_id=dataset.id,
+        datasource_type="table",
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )
+    dashboard = Dashboard(
+        dashboard_title="meta_test_dash",
+        slices=[live_chart, trashed_chart],
+        published=True,
+    )
+    db.session.add_all([live_chart, trashed_chart, dashboard])
+    db.session.flush()
+
+    positions: dict[str, dict[str, Any]] = {
+        "CHART-live": {
+            "type": "CHART",
+            "id": "CHART-live",
+            "children": [],
+            "meta": {"chartId": live_chart.id, "width": 4, "height": 50},
+        },
+        "CHART-trashed": {
+            "type": "CHART",
+            "id": "CHART-trashed",
+            "children": [],
+            "meta": {"chartId": trashed_chart.id, "width": 4, "height": 50},
+        },
+    }
+
+    DashboardDAO.set_dash_metadata(dashboard, {"positions": positions})
+
+    member_ids = {chart.id for chart in dashboard.slices}

Review Comment:
   **Suggestion:** Add an explicit type annotation for `member_ids` to satisfy the type-hints requirement for relevant newly introduced variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The file is new Python code, and `member_ids` is an unannotated variable whose type can clearly be expressed. This matches the rule requiring type hints on relevant variables in new or modified Python code.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ce6bdac9122944d7ae86cdb914c12b9a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ce6bdac9122944d7ae86cdb914c12b9a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/dao/dashboard_test.py
   **Line:** 87:87
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for `member_ids` to satisfy the type-hints requirement for relevant newly introduced variables.
   
   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%2F40129&comment_hash=b1eee493a8005448b3662a1a0fcd4a7341d39e626cd3324247957679f46087dc&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=b1eee493a8005448b3662a1a0fcd4a7341d39e626cd3324247957679f46087dc&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = None  # not soft-deleted
+
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=chart):
+        cmd = RestoreChartCommand("1")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_chart_forbidden_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartForbiddenError on permission check."""
+    chart = MagicMock()

Review Comment:
   **Suggestion:** Add an explicit type annotation for this mocked chart variable in the permission test to comply with the type-hint rule. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is another untyped local variable in the added Python test code. Since it can be annotated, the suggestion correctly identifies a type-hint violation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7e21c5e5b8c842849f2121714cec5fc1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7e21c5e5b8c842849f2121714cec5fc1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/commands/chart/restore_test.py
   **Line:** 76:76
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this mocked chart variable in the permission test to comply with the type-hint rule.
   
   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%2F40129&comment_hash=0e528e65a9acd389710997c0e741588fc246c61606940388854125a5ae915005&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=0e528e65a9acd389710997c0e741588fc246c61606940388854125a5ae915005&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)

Review Comment:
   **Suggestion:** Add an explicit type annotation for the dynamically imported `migration` module so this new variable is fully typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This new module-level variable is inferred without an explicit type hint, and it is a relevant annotatable variable under the Python type-hint rule. The suggestion correctly identifies a real omission.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=97f1862880c44b888cee0680ddcd7052&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=97f1862880c44b888cee0680ddcd7052&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 50:53
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for the dynamically imported `migration` module so this new variable is fully typed.
   
   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%2F40129&comment_hash=17b464f5bf9f9b1a097a25bdd05f6bc3752582f24df83daa0e4345ffa8c0c546&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=17b464f5bf9f9b1a097a25bdd05f6bc3752582f24df83daa0e4345ffa8c0c546&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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4836947265

   ### Soft-delete rollout — related PRs & merge order
   
   This is one of four coordinated PRs implementing soft-delete + restore per [SIP-208](https://github.com/apache/superset/issues/39464), on top of the merged infrastructure (#39977).
   
   **Merge order matters** — the gate must land first so the entity PRs ship behind the `SOFT_DELETE` release toggle (default **off**). Merging an entity PR before the gate would ship soft-delete **unguarded**.
   
   | Order | PR | Role |
   |-------|-----|------|
   | 1️⃣ | #41166 | `SOFT_DELETE` release toggle (the gate) — **merge first** |
   | 2️⃣ | #40129 | charts soft-delete + restore ⬅︎ |
   | 3️⃣ | #40128 | dashboards soft-delete + restore |
   | 4️⃣ | #40130 | datasets soft-delete + restore |
   
   After the gate merges, each entity PR is rebased onto the gated `master` and inherits the flag. Each entity migration's `down_revision` is currently `78a40c08b4be` (current master head) and is re-pointed at merge time as siblings land, to keep a single Alembic head.
   
   Charts entity PR ← **this PR**
   


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4685709124

   Final triage sweep of the open bot threads (codeant + bito), regenerated by the recent pushes — resolving as not actionable:
   
   - **Docstring suggestions** (migration upgrade/downgrade fns, exception classes, test helpers): not this repo's convention — migration functions and test helpers are consistently undocstringed across the codebase; the substantive helpers added by this PR carry docstrings where they earn them.
   - **Empty `msgstr` entries**: by design — new source strings ship with empty `msgstr` (gettext falls back to the English msgid); translations land via the project translation workflow. Documented in earlier triage comments on this PR.
   - **Migration filename hyphens**: the `YYYY-MM-DD_HH-MM_hash_description.py` pattern is Superset's documented migration naming convention (CLAUDE.md); alembic loads migrations by path, not import. The file compiles and CI is green.
   - **Test-hygiene nits** (try/finally placement, mock verification): cosmetic; suites are green and the integration DB is rebuilt per branch.
   


-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3492943034


##########
superset/commands/chart/restore.py:
##########
@@ -0,0 +1,39 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command to restore a soft-deleted chart."""
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+    ChartRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.daos.chart import ChartDAO
+from superset.models.slice import Slice
+
+
+class RestoreChartCommand(BaseRestoreCommand[Slice]):
+    """Restore a soft-deleted chart by clearing its ``deleted_at`` field.
+
+    All transactional wrapping and validation lives in
+    ``BaseRestoreCommand``; this subclass is purely declarative.
+    """
+
+    dao = ChartDAO
+    not_found_exc = ChartNotFoundError
+    forbidden_exc = ChartForbiddenError
+    restore_failed_exc = ChartRestoreFailedError

Review Comment:
   **Suggestion:** Add explicit type annotations to the declarative class attributes so these bindings are type-hinted rather than untyped assignments. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   These new class attributes are typed bindings that can be annotated, but the file assigns them without any type hints. That matches the custom rule requiring type hints on relevant variables in modified Python code.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5b3282dc14864ee7af5eb1ad2d120698&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5b3282dc14864ee7af5eb1ad2d120698&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/chart/restore.py
   **Line:** 36:39
   **Comment:**
   	*Custom Rule: Add explicit type annotations to the declarative class attributes so these bindings are type-hinted rather than untyped assignments.
   
   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%2F40129&comment_hash=5c50a1691b2ac2b7306e7cae8431ae62d01f30029dd3ffc6c4e6a5857cc4d1fb&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=5c50a1691b2ac2b7306e7cae8431ae62d01f30029dd3ffc6c4e6a5857cc4d1fb&reaction=dislike'>👎</a>



##########
superset/daos/dashboard.py:
##########
@@ -276,8 +277,19 @@ def set_dash_metadata(
                 if isinstance(value, dict)
             ]
 
+            # Bypass the soft-delete visibility filter when resolving the
+            # incoming chart ids: a dashboard's ``position_json`` may still
+            # reference a chart that is currently soft-deleted, and this
+            # assignment REBUILDS ``dashboard.slices`` wholesale. With the
+            # filter active, the hidden member would be silently dropped —
+            # deleting its ``dashboard_slices`` junction row (breaking the
+            # documented restore-reattach contract) and writing
+            # ``uuid: None`` into its position slot via ``uuid_map`` below.
             current_slices = (
-                db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
+                db.session.query(Slice)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+                .filter(Slice.id.in_(slice_ids))
+                .all()
             )

Review Comment:
   **Suggestion:** Add an explicit type annotation for the newly introduced local variable so the modified Python code complies with the type-hint requirement. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This modified Python code introduces a new local variable without a type annotation. Since `current_slices` is clearly a list of `Slice` objects and can be annotated, it matches the type-hint requirement rule.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ef35084360cc4b3a9ca7ef8948631e7c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ef35084360cc4b3a9ca7ef8948631e7c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/daos/dashboard.py
   **Line:** 288:293
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for the newly introduced local variable so the modified Python code complies with the type-hint requirement.
   
   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%2F40129&comment_hash=ffb0e815cbbafb6e7501c8d3ae9973a05af911313cc1c62b3ed4b6338f224dcf&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=ffb0e815cbbafb6e7501c8d3ae9973a05af911313cc1c62b3ed4b6338f224dcf&reaction=dislike'>👎</a>



##########
tests/integration_tests/charts/commands_tests.py:
##########
@@ -721,7 +721,7 @@ def test_fave_unfave_chart_command(self):
     def test_fave_unfave_chart_command_not_found(self):
         """Test that faving / unfaving a non-existing chart raises an exception"""
         with self.client.application.test_request_context():
-            example_chart_id = 1234
+            example_chart_id = 0

Review Comment:
   **Suggestion:** Add an explicit type annotation to this newly introduced local variable. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new local variable is a simple Python assignment in modified code and can be annotated with a type hint such as `example_chart_id: int = 0`, so it matches the rule requiring type hints for relevant variables that can be annotated.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=97a03e8d923247bcb2922aa287d100a6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=97a03e8d923247bcb2922aa287d100a6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/integration_tests/charts/commands_tests.py
   **Line:** 724:724
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this newly introduced local variable.
   
   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%2F40129&comment_hash=7d4e54840d1cec33b05413462cbe6e98d5f7fbc2f4c482dc10d274952dbaf3b8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=7d4e54840d1cec33b05413462cbe6e98d5f7fbc2f4c482dc10d274952dbaf3b8&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()

Review Comment:
   **Suggestion:** Add an explicit type annotation for this test-local mock variable to satisfy the type-hint requirement. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This new test-local variable is introduced without an explicit type hint, and it is a relevant variable that could be annotated under the Python type-hint rule.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ade5d379185a4b65bbc86383abce2308&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ade5d379185a4b65bbc86383abce2308&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/commands/chart/restore_test.py
   **Line:** 36:36
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this test-local mock variable to satisfy the type-hint requirement.
   
   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%2F40129&comment_hash=49450f6e2ee99107e8501138be6406afd489be0803eca5f788a915c5a64c50a8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=49450f6e2ee99107e8501138be6406afd489be0803eca5f788a915c5a64c50a8&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")

Review Comment:
   **Suggestion:** Add a type annotation for this command instance variable so the new code consistently uses typed local variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This new local variable is assigned a command instance without a type hint, which matches the type-hint rule for annotatable variables.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f5c8bce9791e4f708463d295db929506&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f5c8bce9791e4f708463d295db929506&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/commands/chart/restore_test.py
   **Line:** 58:58
   **Comment:**
   	*Custom Rule: Add a type annotation for this command instance variable so the new code consistently uses typed local variables.
   
   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%2F40129&comment_hash=00f3378988f62e82deb908266b860271d9ded55f7967fcd39b089127a84ddec8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=00f3378988f62e82deb908266b860271d9ded55f7967fcd39b089127a84ddec8&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"

Review Comment:
   **Suggestion:** Add explicit type annotations for these module-level constants so they comply with the required Python typing rule. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   These module-level constants are new Python variables that can be annotated, and they currently lack type hints. That matches the typing rule requiring type hints on relevant variables in new or modified Python code.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5f2656aaf141499a8e8b19d6f2fbcd1a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5f2656aaf141499a8e8b19d6f2fbcd1a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 55:56
   **Comment:**
   	*Custom Rule: Add explicit type annotations for these module-level constants so they comply with the required Python typing rule.
   
   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%2F40129&comment_hash=5b8f13f777061d495d9cbe2909f9893159d181f0bd11d0c6b880f0e6641fc7fa&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=5b8f13f777061d495d9cbe2909f9893159d181f0bd11d0c6b880f0e6641fc7fa&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()

Review Comment:
   **Suggestion:** Add an explicit type annotation for this mock object variable in the test to comply with the type-hints rule. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is another new mock variable introduced without a type annotation, so it fits the stated Python type-hint violation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7a954a470c60481a83a65387b3584412&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7a954a470c60481a83a65387b3584412&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/commands/chart/restore_test.py
   **Line:** 65:65
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this mock object variable in the test to comply with the type-hints rule.
   
   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%2F40129&comment_hash=bb3377b66370a73a4bc735a5c40db64a04cc351d1bdf0291863786a292d13203&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=bb3377b66370a73a4bc735a5c40db64a04cc351d1bdf0291863786a292d13203&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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3344694739


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   Fixed in 7f15310b2d — moved `find_existing_for_import` to module-top imports. Verified `superset.commands.importers.v1.utils` does not reach `superset.commands.chart.importers.v1.utils` via any import chain. (Noting your re-review retraction at `6a4ebdfd` — the prior pass flagged this in a state where it was already at module top.)



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   Fixed in 7f15310b2d — moved `find_existing_for_import` to module-top imports. Verified `superset.commands.importers.v1.utils` does not reach `superset.commands.chart.importers.v1.utils` via any import chain. (Noting your re-review retraction at `6a4ebdfd` — the prior pass flagged this in a state where it was already at module top.)



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import
+
     user = get_user()

Review Comment:
   Both addressed in 7f15310b2d: (1) added an inline comment block above the `user = get_user()` call explaining the intentional bypass for background / example-loader paths where `ignore_permissions=True` establishes trust at the command level — and noting this now applies to soft-deleted matches via `needs_mutation`, not just `overwrite=True`; (2) dropped the redundant `(user := get_user())` walrus rebind near the end of `import_chart`, replaced with `if user and user not in chart.owners:` since the local binding is still in scope.



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import
+
     user = get_user()

Review Comment:
   Both addressed in 7f15310b2d: (1) added an inline comment block above the `user = get_user()` call explaining the intentional bypass for background / example-loader paths where `ignore_permissions=True` establishes trust at the command level — and noting this now applies to soft-deleted matches via `needs_mutation`, not just `overwrite=True`; (2) dropped the redundant `(user := get_user())` walrus rebind near the end of `import_chart`, replaced with `if user and user not in chart.owners:` since the local binding is still in scope.



##########
UPDATING.md:
##########
@@ -30,6 +30,18 @@ Importing a dataset now validates the `catalog` field against the target databas
 
 If you relied on importing datasets with a non-default catalog, enable "Allow changing catalogs" on the target connection, or set the dataset's catalog to the connection's default before importing.
 
+### Soft delete and restore for charts
+
+`DELETE /api/v1/chart/<id>` no longer hard-deletes the chart. The row is marked with a `deleted_at` timestamp and hidden from all list, detail, and lookup endpoints. Charts in this state are excluded from default queries and from relationship loads (e.g. `dashboard.slices`).
+
+**New endpoint** — `POST /api/v1/chart/<uuid>/restore` clears `deleted_at` and returns the chart to active state. Requires `can_write on Chart` and ownership of the row (or admin). Soft-deleted charts can also be surfaced in the list endpoint via the new `chart_deleted_state` rison filter: `include` returns both live and soft-deleted rows, `only` returns just the soft-deleted ones. Any other value is ignored.
+
+**Permissions migration:** existing role grants of `can_write on Chart` cover the new restore endpoint automatically; no role migration is required.
+
+**Schema migration:** the migration adds a nullable `deleted_at` column and an index on it (`ix_slices_deleted_at`) to the `slices` table. The column add is instant; the index build runs inline (no `CONCURRENTLY`) and may briefly block reads on the `slices` table for the duration of the build on large Postgres deployments. MySQL InnoDB builds the index online (no blocking).

Review Comment:
   Fixed in 7f15310b2d — UPDATING.md now correctly states that the index build may briefly block writes (INSERT/UPDATE/DELETE queued during `ShareLock`) on the `slices` table, with reads unaffected. Added a separate rollback note for the visibility-filter-rollback edge case Richard called out in his review.



##########
UPDATING.md:
##########
@@ -30,6 +30,18 @@ Importing a dataset now validates the `catalog` field against the target databas
 
 If you relied on importing datasets with a non-default catalog, enable "Allow changing catalogs" on the target connection, or set the dataset's catalog to the connection's default before importing.
 
+### Soft delete and restore for charts
+
+`DELETE /api/v1/chart/<id>` no longer hard-deletes the chart. The row is marked with a `deleted_at` timestamp and hidden from all list, detail, and lookup endpoints. Charts in this state are excluded from default queries and from relationship loads (e.g. `dashboard.slices`).
+
+**New endpoint** — `POST /api/v1/chart/<uuid>/restore` clears `deleted_at` and returns the chart to active state. Requires `can_write on Chart` and ownership of the row (or admin). Soft-deleted charts can also be surfaced in the list endpoint via the new `chart_deleted_state` rison filter: `include` returns both live and soft-deleted rows, `only` returns just the soft-deleted ones. Any other value is ignored.
+
+**Permissions migration:** existing role grants of `can_write on Chart` cover the new restore endpoint automatically; no role migration is required.
+
+**Schema migration:** the migration adds a nullable `deleted_at` column and an index on it (`ix_slices_deleted_at`) to the `slices` table. The column add is instant; the index build runs inline (no `CONCURRENTLY`) and may briefly block reads on the `slices` table for the duration of the build on large Postgres deployments. MySQL InnoDB builds the index online (no blocking).

Review Comment:
   Fixed in 7f15310b2d — UPDATING.md now correctly states that the index build may briefly block writes (INSERT/UPDATE/DELETE queued during `ShareLock`) on the `slices` table, with reads unaffected. Added a separate rollback note for the visibility-filter-rollback edge case Richard called out in his review.



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 33d7e0e21daa
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "33d7e0e21daa"

Review Comment:
   There's a story here — first attempt at "updating to current head" (`a1b2c3d4e5f6`) actually broke CI with "Multiple head revisions present", because the chain on master is `a1b2c3d4e5f6 → ce6bd21901ab → 33d7e0e21daa` (the 2025-11-04-dated `33d7e0e21daa` was merged after the 2026-03-02-dated migrations via a feature branch — file dates don't reflect alembic chain order). Reverted to the original `down_revision = "33d7e0e21daa"` in 4a80c6a567, which is actually the correct value. Cross-PR coordination still applies: whichever entity PR lands first stays at `33d7e0e21daa`; the others rebase onto the newly-merged revision.



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 33d7e0e21daa
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "33d7e0e21daa"

Review Comment:
   There's a story here — first attempt at "updating to current head" (`a1b2c3d4e5f6`) actually broke CI with "Multiple head revisions present", because the chain on master is `a1b2c3d4e5f6 → ce6bd21901ab → 33d7e0e21daa` (the 2025-11-04-dated `33d7e0e21daa` was merged after the 2026-03-02-dated migrations via a feature branch — file dates don't reflect alembic chain order). Reverted to the original `down_revision = "33d7e0e21daa"` in 4a80c6a567, which is actually the correct value. Cross-PR coordination still applies: whichever entity PR lands first stays at `33d7e0e21daa`; the others rebase onto the newly-merged revision.



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,406 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import ADMIN_USERNAME, ALPHA_USERNAME
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self):

Review Comment:
   (1) `-> None` annotations added on all 12 test methods in b2b34b79e8. (2) `addCleanup` pattern deferred — agree it's the right shape but the diff to switch all 12 tests would be substantive and the trailing `_hard_delete_chart(chart_id)` pattern matches what the sibling soft-delete test suites do. Worth a follow-up cleanup commit once the entity PRs land.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510307194


##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:
+        query = super().apply(query, value)
+        normalized = str(value).lower().strip() if value is not None else ""

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:
+        query = super().apply(query, value)
+        normalized = str(value).lower().strip() if value is not None else ""
+        if normalized not in {"include", "only"} or security_manager.is_admin():
+            return query
+
+        # Non-admins may only see soft-deleted charts they own. ``any()`` emits
+        # an EXISTS subquery so it composes with the base access filter without
+        # producing duplicate rows from a join.
+        owned = Slice.owners.any(security_manager.user_model.id == get_user_id())

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "78a40c08b4be"
+
+TABLE_NAME = "slices"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self) -> None:
+        """DELETE /api/v1/chart/<pk> sets deleted_at instead of removing."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("soft_delete_test", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # Row still exists in DB with deleted_at set
+        row = (
+            db.session.query(Slice)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+            .filter(Slice.id == chart_id)
+            .one_or_none()
+        )
+        assert row is not None
+        assert row.deleted_at is not None
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_excluded_from_get(self) -> None:
+        """GET /api/v1/chart/<pk> returns 404 for a soft-deleted chart."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("invisible_chart", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.get(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_excluded_from_list(self) -> None:
+        """GET /api/v1/chart/ should not include soft-deleted charts."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("listed_then_deleted", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.get("/api/v1/chart/")
+        data = json.loads(rv.data)
+        chart_ids = [c["id"] for c in data["result"]]
+        assert chart_id not in chart_ids
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/chart/ with chart_deleted_state=include returns deleted charts."""  # noqa: E501
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("listed_with_deleted", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+
+        rison_query = "(filters:!((col:id,opr:chart_deleted_state,value:include)))"
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+
+        data = json.loads(rv.data)
+        deleted_row = next(
+            (row for row in data["result"] if row["id"] == chart_id),
+            None,
+        )
+        assert deleted_row is not None
+        assert deleted_row["deleted_at"] is not None
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_only_filter_returns_only_soft_deleted_charts(self) -> None:
+        """chart_deleted_state=only excludes live rows and returns only deleted ones."""
+        admin_id = self.get_user("admin").id
+        live_chart = self.insert_chart("only_live", [admin_id], 1)
+        deleted_chart = self.insert_chart("only_deleted", [admin_id], 1)
+        live_id = live_chart.id
+        deleted_id = deleted_chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{deleted_id}")
+
+        rison_query = "(filters:!((col:id,opr:chart_deleted_state,value:only)))"
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+
+        data = json.loads(rv.data)
+        returned_ids = {row["id"] for row in data["result"]}
+        assert deleted_id in returned_ids
+        assert live_id not in returned_ids
+
+        # Cleanup
+        _hard_delete_chart(live_id)
+        _hard_delete_chart(deleted_id)
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted charts.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha_id = self.get_user(ALPHA_USERNAME).id
+        chart = self.insert_chart("sd_owner_chart", [alpha_id], 1)
+        chart_id = chart.id
+
+        chart.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:chart_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [c["id"] for c in json.loads(rv.data)["result"]]
+        assert chart_id in ids
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a chart once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the chart's dataset, so
+        ``ChartFilter`` makes the chart visible to gamma while it is live. After
+        soft-delete, the deleted-state list is scoped to the restore audience
+        (owners/admins), so gamma — who could never restore it — must not see it
+        via ``include`` or ``only``.
+        """
+        admin_id = self.get_user(ADMIN_USERNAME).id
+        chart = self.insert_chart("sd_acl_chart", [admin_id], 1)
+        chart_id = chart.id
+
+        table = db.session.query(SqlaTable).get(1)
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu("datasource_access", table.perm)
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the chart while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/chart/?q=(page_size:200)")
+            assert chart_id in [c["id"] for c in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live chart via datasource access"
+            )
+
+            # Soft-delete directly (avoids a mid-test re-login to admin).
+            reloaded = (
+                db.session.query(Slice)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+                .filter(Slice.id == chart_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            # Gamma must not see the soft-deleted chart in either mode.
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:chart_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [c["id"] for c in json.loads(rv.data)["result"]]
+                assert chart_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"chart via chart_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", table.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            _hard_delete_chart(chart_id)
+
+    def test_delete_already_soft_deleted_chart_returns_404(self) -> None:
+        """DELETE on an already soft-deleted chart returns 404 (FR-008)."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("double_delete_test", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_delete_chart_blocked_when_active_report_references_it(self) -> None:
+        """DELETE /api/v1/chart/<id> returns 422 when a report references it.
+
+        Pins down the existing API protection in `DeleteChartCommand.validate()`:
+        when a `report_schedule` row references the chart, the validation
+        raises `ChartDeleteFailedReportsExistError` *before* `ChartDAO.delete()`
+        is invoked, so no soft-delete routing happens. This is the contract
+        soft-delete inherits from the pre-existing API and is what makes the
+        "report-execution against soft-deleted target" crash class
+        (commands/report/execute.py:_get_url) unreachable through the API.
+        """
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("blocked_by_report_test", [admin_id], 1)
+        chart_id = chart.id
+
+        report = ReportSchedule(
+            type=ReportScheduleType.REPORT,
+            name="blocking_report_for_chart_delete",
+            description="Report that should block chart deletion",
+            crontab="0 9 * * *",
+            chart=chart,
+            creation_method=ReportCreationMethod.ALERTS_REPORTS,
+        )
+        db.session.add(report)
+        db.session.commit()
+        report_id = report.id
+
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 422
+        body = json.loads(rv.data)
+        assert "associated alerts or reports" in body.get("message", "").lower() or (
+            "associated" in body.get("message", "").lower()
+            and "report" in body.get("message", "").lower()
+        )
+        assert "blocking_report_for_chart_delete" in body.get("message", "")
+
+        # Confirm the chart was NOT soft-deleted (deleted_at remains NULL).
+        row = (
+            db.session.query(Slice)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+            .filter(Slice.id == chart_id)
+            .one()
+        )
+        assert row.deleted_at is None
+
+        # Cleanup
+        db.session.delete(
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.id == report_id)
+            .one()
+        )
+        db.session.commit()
+        _hard_delete_chart(chart_id)
+
+
+class TestChartRestore(InsertChartMixin, SupersetTestCase):
+    """Tests for chart restore behaviour (T025)."""
+
+    def test_restore_soft_deleted_chart(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore makes the chart visible again."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("restore_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``ChartRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreChartCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``ChartRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.chart.exceptions import (
+            ChartRestoreFailedError,
+        )
+
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("restore_fail_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+
+        with patch(
+            "superset.commands.chart.restore.RestoreChartCommand.run",
+            side_effect=ChartRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_nonexistent_chart_returns_404(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore returns 404 for unknown UUID."""
+        self.login(ADMIN_USERNAME)
+        rv = self.client.post(
+            "/api/v1/chart/00000000-0000-0000-0000-000000000000/restore"
+        )
+        assert rv.status_code == 404
+
+    def test_restore_active_chart_returns_404(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore on active chart returns 404."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("active_restore_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_uses_can_write_permission(self) -> None:
+        """Non-admin owner with ``can_write_Chart`` can hit the restore
+        endpoint.
+
+        Pins the permission contract: ``method_permission_name`` must map
+        ``restore`` to ``write`` so FAB's ``@protect`` resolves the gate to
+        ``can_write_Chart`` (which Alpha already carries), not the implicit
+        fallback ``can_restore_Chart`` (which no standard role carries).
+
+        Without the mapping FAB defaults to ``can_<method>_<class>`` and
+        every non-admin would get 403 here — admins bypass FAB permission
+        checks entirely, so the admin-authed restore tests above don't
+        exercise the mapping.
+        """
+        alpha = self.get_user(ALPHA_USERNAME)
+        chart = self.insert_chart("restore_perm_test", [alpha.id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        self.login(ALPHA_USERNAME)
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200, (
+            f"Alpha owner soft-delete failed: {rv.status_code} {rv.data!r}"
+        )
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200, (
+            f"Expected 200 from Alpha owner restore (can_write_Chart), got "
+            f"{rv.status_code}: {rv.data!r}. If 403, "
+            "method_permission_name is missing 'restore': 'write'."
+        )
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_chart_reattaches_to_dashboards(self) -> None:
+        """Soft-deleting a chart preserves dashboard_slices junction rows;
+        restore makes the chart reappear in its dashboards automatically.
+
+        This is the positive test that pins down the SIP's "no cascade"
+        contract and the corrected commit ``feat(soft-delete): preserve
+        dashboard_slices on chart soft-delete (MissingChart handles UI)``.
+        Soft-delete leaves the junction intact so:
+
+          - dashboards continue to render the chart slot (frontend uses
+            ``MissingChart`` placeholder while the chart is hidden via the
+            visibility filter)
+          - on restore the chart is automatically a member of every
+            dashboard it was a member of before, with no manual
+            re-attachment step
+        """
+        admin = self.get_user("admin")
+        admin_id = admin.id
+
+        chart = self.insert_chart("reattach_test_chart", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        dashboard = Dashboard(
+            dashboard_title="reattach_test_dashboard",
+            slug="slug_reattach_test",
+            owners=[admin],
+            published=True,
+        )
+        dashboard.slices = [chart]
+        db.session.add(dashboard)
+        db.session.commit()
+        dashboard_id = dashboard.id
+
+        # Sanity: the junction row exists
+        junction_count = (
+            db.session.query(dashboard_slices)
+            .filter(
+                dashboard_slices.c.dashboard_id == dashboard_id,
+                dashboard_slices.c.slice_id == chart_id,
+            )
+            .count()
+        )
+        assert junction_count == 1, "junction row should exist after dashboard creation"
+
+        self.login(ADMIN_USERNAME)
+
+        # Soft-delete the chart
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # The junction row is preserved (no cascade)
+        junction_count_after_delete = (
+            db.session.query(dashboard_slices)
+            .filter(
+                dashboard_slices.c.dashboard_id == dashboard_id,
+                dashboard_slices.c.slice_id == chart_id,
+            )
+            .count()
+        )
+        assert junction_count_after_delete == 1, (
+            "junction row should remain intact on chart soft-delete; "
+            "MissingChart placeholder handles the UI gap"
+        )
+
+        # The dashboard's loaded `slices` collection no longer includes the
+        # soft-deleted chart (the global visibility filter applies to
+        # relationship loads via `with_loader_criteria(..., include_aliases=True)`).
+        db.session.expire_all()
+        dashboard_after_delete = (
+            db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+        )
+        assert chart_id not in [s.id for s in dashboard_after_delete.slices], (
+            "soft-deleted chart should be filtered out of dashboard.slices "
+            "by the visibility-filter listener"
+        )
+
+        # Restore the chart
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200
+
+        # The chart automatically reappears in the dashboard — junction row
+        # was preserved, so no manual reattach was needed.
+        db.session.expire_all()
+        dashboard_after_restore = (
+            db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+        )
+        assert chart_id in [s.id for s in dashboard_after_restore.slices], (
+            "restored chart should reappear in dashboard.slices automatically; "
+            "the junction row was never removed by soft-delete"
+        )
+
+        # Cleanup
+        _hard_delete_dashboard_for_charts_test(dashboard_id)
+        _hard_delete_chart(chart_id)
+
+    def test_restore_chart_by_non_admin_owner(self) -> None:
+        """Non-admin owners can restore their own soft-deleted charts.
+
+        The unit-level restore command tests mock security; this
+        integration test exercises the FAB security wiring end-to-end
+        so a future change that breaks the owner check on a non-admin
+        path can't slip through.
+        """
+        alpha = self.get_user(ALPHA_USERNAME)
+        alpha_id = alpha.id
+
+        chart = self.insert_chart("alpha_owned_chart", [alpha_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        self.login(ALPHA_USERNAME)
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200, rv.data
+
+        db.session.expire_all()
+        restored = db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "78a40c08b4be"

Review Comment:
   Intentional, not an unintended dependency: `2bee73611e32` is the current single alembic head on master (the composite-PK migration from #39859, merged 2026-07-01). Every new migration must chain off the current head — pointing anywhere else would fork the migration DAG and fail the "Check DB migration conflict" CI check. The re-point is documented in the PR body. Declining.



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4606701871

   Thanks @richardfogaca (and the PR review agent — looping you back in via that path) — both of your suggestions are addressed:
   
   **`UPDATING.md:41` — rollback edge for soft-deleted rows**: added a rollback paragraph in `7f15310b2d`:
   
   > *"Rollback note: if the application code is rolled back after charts have been soft-deleted, the older code path's visibility filter no longer applies and previously hidden rows become visible to the older code. Pair the rollback with a data decision (restore the rows, hard-delete them, or also downgrade the migration) rather than assuming the old hard-delete semantics still hold."*
   
   Matches the shape you described — operator pairs rollback with a data plan, not assumed old semantics.
   
   **`superset/commands/chart/importers/v1/utils.py:81` — inline `find_existing_for_import` import**: moved to module top (same commit). Verified no circular dependency exists between `superset.commands.importers.v1.utils` and `superset.commands.chart.importers.v1.utils` before moving. Per constitution v1.3.2 (recently updated in this fork), inline imports require a `# avoid circular import` or `# avoid app-init regression` justification comment; without that justification, module-top is the default. Your reading was correct on the first pass.
   
   Also thanks for the praise on the dashboard-junction regression test — the two-sided contract check was deliberate and reading it back from your review made me appreciate the framing more.


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4635112605

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3365403427


##########
superset/translations/ja/LC_MESSAGES/messages.po:
##########
@@ -2866,6 +2866,9 @@ msgstr "チャートの変更"
 msgid "Chart could not be created."
 msgstr "チャートを作成できませんでした。"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Japanese translation</b></div>
   <div id="fix">
   
   The `msgstr` for "Chart could not be restored." is empty. Japanese users will see the untranslated English error message when `ChartRestoreFailedError` is raised in `charts/api.py:640`. Following the pattern of adjacent translations (lines 2867, 2873), the translation should be "チャートを復元できませんでした。".
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1ed16d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/sk/LC_MESSAGES/messages.po:
##########
@@ -3104,6 +3104,9 @@ msgstr "Zmeny grafu"
 msgid "Chart could not be created."
 msgstr "Graf sa nepodarilo vytvoriť."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Slovak translation</b></div>
   <div id="fix">
   
   The new translation entry `msgid "Chart could not be restored."` has an empty `msgstr ""`. Slovak users will see untranslated English text. Following the established pattern (created→vytvoriť, updated→aktualizovať), the translation should be `msgstr "Graf sa nepodarilo obnoviť."`.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1ed16d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/lv/LC_MESSAGES/messages.po:
##########
@@ -3072,6 +3072,9 @@ msgstr "Diagrammas izmaiņas"
 msgid "Chart could not be created."
 msgstr "Diagrammu nevarēja izveidot."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing source template update</b></div>
   <div id="fix">
   
   The source template `messages.pot` does not contain `msgid "Chart could not be restored."`, but the English translation file does. This translation was added directly without going through the standard i18n workflow. The source template must be regenerated first (`pybabel extract` + `pybabel update`) to ensure all language files receive this new string and the entry is properly tracked.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1ed16d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/ko/LC_MESSAGES/messages.po:
##########
@@ -2982,6 +2982,9 @@ msgstr ""
 msgid "Chart could not be created."
 msgstr "차트를 생성할 수 없습니다."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Korean translation</b></div>
   <div id="fix">
   
   The new translation string "Chart could not be restored." has an empty `msgstr`. Korean users will see the untranslated English text. Following the established pattern for similar messages in this file, the translation should be "차트를 복원할 수 없습니다.".
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/ko/LC_MESSAGES/messages.po
    +++ superset/translations/ko/LC_MESSAGES/messages.po
    @@ -2983,7 +2983,7 @@ msgstr "차트를 생성할 수 없습니다."
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "차트를 복원할 수 없습니다."
    
     msgid "Chart could not be updated."
     msgstr "차트를 업데이트할 수 없습니다."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1ed16d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4673536299

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3350425153


##########
superset/commands/chart/restore.py:
##########
@@ -0,0 +1,43 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command to restore a soft-deleted chart."""
+
+import logging
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+    ChartRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.daos.chart import ChartDAO
+from superset.models.slice import Slice
+
+logger = logging.getLogger(__name__)

Review Comment:
   **Suggestion:** `logging` and `logger` are introduced but never used, which adds dead code and an unnecessary module import. Remove the unused logger setup (or add actual logging calls) to keep the command minimal and avoid lint/runtime overhead from unused symbols. [code quality]
   
   <details>
   <summary><b>Severity Level:</b> Minor 🧹</summary>
   
   ```mdx
   - ⚠️ Linting step reports unused import and variable.
   - ⚠️ Adds minor noise in reviews for this command.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Open `superset/commands/chart/restore.py` and observe at line 19 the import `import
   logging` (verified via Read tool output) and at line 30 the assignment `logger =
   logging.getLogger(__name__)`.
   
   2. In the same file, inspect the `RestoreChartCommand` class definition at lines 33–43 and
   confirm there are no references to `logging` or `logger` anywhere in the file (no
   `logger.` calls or use of the imported module).
   
   3. Run any standard Python linter used in this repository (e.g., pyflakes/ruff/flake8)
   over `superset/commands/chart/restore.py`; because `logging` is imported but never used
   and `logger` is assigned but never referenced, the linter will report unused-import and
   unused-variable warnings for these symbols.
   
   4. Observe that these warnings originate specifically from
   `superset/commands/chart/restore.py:19` (`import logging`) and
   `superset/commands/chart/restore.py:30` (`logger = logging.getLogger(__name__)`),
   confirming that the logger setup is dead code until actual logging calls are added.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=9531404a77df46c8b9574e896dc30009&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=9531404a77df46c8b9574e896dc30009&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/chart/restore.py
   **Line:** 19:30
   **Comment:**
   	*Code Quality: `logging` and `logger` are introduced but never used, which adds dead code and an unnecessary module import. Remove the unused logger setup (or add actual logging calls) to keep the command minimal and avoid lint/runtime overhead from unused symbols.
   
   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%2F40129&comment_hash=e8e4996278c93a0e1f848d6701220314dff4ba088cbe4b5eb9254406ec755d0f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=e8e4996278c93a0e1f848d6701220314dff4ba088cbe4b5eb9254406ec755d0f&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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4624947441

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4617244423

   <!-- translation-regression-bot -->
   ## ⚠️ Translation Regression Detected
   
   A source change in this PR renamed or reworded strings, invalidating existing translations (they are now `#, fuzzy`) in `ar`, `ca`, `cs`, `de`, `fi`, `fr`, `it`, `ja`, `ko`, `lv`, `mi`, `nl`, `pt`, `ru`, `sk`, `sl`, `th`, `tr`, `uk`. Please resolve the affected `.po` files before merging.
   
   _Note: intentionally **deleting** a translatable string is not a regression and is not flagged here — only translations invalidated by a renamed/reworded source string are._
   
   | Language | Fuzzy before | Fuzzy after | New |
   |----------|-------------:|------------:|----:|
   | `ar` | 1136 | 1137 | +1 |
   | `ca` | 815 | 816 | +1 |
   | `cs` | 787 | 788 | +1 |
   | `de` | 997 | 998 | +1 |
   | `fi` | 4824 | 4825 | +1 |
   | `fr` | 1014 | 1015 | +1 |
   | `it` | 1667 | 1668 | +1 |
   | `ja` | 322 | 323 | +1 |
   | `ko` | 1521 | 1522 | +1 |
   | `lv` | 295 | 296 | +1 |
   | `mi` | 807 | 808 | +1 |
   | `nl` | 1143 | 1144 | +1 |
   | `pt` | 1839 | 1840 | +1 |
   | `ru` | 293 | 294 | +1 |
   | `sk` | 774 | 775 | +1 |
   | `sl` | 963 | 964 | +1 |
   | `th` | 4824 | 4825 | +1 |
   | `tr` | 786 | 787 | +1 |
   | `uk` | 293 | 294 | +1 |
   
   ### How to fix
   
   **1. Install dependencies** (if not already set up):
   
   ```bash
   pip install -r superset/translations/requirements.txt
   sudo apt-get install gettext   # or: brew install gettext
   ```
   
   **2. Re-extract strings and sync `.po` files:**
   
   ```bash
   ./scripts/translations/babel_update.sh
   ```
   
   This rewrites `superset/translations/messages.pot` from the current source files and merges the changes into every `.po` file. Strings whose `msgid` changed will be marked `#, fuzzy`.
   
   **3. Resolve the fuzzy entries** in the affected language files (`ar`, `ca`, `cs`, `de`, `fi`, `fr`, `it`, `ja`, `ko`, `lv`, `mi`, `nl`, `pt`, `ru`, `sk`, `sl`, `th`, `tr`, `uk`):
   
   ```bash
   grep -n '#, fuzzy' superset/translations/<lang>/LC_MESSAGES/messages.po
   ```
   
   For each fuzzy entry, either rewrite the `msgstr` to match the new string and remove the `#, fuzzy` line, or clear the `msgstr` to `""` if you cannot provide a translation.
   
   **4. Commit your changes to the `.po` 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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3455360899


##########
superset/translations/ru/LC_MESSAGES/messages.po:
##########
@@ -3060,6 +3060,9 @@ msgstr "Изменения диаграммы"
 msgid "Chart could not be created."
 msgstr "Не удалось создать диаграмму"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Russian translation</b></div>
   <div id="fix">
   
   The new translation entry `msgid "Chart could not be restored."` has an empty `msgstr ""` with no `#, fuzzy` flag, meaning it will display the raw English text to Russian-speaking users when a chart restore fails. This degrades user experience for this locale.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/translations/ru/LC_MESSAGES/messages.po
    +++ b/superset/translations/ru/LC_MESSAGES/messages.po
    @@ -3061,6 +3061,7 @@ msgstr "Не удалось создать диаграмму"
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "Не удалось восстановить диаграмму."
    
     msgid "Chart could not be updated."
     msgstr "Не удалось обновить диаграмму."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #697b9f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/it/LC_MESSAGES/messages.po:
##########
@@ -2999,6 +2999,9 @@ msgstr "Ultima Modifica"
 msgid "Chart could not be created."
 msgstr "La tua query non può essere salvata"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Italian translation</b></div>
   <div id="fix">
   
   The `msgstr` for the new message ID is empty, leaving users with Italian locale seeing untranslated English text when this error occurs. Complete the translation using the same phrasing pattern as other chart error messages in this file.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/it/LC_MESSAGES/messages.po
    +++ superset/translations/it/LC_MESSAGES/messages.po
    @@ -3000,6 +3000,7 @@ msgstr "La tua query non pu\u00f2 essere salvata"
     msgid "Chart could not be restored."
     msgstr "La tua query non pu\u00f2 essere ripristinata"
    +
     msgid "Chart could not be updated."
     msgstr "La tua query non pu\u00f2 essere salvata"
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #697b9f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/lv/LC_MESSAGES/messages.po:
##########
@@ -3072,6 +3072,9 @@ msgstr "Diagrammas izmaiņas"
 msgid "Chart could not be created."
 msgstr "Diagrammu nevarēja izveidot."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing source template update</b></div>
   <div id="fix">
   
   The source template `messages.pot` does not contain `msgid "Chart could not be restored."`, but the English translation file does. This translation was added directly without going through the standard i18n workflow. The source template must be regenerated first (`pybabel extract` + `pybabel update`) to ensure all language files receive this new string and the entry is properly tracked.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1ed16d</i></small>
   </div><div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing translation for user-facing error</b></div>
   <div id="fix">
   
   The new translatable string "Chart could not be restored." (from `ChartRestoreFailedError` in `superset/commands/chart/exceptions.py:133`) has an empty `msgstr`. User-facing error messages should not be left untranslated. Latvian follows the pattern "Diagrammu nevarēja [verb]." based on adjacent entries.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/lv/LC_MESSAGES/messages.po
    +++ superset/translations/lv/LC_MESSAGES/messages.po
    @@ -3073,7 +3073,7 @@ msgstr "Diagrammu nevarēja izveidot."
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "Diagrammu nevarēja atjaunot."
    
     msgid "Chart could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #697b9f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/fa/LC_MESSAGES/messages.po:
##########
@@ -3065,6 +3065,9 @@ msgstr "تغییرات نمودار"
 msgid "Chart could not be created."
 msgstr "نمودار نتوانسته ایجاد شود."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Persian translation</b></div>
   <div id="fix">
   
   Empty `msgstr ""` at line 3069 will display as blank text to Persian-speaking users when `ChartRestoreFailedError` is raised in `superset/commands/chart/exceptions.py:133`. Other error messages in this file (e.g., lines 3066, 3072) have complete Persian translations. Add the Persian translation to avoid a degraded user experience.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #697b9f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/pt/LC_MESSAGES/messages.po:
##########
@@ -3045,6 +3045,9 @@ msgstr "Modificado pela última vez"
 msgid "Chart could not be created."
 msgstr "Não foi possível gravar a sua query"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Portuguese translation</b></div>
   <div id="fix">
   
   The Portuguese translation for "Chart could not be restored." is empty. Portuguese-speaking users will see this error in English instead. Use a similar phrasing to nearby translations (e.g., lines 3046, 3052) which use "Não foi possível" for "could not".
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/translations/pt/LC_MESSAGES/messages.po
    +++ b/superset/translations/pt/LC_MESSAGES/messages.po
    @@ -3046,7 +3046,7 @@ msgstr "Não foi possível gravar a sua query"
     msgid "Chart could not be created."
     msgstr "Não foi possível gravar a sua query"
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "Não foi possível restaurar o gráfico."
    
     msgid "Chart could not be updated."
     msgstr "Não foi possível gravar a sua query"
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #697b9f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/nl/LC_MESSAGES/messages.po:
##########
@@ -3118,6 +3118,9 @@ msgstr "Veranderingen in de grafiek"
 msgid "Chart could not be created."
 msgstr "Grafiek kon niet worden aangemaakt."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Dutch translation</b></div>
   <div id="fix">
   
   The new message "Chart could not be restored." is missing its Dutch translation. Dutch users will see the untranslated English error message at runtime. Following the established pattern in this file for similar error messages (lines 3118-3119, 3124-3125), provide a Dutch translation using the imperative form consistent with the existing translations.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/nl/LC_MESSAGES/messages.po (lines 3121-3122) ---
    3121: +msgid "Chart could not be restored."
    3122: +msgstr "De grafiek kon niet worden teruggezet."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #697b9f</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510308185


##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for local test-scaffolding variables in test files when the type is already unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing explicit type annotations for local mock/scaffolding variables in test files when the type is unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for local/test-scaffolding variables in test files when the type is unambiguous from context and the file follows surrounding test conventions.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/charts/api.py:
##########
@@ -134,7 +142,17 @@ def ensure_thumbnails_enabled(self) -> Optional[Response]:
         "warm_up_cache",
     }
     class_permission_name = "Chart"
-    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
+    # Custom methods (``restore``) need an explicit entry; FAB's @protect()
+    # decorator falls back to ``can_<method>_<class>`` (i.e.
+    # ``can_restore_Chart``) when the mapping is missing, which standard
+    # roles don't carry. Mirrors the permission model documented for
+    # ``DELETE`` / ``bulk_delete``: endpoint-level ``can_write`` plus
+    # resource-level ``raise_for_ownership``. See themes/api.py for the
+    # established pattern.
+    method_permission_name = {
+        **MODEL_API_RW_METHOD_PERMISSION_MAP,
+        "restore": "write",
+    }

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for clearly unambiguous local or class-level scaffolding variables when the surrounding file already follows that convention.
   
   **Applied to:**
     - `superset/charts/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "78a40c08b4be"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > In Alembic migration files, do not flag `down_revision` values that intentionally chain off the current single head on `master`; this is required to avoid forking the migration DAG and to pass migration-conflict checks.
   
   **Applied to:**
     - `**/migrations/versions/*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:
+        query = super().apply(query, value)
+        normalized = str(value).lower().strip() if value is not None else ""
+        if normalized not in {"include", "only"} or security_manager.is_admin():
+            return query
+
+        # Non-admins may only see soft-deleted charts they own. ``any()`` emits
+        # an EXISTS subquery so it composes with the base access filter without
+        # producing duplicate rows from a join.
+        owned = Slice.owners.any(security_manager.user_model.id == get_user_id())

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require additional type annotations for local variables in this file when the type is already unambiguous from context.
   
   **Applied to:**
     - `superset/charts/filters.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3364369687


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +49,90 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    # `user` is None for background / example-loader paths (no Flask request
+    # user). Combined with ``can_write=True`` (typically from
+    # ``ignore_permissions=True``), the ownership check below is intentionally
+    # skipped because the caller has already established trust at the command
+    # level. This matches pre-existing overwrite behaviour but now also applies
+    # to soft-deleted matches via ``needs_mutation``.
     user = get_user()
-    if existing:
-        if overwrite and can_write and user:
+
+    if existing := find_existing_for_import(Slice, config["uuid"]):
+        is_soft_deleted = existing.deleted_at is not None
+        needs_mutation = overwrite or is_soft_deleted

Review Comment:
   Follow-up before merge (noting here so it isn't lost): this fuses two distinct operations — *overwrite an alive chart* vs. *restore a soft-deleted one* — into a single `needs_mutation` flag, then re-discriminates them with `'restore' if is_soft_deleted else 'overwrite'` ternaries and the `if is_soft_deleted:` side-effect block below.
   
   **Plan:** extract an `_ImportOp` enum (`CREATE` / `RETURN_EXISTING` / `OVERWRITE` / `RESTORE`) and a pure, unit-testable `_resolve_import_op(existing, overwrite, can_write, user)` that owns the permission/ownership gate and returns the operation, keeping the restore side-effects gated by `op is _ImportOp.RESTORE`. Behavior-preserving except one fix: an alive row with `overwrite=True` but no `can_write` currently raises the wrong message (`"Chart was deleted and re-import requires can_write…"`).
   
   The same collapse exists in the datasets (#40130) and dashboards (#40128) importers — refactor all three together so the siblings stay consistent.
   



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3391960650


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +49,90 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    # `user` is None for background / example-loader paths (no Flask request
+    # user). Combined with ``can_write=True`` (typically from
+    # ``ignore_permissions=True``), the ownership check below is intentionally
+    # skipped because the caller has already established trust at the command
+    # level. This matches pre-existing overwrite behaviour but now also applies
+    # to soft-deleted matches via ``needs_mutation``.
     user = get_user()
-    if existing:
-        if overwrite and can_write and user:
+
+    if existing := find_existing_for_import(Slice, config["uuid"]):
+        is_soft_deleted = existing.deleted_at is not None
+        needs_mutation = overwrite or is_soft_deleted

Review Comment:
   Done — `import_chart` no longer fuses the two operations: it now branches explicitly on `existing.deleted_at is not None` (RESTORE) vs `else` (OVERWRITE), and `needs_mutation` is gone. The same split was applied to the dashboards and datasets importers. Resolving.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4664677630

   @richardfogaca — heads-up that this has changed since your approval, so it'll need another look. Rebased onto current master; the changes since:
   
   - **Deleted-state listing audience** — scoped `ChartDeletedStateFilter` to the restore audience (owners/admins), matching the decision on the dashboards PR (#40128) and `RestoreChartCommand`'s `raise_for_ownership`. A read-access non-owner can no longer enumerate soft-deleted charts they can't restore; live rows keep normal `ChartFilter` visibility. Added integration coverage (owner sees own deleted; gamma with datasource access does not).
   - **Migration head** — re-pointed `add_deleted_at_to_slices` `down_revision` from `33d7e0e21daa` to `31dae2559c05` (master's current head) to avoid an alembic multi-head against current master. (Will be re-pointed onto the dashboards migration during the charts→dashboards→datasets merge sequence.)
   - **Importer Case B** — keyed on `is_soft_deleted` rather than the fused `needs_mutation`, so an active chart re-imported with `overwrite=True` but no `can_write` returns the existing row instead of raising the restore error. Added a regression test.
   
   CI is green on HEAD `b9032c54`.
   


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3338050658


##########
superset/charts/api.py:
##########
@@ -122,6 +129,7 @@ def ensure_thumbnails_enabled(self) -> Optional[Response]:
         RouteMethod.IMPORT,
         RouteMethod.RELATED,
         "bulk_delete",  # not using RouteMethod since locally defined
+        "restore",

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing RBAC permission for restore</b></div>
   <div id="fix">
   
   The `restore` route is exposed via `include_route_methods` at line 132 but `method_permission_name` at line 143 only inherits `MODEL_API_RW_METHOD_PERMISSION_MAP`, which does not define `"restore"`. FAB's `@protect()` decorator uses `method_permission_name` to gate access — a method not listed defaults to an unpredictable fallback. Adding `"restore": "write"` aligns with the pattern in `themes/api.py:83-89` for custom methods and ensures the endpoint requires the same write permission as `bulk_delete`.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/charts/api.py
    +++ b/superset/charts/api.py
    @@ -140,7 +140,10 @@ class ChartRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
             "warm_up_cache",
         }
         class_permission_name = "Chart"
    -    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
    +    method_permission_name = {
    +        **MODEL_API_RW_METHOD_PERMISSION_MAP,
    +        "restore": "write",
    +    }
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #2eef54</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3365146771


##########
superset/commands/chart/restore.py:
##########
@@ -0,0 +1,43 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command to restore a soft-deleted chart."""
+
+import logging
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+    ChartRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.daos.chart import ChartDAO
+from superset.models.slice import Slice
+
+logger = logging.getLogger(__name__)

Review Comment:
   Fixed in be349a7189 — removed the unused `logger`/`import logging` from `RestoreChartCommand`. The command does no logging; matches the datasets restore command which already had this cleaned up.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342332524


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   test comment



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   test comment



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4616226863

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3454234086


##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:

Review Comment:
   **Suggestion:** Add a docstring to this newly added method to describe its deleted-state filtering behavior and ownership scoping logic. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new `ChartDeletedStateFilter.apply` method has no docstring. The custom rule explicitly requires newly added Python functions and classes to include docstrings, so this is a real violation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=3f24a69735d44d8eadf096720cd47ce8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=3f24a69735d44d8eadf096720cd47ce8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/charts/filters.py
   **Line:** 221:221
   **Comment:**
   	*Custom Rule: Add a docstring to this newly added method to describe its deleted-state filtering behavior and ownership scoping logic.
   
   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%2F40129&comment_hash=1bc211ef42e1177d2913881cbb5411b8ec6502467d7a37c5d5682c6cd16220f5&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=1bc211ef42e1177d2913881cbb5411b8ec6502467d7a37c5d5682c6cd16220f5&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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4860978238

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4896304750

   **Bito Automatic Review Skipped – PR Already Merged**<br/><br/>Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.<br/>No action is needed if you didn't intend to review it. To get a review, you can type `/review` in a comment and save it


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3509705150


##########
superset/commands/report/exceptions.py:
##########
@@ -225,6 +225,13 @@ class ReportScheduleExecuteUnexpectedError(CommandException):
     message = _("Report Schedule execution got an unexpected error.")
 
 
+class ReportScheduleTargetChartDeletedError(CommandException):

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing HTTP status code for not-found error</b></div>
   <div id="fix">
   
   The new exception inherits `status = 500` from `SupersetException` (line 30), but the error describes a client-side "not found" condition (target chart was deleted), not a server misconfiguration. Add `status = 404` to match the pattern of `ReportScheduleNotFoundError` (line 176) which uses the same status for similar "target entity not found" scenarios. Without this, HTTP responses will incorrectly return 500 instead of 404.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c2c31c</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/fr/LC_MESSAGES/messages.po:
##########
@@ -3117,6 +3117,9 @@ msgstr "Changements de graphique"
 msgid "Chart could not be created."
 msgstr "Le graphique n'a pas pu être créé."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing French translation</b></div>
   <div id="fix">
   
   Empty French translation will display English text to French-speaking users when chart restore fails. Add proper translation following established pattern.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c2c31c</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/pt_BR/LC_MESSAGES/messages.po:
##########
@@ -3194,6 +3194,9 @@ msgstr "Alterações no gráfico"
 msgid "Chart could not be created."
 msgstr "Não foi possível criar o gráfico."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing pt_BR translation</b></div>
   <div id="fix">
   
   The new entry for 'Chart could not be restored.' has an empty `msgstr` field. Brazilian Portuguese users will see the untranslated English error message. Apply translation following the established pattern: "Não foi possível restaurar o gráfico."
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c2c31c</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510245445


##########
superset/daos/dashboard.py:
##########
@@ -276,11 +277,30 @@ def set_dash_metadata(
                 if isinstance(value, dict)
             ]
 
-            current_slices = (
-                db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
-            )
-
-            dashboard.slices = current_slices
+            # Bypass the soft-delete visibility filter when resolving the
+            # incoming chart ids: a dashboard's ``position_json`` may still
+            # reference a chart that is currently soft-deleted, and this
+            # assignment REBUILDS ``dashboard.slices`` wholesale. With the
+            # filter active, the hidden member would be silently dropped —
+            # deleting its ``dashboard_slices`` junction row (breaking the
+            # documented restore-reattach contract) and writing
+            # ``uuid: None`` into its position slot via ``uuid_map`` below.
+            #
+            # The bypass must be session-scoped and cover the ASSIGNMENT,
+            # not just the resolution query: assigning to
+            # ``dashboard.slices`` makes the unit of work diff the new
+            # collection against the existing one, which it lazy-loads at
+            # that moment. A filtered baseline load would exclude the
+            # trashed member, so the diff would treat it as net-new and
+            # INSERT a ``dashboard_slices`` row that still exists (soft
+            # delete never removes junction rows) — an IntegrityError on
+            # the composite primary key on every save of a dashboard
+            # containing a trashed chart.
+            with skip_visibility_filter(db.session, Slice):
+                current_slices = (
+                    db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
+                )

Review Comment:
   **Suggestion:** Add an explicit type annotation for the newly introduced local query result variable to comply with the type-hint requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new local variable `current_slices` is assigned a list of `Slice` objects but has no type annotation. This matches the rule requiring type hints for relevant new or modified Python variables that can be annotated.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=76b953bf2a0345448db26cf5521bb850&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=76b953bf2a0345448db26cf5521bb850&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/daos/dashboard.py
   **Line:** 300:302
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for the newly introduced local query result variable to comply with the type-hint requirement for relevant variables.
   
   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%2F40129&comment_hash=d22994aeb7cacbff1ff49195e461e9f5d559f9db20e668141e985be4ee982740&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=d22994aeb7cacbff1ff49195e461e9f5d559f9db20e668141e985be4ee982740&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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510309536


##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for dynamically imported modules in test-scaffolding or test-only files when the type is already clear from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/daos/dashboard.py:
##########
@@ -276,11 +277,30 @@ def set_dash_metadata(
                 if isinstance(value, dict)
             ]
 
-            current_slices = (
-                db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
-            )
-
-            dashboard.slices = current_slices
+            # Bypass the soft-delete visibility filter when resolving the
+            # incoming chart ids: a dashboard's ``position_json`` may still
+            # reference a chart that is currently soft-deleted, and this
+            # assignment REBUILDS ``dashboard.slices`` wholesale. With the
+            # filter active, the hidden member would be silently dropped —
+            # deleting its ``dashboard_slices`` junction row (breaking the
+            # documented restore-reattach contract) and writing
+            # ``uuid: None`` into its position slot via ``uuid_map`` below.
+            #
+            # The bypass must be session-scoped and cover the ASSIGNMENT,
+            # not just the resolution query: assigning to
+            # ``dashboard.slices`` makes the unit of work diff the new
+            # collection against the existing one, which it lazy-loads at
+            # that moment. A filtered baseline load would exclude the
+            # trashed member, so the diff would treat it as net-new and
+            # INSERT a ``dashboard_slices`` row that still exists (soft
+            # delete never removes junction rows) — an IntegrityError on
+            # the composite primary key on every save of a dashboard
+            # containing a trashed chart.
+            with skip_visibility_filter(db.session, Slice):
+                current_slices = (
+                    db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
+                )

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for unambiguous local variables in this DAO file; follow the surrounding file's existing style when the type is clear from context.
   
   **Applied to:**
     - `superset/daos/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510308926


##########
superset/translations/pt_BR/LC_MESSAGES/messages.po:
##########
@@ -3194,6 +3194,9 @@ msgstr "Alterações no gráfico"
 msgid "Chart could not be created."
 msgstr "Não foi possível criar o gráfico."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate for maintaining translation consistency. In the context of gettext catalogs, while an empty `msgstr` is technically valid and causes a fallback to the source text, providing the translation ensures that the application is fully localized for the target language, avoiding mixed-language interfaces for users.
   
   **superset/translations/pt_BR/LC_MESSAGES/messages.po**
   ```
   msgid "Chart could not be restored."
   msgstr "Não foi possível restaurar o gráfico."
   ```



##########
superset/commands/report/exceptions.py:
##########
@@ -225,6 +225,13 @@ class ReportScheduleExecuteUnexpectedError(CommandException):
     message = _("Report Schedule execution got an unexpected error.")
 
 
+class ReportScheduleTargetChartDeletedError(CommandException):

Review Comment:
   <!-- Bito Reply -->
   The reviewer's suggestion to use a 404 status code for the new exception is based on the pattern of other 'not found' exceptions in the codebase. However, your assessment that this specific exception should remain a 500 error is appropriate given that it is raised within the Celery report executor, where a 5xx status is required to trigger the necessary task failure and alerting mechanisms for ops.



##########
superset/translations/fr/LC_MESSAGES/messages.po:
##########
@@ -3117,6 +3117,9 @@ msgstr "Changements de graphique"
 msgid "Chart could not be created."
 msgstr "Le graphique n'a pas pu être créé."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The reviewer's suggestion is correct. In the context of `gettext` and `.po` files, an empty `msgstr` is the standard way to indicate that a string is untranslated. This ensures that the application falls back to the source text (English) for that specific string, which is the expected behavior for newly added strings until a translator provides the translation.
   
   **superset/translations/fr/LC_MESSAGES/messages.po**
   ```
   +msgid "Chart could not be restored."
   +msgstr ""
   ```



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4862779514

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4654976831

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4636331730

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3397904594


##########
superset/charts/filters.py:
##########
@@ -180,3 +181,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:
+        query = super().apply(query, value)
+        normalized = str(value).lower().strip() if value is not None else ""
+        if normalized not in {"include", "only"} or security_manager.is_admin():
+            return query
+
+        # Non-admins may only see soft-deleted charts they own. ``any()`` emits
+        # an EXISTS subquery so it composes with the base access filter without
+        # producing duplicate rows from a join.
+        owned = Slice.owners.any(security_manager.user_model.id == get_user_id())
+        if normalized == "only":
+            # ``super().apply`` already restricted to ``deleted_at IS NOT NULL``.
+            return query.filter(owned)
+        # ``include``: keep all live rows (normal access) and add only the
+        # soft-deleted rows this user owns.
+        return query.filter(or_(Slice.deleted_at.is_(None), owned))

Review Comment:
   **Suggestion:** Add a method docstring to this newly introduced function so the new API behavior is documented inline, consistent with the requirement that new functions/classes include docstrings. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly introduced Python method in the added class, and it has no docstring. The custom rule requires new Python functions and classes to include docstrings, so the suggestion correctly identifies a real violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=71d2dbe2dce24768bdef0f3add70feda&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=71d2dbe2dce24768bdef0f3add70feda&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/charts/filters.py
   **Line:** 205:220
   **Comment:**
   	*Custom Rule: Add a method docstring to this newly introduced function so the new API behavior is documented inline, consistent with the requirement that new functions/classes include docstrings.
   
   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%2F40129&comment_hash=f7f56580c432bfcf25f228a5fbbf0888eccd481fd283a251b99de4a2d100335a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=f7f56580c432bfcf25f228a5fbbf0888eccd481fd283a251b99de4a2d100335a&reaction=dislike'>👎</a>



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 31dae2559c05
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "31dae2559c05"
+
+TABLE_NAME = "slices"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"
+
+
+def upgrade() -> None:
+    add_columns(TABLE_NAME, Column("deleted_at", DateTime(), nullable=True))
+    create_index(TABLE_NAME, INDEX_NAME, ["deleted_at"])

Review Comment:
   **Suggestion:** Add an inline docstring to this new function describing the migration step it applies so the function is self-documented per the project rule. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The function is newly added in this file and has no docstring. The custom rule requires newly added Python functions and classes to include docstrings, so this is a real violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=47b5fd8e0ef6414aa91f3fd1de1b983b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=47b5fd8e0ef6414aa91f3fd1de1b983b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py
   **Line:** 45:47
   **Comment:**
   	*Custom Rule: Add an inline docstring to this new function describing the migration step it applies so the function is self-documented per the project rule.
   
   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%2F40129&comment_hash=720a13f73499e78b1363b916137c388ac1054440683b2912f1c354e919a2410a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=720a13f73499e78b1363b916137c388ac1054440683b2912f1c354e919a2410a&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"
+
+
+@pytest.fixture
+def engine() -> Engine:
+    """In-memory SQLite seeded with a minimal pre-migration ``slices`` table.
+
+    The real ``slices`` table has many columns; the migration only touches
+    ``deleted_at`` and its index, so only the columns that participate in
+    the test are seeded.
+    """
+    engine = create_engine("sqlite:///:memory:")
+    md = MetaData()
+    Table(
+        TABLE_NAME,
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("slice_name", String(250), nullable=False),
+    )
+    md.create_all(engine)
+    return engine
+
+
+def _columns(engine: Engine) -> set[str]:
+    return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)}
+
+
+def _indexes(engine: Engine) -> set[str]:

Review Comment:
   **Suggestion:** Add a concise docstring to this newly added helper function describing that it returns the index names for the target table. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This newly added helper function has no docstring. Since the rule requires newly added Python functions to include docstrings, the suggestion identifies a genuine violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d2690bcdebe14b8a8ee2c0c220dfe242&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d2690bcdebe14b8a8ee2c0c220dfe242&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 83:83
   **Comment:**
   	*Custom Rule: Add a concise docstring to this newly added helper function describing that it returns the index names for the target table.
   
   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%2F40129&comment_hash=4de8450bf70e944de5ee1695973bc1fc0180ed1402e682c7c1bb793aa7873613&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=4de8450bf70e944de5ee1695973bc1fc0180ed1402e682c7c1bb793aa7873613&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"
+
+
+@pytest.fixture
+def engine() -> Engine:
+    """In-memory SQLite seeded with a minimal pre-migration ``slices`` table.
+
+    The real ``slices`` table has many columns; the migration only touches
+    ``deleted_at`` and its index, so only the columns that participate in
+    the test are seeded.
+    """
+    engine = create_engine("sqlite:///:memory:")
+    md = MetaData()
+    Table(
+        TABLE_NAME,
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("slice_name", String(250), nullable=False),
+    )
+    md.create_all(engine)
+    return engine
+
+
+def _columns(engine: Engine) -> set[str]:
+    return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)}
+
+
+def _indexes(engine: Engine) -> set[str]:
+    return {ix["name"] for ix in inspect(engine).get_indexes(TABLE_NAME)}
+
+
+def test_upgrade_adds_deleted_at_column_and_index(engine: Engine) -> None:

Review Comment:
   **Suggestion:** Add a docstring to this new test function to describe the upgrade behavior it verifies. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added test function and it does not have a docstring in the final file state. That violates the rule requiring new functions to be documented inline.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=fb4ae302ed744d289c415f1573e1aea1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=fb4ae302ed744d289c415f1573e1aea1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 87:87
   **Comment:**
   	*Custom Rule: Add a docstring to this new test function to describe the upgrade behavior it verifies.
   
   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%2F40129&comment_hash=28f41eedc3446a60b5ec4dec3692a2e2f6980b04831cf3a4eb0b4e8869398fff&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=28f41eedc3446a60b5ec4dec3692a2e2f6980b04831cf3a4eb0b4e8869398fff&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"
+
+
+@pytest.fixture
+def engine() -> Engine:
+    """In-memory SQLite seeded with a minimal pre-migration ``slices`` table.
+
+    The real ``slices`` table has many columns; the migration only touches
+    ``deleted_at`` and its index, so only the columns that participate in
+    the test are seeded.
+    """
+    engine = create_engine("sqlite:///:memory:")
+    md = MetaData()
+    Table(
+        TABLE_NAME,
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("slice_name", String(250), nullable=False),
+    )
+    md.create_all(engine)
+    return engine
+
+
+def _columns(engine: Engine) -> set[str]:
+    return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)}
+
+
+def _indexes(engine: Engine) -> set[str]:
+    return {ix["name"] for ix in inspect(engine).get_indexes(TABLE_NAME)}
+
+
+def test_upgrade_adds_deleted_at_column_and_index(engine: Engine) -> None:
+    with engine.connect() as conn:
+        ctx = MigrationContext.configure(conn)
+        with Operations.context(ctx):
+            migration.upgrade()
+
+    assert "deleted_at" in _columns(engine), "upgrade() must add the deleted_at column"
+    assert INDEX_NAME in _indexes(engine), (
+        "upgrade() must create the supporting index on deleted_at"
+    )
+
+
+def test_downgrade_drops_deleted_at_column_and_index(engine: Engine) -> None:
+    with engine.connect() as conn:
+        ctx = MigrationContext.configure(conn)
+        with Operations.context(ctx):
+            migration.upgrade()
+            migration.downgrade()
+
+    assert "deleted_at" not in _columns(engine), (
+        "downgrade() must drop the deleted_at column"
+    )
+    assert INDEX_NAME not in _indexes(engine), (
+        "downgrade() must drop the supporting index"
+    )
+
+
+def test_downgrade_preserves_soft_deleted_row_data(engine: Engine) -> None:
+    """Pin the operator-facing contract from ``UPDATING.md``: rows that
+    were soft-deleted before the migration is reversed survive the
+    downgrade. The ``deleted_at`` column is gone, so those rows are
+    indistinguishable from live rows to any code path that no longer
+    applies the visibility filter — operators must decide on
+    hard-delete, restore, or rename BEFORE downgrading. See the
+    "Rollback note" in ``UPDATING.md``.
+    """
+    with engine.connect() as conn:
+        ctx = MigrationContext.configure(conn)
+        with Operations.context(ctx):
+            migration.upgrade()
+
+            slices = Table(TABLE_NAME, MetaData(), autoload_with=conn)
+            conn.execute(
+                insert(slices).values(
+                    [
+                        {
+                            "id": 1,
+                            "slice_name": "live_chart",
+                            "deleted_at": None,
+                        },
+                        {
+                            "id": 2,
+                            "slice_name": "archived_chart",
+                            "deleted_at": datetime(2026, 1, 1, 12, 0, 0),
+                        },
+                    ]
+                )
+            )
+
+            migration.downgrade()
+
+            slices_after = Table(TABLE_NAME, MetaData(), autoload_with=conn)
+            rows = conn.execute(
+                select(slices_after).order_by(slices_after.c.id)
+            ).fetchall()
+
+    assert [(r.id, r.slice_name) for r in rows] == [
+        (1, "live_chart"),
+        (2, "archived_chart"),
+    ], (
+        "downgrade() must not delete or mutate row data — soft-deleted "
+        "rows become indistinguishable from live rows but they remain"
+    )
+    assert "deleted_at" not in {
+        c["name"] for c in inspect(engine).get_columns(TABLE_NAME)
+    }
+
+
+def test_upgrade_is_idempotent(engine: Engine) -> None:

Review Comment:
   **Suggestion:** Add a docstring to this new test function describing the idempotency expectation for repeated upgrade execution. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added test function and it does not include a docstring in the final file state. That matches the custom rule violation for new functions lacking docstrings.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=da91f100569a433faaa613418293d8e2&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=da91f100569a433faaa613418293d8e2&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 165:165
   **Comment:**
   	*Custom Rule: Add a docstring to this new test function describing the idempotency expectation for repeated upgrade execution.
   
   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%2F40129&comment_hash=9e3a6c7df8fa9a26593752aea24252deceeafd76cf253ce4adceb4dd0ba33d3f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=9e3a6c7df8fa9a26593752aea24252deceeafd76cf253ce4adceb4dd0ba33d3f&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"
+
+
+@pytest.fixture
+def engine() -> Engine:
+    """In-memory SQLite seeded with a minimal pre-migration ``slices`` table.
+
+    The real ``slices`` table has many columns; the migration only touches
+    ``deleted_at`` and its index, so only the columns that participate in
+    the test are seeded.
+    """
+    engine = create_engine("sqlite:///:memory:")
+    md = MetaData()
+    Table(
+        TABLE_NAME,
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("slice_name", String(250), nullable=False),
+    )
+    md.create_all(engine)
+    return engine
+
+
+def _columns(engine: Engine) -> set[str]:
+    return {col["name"] for col in inspect(engine).get_columns(TABLE_NAME)}
+
+
+def _indexes(engine: Engine) -> set[str]:
+    return {ix["name"] for ix in inspect(engine).get_indexes(TABLE_NAME)}
+
+
+def test_upgrade_adds_deleted_at_column_and_index(engine: Engine) -> None:
+    with engine.connect() as conn:
+        ctx = MigrationContext.configure(conn)
+        with Operations.context(ctx):
+            migration.upgrade()
+
+    assert "deleted_at" in _columns(engine), "upgrade() must add the deleted_at column"
+    assert INDEX_NAME in _indexes(engine), (
+        "upgrade() must create the supporting index on deleted_at"
+    )
+
+
+def test_downgrade_drops_deleted_at_column_and_index(engine: Engine) -> None:

Review Comment:
   **Suggestion:** Add a docstring to this new test function clarifying that it validates downgrade removal of both schema artifacts. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This newly added test function has no docstring. The custom rule explicitly flags new Python functions without docstrings, so the violation is real.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=167126cade7d47f79f2b0f675162633e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=167126cade7d47f79f2b0f675162633e&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 99:99
   **Comment:**
   	*Custom Rule: Add a docstring to this new test function clarifying that it validates downgrade removal of both schema artifacts.
   
   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%2F40129&comment_hash=ff1fb8662357da65f4406aa96eff861abe0ffbfb76f42dc1fd328b08bc817a13&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=ff1fb8662357da65f4406aa96eff861abe0ffbfb76f42dc1fd328b08bc817a13&reaction=dislike'>👎</a>



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"
+
+
+@pytest.fixture
+def engine() -> Engine:
+    """In-memory SQLite seeded with a minimal pre-migration ``slices`` table.
+
+    The real ``slices`` table has many columns; the migration only touches
+    ``deleted_at`` and its index, so only the columns that participate in
+    the test are seeded.
+    """
+    engine = create_engine("sqlite:///:memory:")
+    md = MetaData()
+    Table(
+        TABLE_NAME,
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("slice_name", String(250), nullable=False),
+    )
+    md.create_all(engine)
+    return engine
+
+
+def _columns(engine: Engine) -> set[str]:

Review Comment:
   **Suggestion:** Add a short docstring to this newly added helper function explaining that it returns the current column names for the target table. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python helper function and it has no docstring in the final file state. The custom rule requires new functions to be documented inline, so this is a real violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=73d71f04d793461888c781a7286e033f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=73d71f04d793461888c781a7286e033f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/migrations/test_add_deleted_at_to_slices.py
   **Line:** 79:79
   **Comment:**
   	*Custom Rule: Add a short docstring to this newly added helper function explaining that it returns the current column names for the target table.
   
   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%2F40129&comment_hash=1f8dd6ecc83953402dcffc7d689a3c4937eab9c657439b4b4e02dd58cf8e92c4&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=1f8dd6ecc83953402dcffc7d689a3c4937eab9c657439b4b4e02dd58cf8e92c4&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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3397904608


##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 31dae2559c05
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "31dae2559c05"
+
+TABLE_NAME = "slices"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"
+
+
+def upgrade() -> None:
+    add_columns(TABLE_NAME, Column("deleted_at", DateTime(), nullable=True))
+    create_index(TABLE_NAME, INDEX_NAME, ["deleted_at"])
+
+
+def downgrade() -> None:
+    drop_index(TABLE_NAME, INDEX_NAME)
+    drop_columns(TABLE_NAME, "deleted_at")

Review Comment:
   **Suggestion:** Add an inline docstring to this new function describing the rollback behavior so it meets the requirement that new functions are documented. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The downgrade function is newly added and lacks a docstring. This matches the custom rule requiring new Python functions and classes to be documented inline.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f85f00584d234dfb869c4a2a4b435e7d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f85f00584d234dfb869c4a2a4b435e7d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py
   **Line:** 50:52
   **Comment:**
   	*Custom Rule: Add an inline docstring to this new function describing the rollback behavior so it meets the requirement that new functions are documented.
   
   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%2F40129&comment_hash=58a395dd12347bc76eb6f5baf84c326867a0df45a62e03830c7485625eec13e2&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=58a395dd12347bc76eb6f5baf84c326867a0df45a62e03830c7485625eec13e2&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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4606022871

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4675282630

   Closing the batch of bito **empty-`msgstr`** findings on the new *"Chart could not be restored."* string as not actionable. In Superset's i18n workflow an empty `msgstr` is the expected initial state for a newly-added source string: gettext falls back to the English `msgid`, and translations are filled in later through the project translation process — they are not hand-authored in a feature PR (machine-translating into 20+ locales without review would be wrong). These entries were deliberately seeded empty (see the `i18n(charts): seed empty msgstr …` commit). Resolving the related per-locale threads.


-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3500177838


##########
superset/models/slice.py:
##########
@@ -67,7 +71,7 @@
 
 
 class Slice(  # pylint: disable=too-many-public-methods
-    CoreChart, AuditMixinNullable, ImportExportMixin
+    CoreChart, SoftDeleteMixin, AuditMixinNullable, ImportExportMixin

Review Comment:
   **Suggestion:** Adding `SoftDeleteMixin` here immediately changes all chart deletes to soft-delete through `BaseDAO.delete()` with no feature-flag guard in this branch, so environments expecting hard-delete semantics will silently get different behavior. Gate this rollout behind the `SOFT_DELETE` toggle in the delete path (or defer this inheritance until that guard is present) to avoid shipping unguarded behavior changes. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Chart DELETE endpoint always soft-deletes charts without gating.
   - ⚠️ Hard-delete expectations broken; rows remain in slices table.
   - ⚠️ Soft-deleted charts accumulate, increasing database storage usage.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Observe that the `Slice` ORM model now inherits `SoftDeleteMixin` in
   `superset/models/slice.py:73-75`, specifically the base-class line `CoreChart,
   SoftDeleteMixin, AuditMixinNullable, ImportExportMixin` at line 74 (from the PR hunk and
   Grep output).
   
   2. Follow the chart delete API entrypoint: `DELETE /api/v1/chart/<pk>` is handled by
   `delete(self, pk: int)` in `superset/charts/api.py:483-501`, which (per the body at lines
   ~520-522 in the same file) calls `DeleteChartCommand([pk]).run()`.
   
   3. In `superset/commands/chart/delete.py:16-21`, `DeleteChartCommand.run()` calls
   `ChartDAO.delete(self._models)`. `ChartDAO` is defined as `class
   ChartDAO(BaseDAO[Slice]):` in `superset/daos/chart.py:45`, so `BaseDAO`’s generic
   machinery (`__init_subclass__` in `superset/daos/base.py:45-48`) sets `ChartDAO.model_cls`
   to `Slice`.
   
   4. In `superset/daos/base.py:523-532`, `BaseDAO.delete()` checks `if cls.model_cls is not
   None and issubclass(cls.model_cls, SoftDeleteMixin):` (lines 524-539) and, for such
   models, calls `cls.soft_delete(items)`. Because `Slice` now subclasses `SoftDeleteMixin`,
   `ChartDAO.delete()` always routes to `BaseDAO.soft_delete()` (lines 493-502), which
   iterates items and calls `item.soft_delete()`. `SoftDeleteMixin.soft_delete()` in
   `superset/models/helpers.py:743-748` sets `self.deleted_at = datetime.now()` without
   removing the row. There is no feature-flag or `SOFT_DELETE` toggle anywhere in the repo
   (confirmed by `Grep` returning no matches for `SOFT_DELETE` under `/workspace/superset`).
   As a result, every call to the chart DELETE API now performs a soft delete instead of the
   previous hard delete, unconditionally changing behaviour for all environments.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=520b72cb0bd1408aa6e04787963b0154&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=520b72cb0bd1408aa6e04787963b0154&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/models/slice.py
   **Line:** 74:74
   **Comment:**
   	*Logic Error: Adding `SoftDeleteMixin` here immediately changes all chart deletes to soft-delete through `BaseDAO.delete()` with no feature-flag guard in this branch, so environments expecting hard-delete semantics will silently get different behavior. Gate this rollout behind the `SOFT_DELETE` toggle in the delete path (or defer this inheritance until that guard is present) to avoid shipping unguarded behavior changes.
   
   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%2F40129&comment_hash=e2596a7c48e57da59d1c61c635f07fccf4a35e5500f302df078aa743ca786809&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=e2596a7c48e57da59d1c61c635f07fccf4a35e5500f302df078aa743ca786809&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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510308863


##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Avoid flagging missing type annotations for local test-scaffolding variables in test files when the type is already unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Avoid flagging missing concrete type annotations for local/test-scaffolding variables in test files when the type is unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "78a40c08b4be"
+
+TABLE_NAME = "slices"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for obvious module-level constants in migration files; follow the surrounding migration file conventions.
   
   **Applied to:**
     - `**/migration*/**`
     - `**/*migration*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > In test files, do not require explicit type annotations for local test-scaffolding variables when the type is already unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self) -> None:
+        """DELETE /api/v1/chart/<pk> sets deleted_at instead of removing."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("soft_delete_test", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # Row still exists in DB with deleted_at set
+        row = (
+            db.session.query(Slice)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+            .filter(Slice.id == chart_id)
+            .one_or_none()
+        )
+        assert row is not None
+        assert row.deleted_at is not None
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_excluded_from_get(self) -> None:
+        """GET /api/v1/chart/<pk> returns 404 for a soft-deleted chart."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("invisible_chart", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.get(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_excluded_from_list(self) -> None:
+        """GET /api/v1/chart/ should not include soft-deleted charts."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("listed_then_deleted", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.get("/api/v1/chart/")
+        data = json.loads(rv.data)
+        chart_ids = [c["id"] for c in data["result"]]
+        assert chart_id not in chart_ids
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/chart/ with chart_deleted_state=include returns deleted charts."""  # noqa: E501
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("listed_with_deleted", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+
+        rison_query = "(filters:!((col:id,opr:chart_deleted_state,value:include)))"
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+
+        data = json.loads(rv.data)
+        deleted_row = next(
+            (row for row in data["result"] if row["id"] == chart_id),
+            None,
+        )
+        assert deleted_row is not None
+        assert deleted_row["deleted_at"] is not None
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_only_filter_returns_only_soft_deleted_charts(self) -> None:
+        """chart_deleted_state=only excludes live rows and returns only deleted ones."""
+        admin_id = self.get_user("admin").id
+        live_chart = self.insert_chart("only_live", [admin_id], 1)
+        deleted_chart = self.insert_chart("only_deleted", [admin_id], 1)
+        live_id = live_chart.id
+        deleted_id = deleted_chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{deleted_id}")
+
+        rison_query = "(filters:!((col:id,opr:chart_deleted_state,value:only)))"
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+
+        data = json.loads(rv.data)
+        returned_ids = {row["id"] for row in data["result"]}
+        assert deleted_id in returned_ids
+        assert live_id not in returned_ids
+
+        # Cleanup
+        _hard_delete_chart(live_id)
+        _hard_delete_chart(deleted_id)
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted charts.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha_id = self.get_user(ALPHA_USERNAME).id
+        chart = self.insert_chart("sd_owner_chart", [alpha_id], 1)
+        chart_id = chart.id
+
+        chart.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:chart_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [c["id"] for c in json.loads(rv.data)["result"]]
+        assert chart_id in ids
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a chart once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the chart's dataset, so
+        ``ChartFilter`` makes the chart visible to gamma while it is live. After
+        soft-delete, the deleted-state list is scoped to the restore audience
+        (owners/admins), so gamma — who could never restore it — must not see it
+        via ``include`` or ``only``.
+        """
+        admin_id = self.get_user(ADMIN_USERNAME).id
+        chart = self.insert_chart("sd_acl_chart", [admin_id], 1)
+        chart_id = chart.id
+
+        table = db.session.query(SqlaTable).get(1)
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu("datasource_access", table.perm)
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the chart while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/chart/?q=(page_size:200)")
+            assert chart_id in [c["id"] for c in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live chart via datasource access"
+            )
+
+            # Soft-delete directly (avoids a mid-test re-login to admin).
+            reloaded = (
+                db.session.query(Slice)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+                .filter(Slice.id == chart_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            # Gamma must not see the soft-deleted chart in either mode.
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:chart_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [c["id"] for c in json.loads(rv.data)["result"]]
+                assert chart_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"chart via chart_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", table.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            _hard_delete_chart(chart_id)
+
+    def test_delete_already_soft_deleted_chart_returns_404(self) -> None:
+        """DELETE on an already soft-deleted chart returns 404 (FR-008)."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("double_delete_test", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_delete_chart_blocked_when_active_report_references_it(self) -> None:
+        """DELETE /api/v1/chart/<id> returns 422 when a report references it.
+
+        Pins down the existing API protection in `DeleteChartCommand.validate()`:
+        when a `report_schedule` row references the chart, the validation
+        raises `ChartDeleteFailedReportsExistError` *before* `ChartDAO.delete()`
+        is invoked, so no soft-delete routing happens. This is the contract
+        soft-delete inherits from the pre-existing API and is what makes the
+        "report-execution against soft-deleted target" crash class
+        (commands/report/execute.py:_get_url) unreachable through the API.
+        """
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("blocked_by_report_test", [admin_id], 1)
+        chart_id = chart.id
+
+        report = ReportSchedule(
+            type=ReportScheduleType.REPORT,
+            name="blocking_report_for_chart_delete",
+            description="Report that should block chart deletion",
+            crontab="0 9 * * *",
+            chart=chart,
+            creation_method=ReportCreationMethod.ALERTS_REPORTS,
+        )
+        db.session.add(report)
+        db.session.commit()
+        report_id = report.id
+
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 422
+        body = json.loads(rv.data)
+        assert "associated alerts or reports" in body.get("message", "").lower() or (
+            "associated" in body.get("message", "").lower()
+            and "report" in body.get("message", "").lower()
+        )
+        assert "blocking_report_for_chart_delete" in body.get("message", "")
+
+        # Confirm the chart was NOT soft-deleted (deleted_at remains NULL).
+        row = (
+            db.session.query(Slice)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+            .filter(Slice.id == chart_id)
+            .one()
+        )
+        assert row.deleted_at is None
+
+        # Cleanup
+        db.session.delete(
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.id == report_id)
+            .one()
+        )
+        db.session.commit()
+        _hard_delete_chart(chart_id)
+
+
+class TestChartRestore(InsertChartMixin, SupersetTestCase):
+    """Tests for chart restore behaviour (T025)."""
+
+    def test_restore_soft_deleted_chart(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore makes the chart visible again."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("restore_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``ChartRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreChartCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``ChartRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.chart.exceptions import (
+            ChartRestoreFailedError,
+        )
+
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("restore_fail_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+
+        with patch(
+            "superset.commands.chart.restore.RestoreChartCommand.run",
+            side_effect=ChartRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_nonexistent_chart_returns_404(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore returns 404 for unknown UUID."""
+        self.login(ADMIN_USERNAME)
+        rv = self.client.post(
+            "/api/v1/chart/00000000-0000-0000-0000-000000000000/restore"
+        )
+        assert rv.status_code == 404
+
+    def test_restore_active_chart_returns_404(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore on active chart returns 404."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("active_restore_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_uses_can_write_permission(self) -> None:
+        """Non-admin owner with ``can_write_Chart`` can hit the restore
+        endpoint.
+
+        Pins the permission contract: ``method_permission_name`` must map
+        ``restore`` to ``write`` so FAB's ``@protect`` resolves the gate to
+        ``can_write_Chart`` (which Alpha already carries), not the implicit
+        fallback ``can_restore_Chart`` (which no standard role carries).
+
+        Without the mapping FAB defaults to ``can_<method>_<class>`` and
+        every non-admin would get 403 here — admins bypass FAB permission
+        checks entirely, so the admin-authed restore tests above don't
+        exercise the mapping.
+        """
+        alpha = self.get_user(ALPHA_USERNAME)
+        chart = self.insert_chart("restore_perm_test", [alpha.id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        self.login(ALPHA_USERNAME)
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200, (
+            f"Alpha owner soft-delete failed: {rv.status_code} {rv.data!r}"
+        )
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200, (
+            f"Expected 200 from Alpha owner restore (can_write_Chart), got "
+            f"{rv.status_code}: {rv.data!r}. If 403, "
+            "method_permission_name is missing 'restore': 'write'."
+        )
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_chart_reattaches_to_dashboards(self) -> None:
+        """Soft-deleting a chart preserves dashboard_slices junction rows;
+        restore makes the chart reappear in its dashboards automatically.
+
+        This is the positive test that pins down the SIP's "no cascade"
+        contract and the corrected commit ``feat(soft-delete): preserve
+        dashboard_slices on chart soft-delete (MissingChart handles UI)``.
+        Soft-delete leaves the junction intact so:
+
+          - dashboards continue to render the chart slot (frontend uses
+            ``MissingChart`` placeholder while the chart is hidden via the
+            visibility filter)
+          - on restore the chart is automatically a member of every
+            dashboard it was a member of before, with no manual
+            re-attachment step
+        """
+        admin = self.get_user("admin")
+        admin_id = admin.id
+
+        chart = self.insert_chart("reattach_test_chart", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        dashboard = Dashboard(
+            dashboard_title="reattach_test_dashboard",
+            slug="slug_reattach_test",
+            owners=[admin],
+            published=True,
+        )
+        dashboard.slices = [chart]
+        db.session.add(dashboard)
+        db.session.commit()
+        dashboard_id = dashboard.id
+
+        # Sanity: the junction row exists
+        junction_count = (
+            db.session.query(dashboard_slices)
+            .filter(
+                dashboard_slices.c.dashboard_id == dashboard_id,
+                dashboard_slices.c.slice_id == chart_id,
+            )
+            .count()
+        )
+        assert junction_count == 1, "junction row should exist after dashboard creation"
+
+        self.login(ADMIN_USERNAME)
+
+        # Soft-delete the chart
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # The junction row is preserved (no cascade)
+        junction_count_after_delete = (
+            db.session.query(dashboard_slices)
+            .filter(
+                dashboard_slices.c.dashboard_id == dashboard_id,
+                dashboard_slices.c.slice_id == chart_id,
+            )
+            .count()
+        )
+        assert junction_count_after_delete == 1, (
+            "junction row should remain intact on chart soft-delete; "
+            "MissingChart placeholder handles the UI gap"
+        )
+
+        # The dashboard's loaded `slices` collection no longer includes the
+        # soft-deleted chart (the global visibility filter applies to
+        # relationship loads via `with_loader_criteria(..., include_aliases=True)`).
+        db.session.expire_all()
+        dashboard_after_delete = (
+            db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+        )
+        assert chart_id not in [s.id for s in dashboard_after_delete.slices], (
+            "soft-deleted chart should be filtered out of dashboard.slices "
+            "by the visibility-filter listener"
+        )
+
+        # Restore the chart
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200
+
+        # The chart automatically reappears in the dashboard — junction row
+        # was preserved, so no manual reattach was needed.
+        db.session.expire_all()
+        dashboard_after_restore = (
+            db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+        )
+        assert chart_id in [s.id for s in dashboard_after_restore.slices], (
+            "restored chart should reappear in dashboard.slices automatically; "
+            "the junction row was never removed by soft-delete"
+        )
+
+        # Cleanup
+        _hard_delete_dashboard_for_charts_test(dashboard_id)
+        _hard_delete_chart(chart_id)
+
+    def test_restore_chart_by_non_admin_owner(self) -> None:
+        """Non-admin owners can restore their own soft-deleted charts.
+
+        The unit-level restore command tests mock security; this
+        integration test exercises the FAB security wiring end-to-end
+        so a future change that breaks the owner check on a non-admin
+        path can't slip through.
+        """
+        alpha = self.get_user(ALPHA_USERNAME)
+        alpha_id = alpha.id
+
+        chart = self.insert_chart("alpha_owned_chart", [alpha_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        self.login(ALPHA_USERNAME)
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200, rv.data
+
+        db.session.expire_all()
+        restored = db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for local test-scaffolding variables when the type is unambiguous from context; follow the surrounding file's existing conventions.
   
   **Applied to:**
     - `tests/integration_tests/charts/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy.orm.session import Session
+
+
+def test_set_dash_metadata_preserves_soft_deleted_members(
+    session: Session,
+) -> None:
+    """Saving a dashboard must not sever a soft-deleted member chart.
+
+    ``set_dash_metadata`` rebuilds ``dashboard.slices`` wholesale from the
+    incoming position data. The slice-resolution query must bypass the
+    soft-delete visibility filter: with the filter active, a member chart
+    sitting in the trash would be silently dropped from the assignment —
+    deleting its ``dashboard_slices`` junction row (breaking the
+    restore-reattach contract) and writing ``uuid: None`` into its
+    position slot. This test fails if the bypass is removed.
+    """
+    from superset import db
+    from superset.connectors.sqla.models import Database, SqlaTable
+    from superset.daos.dashboard import DashboardDAO
+    from superset.models.dashboard import Dashboard
+    from superset.models.slice import Slice
+
+    Dashboard.metadata.create_all(session.get_bind())
+
+    dataset = SqlaTable(
+        table_name="dash_meta_table",
+        database=Database(database_name="dash_meta_db", sqlalchemy_uri="sqlite://"),
+    )
+    db.session.add(dataset)
+    db.session.flush()
+
+    live_chart = Slice(
+        slice_name="live_chart",
+        datasource_id=dataset.id,
+        datasource_type="table",
+    )
+    trashed_chart = Slice(
+        slice_name="trashed_chart",
+        datasource_id=dataset.id,
+        datasource_type="table",
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )
+    dashboard = Dashboard(
+        dashboard_title="meta_test_dash",
+        slices=[live_chart, trashed_chart],
+        published=True,
+    )
+    db.session.add_all([live_chart, trashed_chart, dashboard])
+    db.session.flush()
+
+    positions: dict[str, dict[str, Any]] = {
+        "CHART-live": {
+            "type": "CHART",
+            "id": "CHART-live",
+            "children": [],
+            "meta": {"chartId": live_chart.id, "width": 4, "height": 50},
+        },
+        "CHART-trashed": {
+            "type": "CHART",
+            "id": "CHART-trashed",
+            "children": [],
+            "meta": {"chartId": trashed_chart.id, "width": 4, "height": 50},
+        },
+    }
+
+    DashboardDAO.set_dash_metadata(dashboard, {"positions": positions})
+
+    member_ids = {chart.id for chart in dashboard.slices}

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for local test-scaffolding variables whose types are unambiguous from context in test files.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,21 +49,107 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    # `user` is None for background / example-loader paths (no Flask request
+    # user). Combined with ``can_write=True`` (typically from
+    # ``ignore_permissions=True``), the ownership checks in the restore /
+    # overwrite branches below are intentionally skipped because the caller has
+    # already established trust at the command level.
     user = get_user()
-    if existing:
-        if overwrite and can_write and user:
-            if not security_manager.can_access_chart(existing) or (
-                user not in existing.owners and not security_manager.is_admin()
+
+    if existing := find_existing_for_import(Slice, config["uuid"]):

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for clearly inferred local variables when this file's existing conventions already use unannotated, context-obvious locals.
   
   **Applied to:**
     - `superset/commands/chart/importers/v1/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = None  # not soft-deleted
+
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=chart):
+        cmd = RestoreChartCommand("1")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_chart_forbidden_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartForbiddenError on permission check."""
+    chart = MagicMock()

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for local test-scaffolding variables in test files when the type is already unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510306611


##########
superset/daos/dashboard.py:
##########
@@ -276,8 +277,19 @@ def set_dash_metadata(
                 if isinstance(value, dict)
             ]
 
+            # Bypass the soft-delete visibility filter when resolving the
+            # incoming chart ids: a dashboard's ``position_json`` may still
+            # reference a chart that is currently soft-deleted, and this
+            # assignment REBUILDS ``dashboard.slices`` wholesale. With the
+            # filter active, the hidden member would be silently dropped —
+            # deleting its ``dashboard_slices`` junction row (breaking the
+            # documented restore-reattach contract) and writing
+            # ``uuid: None`` into its position slot via ``uuid_map`` below.
             current_slices = (
-                db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
+                db.session.query(Slice)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+                .filter(Slice.id.in_(slice_ids))
+                .all()
             )

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/integration_tests/charts/commands_tests.py:
##########
@@ -721,7 +721,7 @@ def test_fave_unfave_chart_command(self):
     def test_fave_unfave_chart_command_not_found(self):
         """Test that faving / unfaving a non-existing chart raises an exception"""
         with self.client.application.test_request_context():
-            example_chart_id = 1234
+            example_chart_id = 0

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
tests/unit_tests/migrations/test_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,186 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Tests for migration ``7c4a8d09ca37_add_deleted_at_to_slices``.
+
+Runs the migration's ``upgrade()`` and ``downgrade()`` against an
+in-memory SQLite engine with a real Alembic ``Operations`` context.
+The behaviour being pinned is the operator-facing contract documented
+in ``UPDATING.md``: ``downgrade()`` reverses the schema but does not
+hard-delete or otherwise mutate rows that were soft-deleted before
+the migration was reversed — those rows survive the downgrade and
+become visible to any code path that no longer applies the
+soft-delete visibility filter.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from importlib import import_module
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from sqlalchemy import (
+    Column,
+    create_engine,
+    insert,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices"
+)
+
+TABLE_NAME = migration.TABLE_NAME  # "slices"
+INDEX_NAME = migration.INDEX_NAME  # "ix_slices_deleted_at"

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



##########
superset/charts/api.py:
##########
@@ -134,7 +142,17 @@ def ensure_thumbnails_enabled(self) -> Optional[Response]:
         "warm_up_cache",
     }
     class_permission_name = "Chart"
-    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
+    # Custom methods (``restore``) need an explicit entry; FAB's @protect()
+    # decorator falls back to ``can_<method>_<class>`` (i.e.
+    # ``can_restore_Chart``) when the mapping is missing, which standard
+    # roles don't carry. Mirrors the permission model documented for
+    # ``DELETE`` / ``bulk_delete``: endpoint-level ``can_write`` plus
+    # resource-level ``raise_for_ownership``. See themes/api.py for the
+    # established pattern.
+    method_permission_name = {
+        **MODEL_API_RW_METHOD_PERMISSION_MAP,
+        "restore": "write",
+    }

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4597750627

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3399241865


##########
superset/translations/th/LC_MESSAGES/messages.po:
##########
@@ -5236,6 +5236,9 @@ msgstr "ไม่สามารถสร้างแผนภูมิได้
 # de, es, fa, fr, it, ja, ko, lv, mi, nl, pl, pt, pt_BR, ru, sk, sl, tr, uk,
 # zh, zh_TW]
 #, fuzzy
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Thai translation</b></div>
   <div id="fix">
   
   The `msgstr` is empty for this translation entry. Thai users will see untranslated English text 'Chart could not be restored.' when `ChartRestoreFailedError` is raised. Compare with similar entries: 'Chart could not be created.' → 'ไม่สามารถสร้างแผนภูมิได้' and 'Chart could not be updated.' → 'ไม่สามารถอัปเดตแผนภูมิได้'. The missing translation should follow the same pattern.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/th/LC_MESSAGES/messages.po (lines 5238-5240)
    +++ superset/translations/th/LC_MESSAGES/messages.po (lines 5238-5240)
    @@ -5235,7 +5235,7 @@
     # de, es, fa, fr, it, ja, ko, lv, mi, nl, pl, pt, pt_BR, ru, sk, sl, tr, uk,
     # zh, zh_TW]
    -#, fuzzy
    +#
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "ไม่สามารถกู้คืนแผนภูมิได้"
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1bfcc1</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/cs/LC_MESSAGES/messages.po:
##########
@@ -3106,6 +3106,9 @@ msgstr "Změny grafu"
 msgid "Chart could not be created."
 msgstr "Graf se nepodařilo vytvořit."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Czech translation</b></div>
   <div id="fix">
   
   The Czech translation for "Chart could not be restored." is missing (empty `msgstr`). Other similar error messages in this file have proper Czech translations. Without a translation, Czech-speaking users will see the untranslated English text or an empty string when this error occurs.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/cs/LC_MESSAGES/messages.po (lines 3109-3110) ---
    3109: msgid "Chart could not be restored."
    3110:-msgstr ""
    3110:+msgstr "Graf se nepodařilo obnovit."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #1bfcc1</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4684802933

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3344696219


##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,406 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import ADMIN_USERNAME, ALPHA_USERNAME
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self):

Review Comment:
   (1) `-> None` annotations added on all 12 test methods in b2b34b79e8. (2) `addCleanup` pattern deferred — agree it's the right shape but the diff to switch all 12 tests would be substantive and the trailing `_hard_delete_chart(chart_id)` pattern matches what the sibling soft-delete test suites do. Worth a follow-up cleanup commit once the entity PRs land.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #40129:
URL: https://github.com/apache/superset/pull/40129


-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3492944643


##########
superset/charts/api.py:
##########
@@ -134,7 +142,17 @@ def ensure_thumbnails_enabled(self) -> Optional[Response]:
         "warm_up_cache",
     }
     class_permission_name = "Chart"
-    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
+    # Custom methods (``restore``) need an explicit entry; FAB's @protect()
+    # decorator falls back to ``can_<method>_<class>`` (i.e.
+    # ``can_restore_Chart``) when the mapping is missing, which standard
+    # roles don't carry. Mirrors the permission model documented for
+    # ``DELETE`` / ``bulk_delete``: endpoint-level ``can_write`` plus
+    # resource-level ``raise_for_ownership``. See themes/api.py for the
+    # established pattern.
+    method_permission_name = {
+        **MODEL_API_RW_METHOD_PERMISSION_MAP,
+        "restore": "write",
+    }

Review Comment:
   **Suggestion:** Add an explicit type annotation to this new class-level mapping so the newly introduced variable is fully typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new class-level mapping is introduced without any type annotation, and it is a variable that can be annotated. This matches the Python type-hint rule for newly modified code.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ad66017cbfd243a08d75b25cc16a36c0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ad66017cbfd243a08d75b25cc16a36c0&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/charts/api.py
   **Line:** 152:155
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this new class-level mapping so the newly introduced variable is fully typed.
   
   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%2F40129&comment_hash=252d1c2cda404aca07ae1e56485f2b12b791c80d93e7a88523d56779fa19e40d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=252d1c2cda404aca07ae1e56485f2b12b791c80d93e7a88523d56779fa19e40d&reaction=dislike'>👎</a>



##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:
+        query = super().apply(query, value)
+        normalized = str(value).lower().strip() if value is not None else ""
+        if normalized not in {"include", "only"} or security_manager.is_admin():
+            return query
+
+        # Non-admins may only see soft-deleted charts they own. ``any()`` emits
+        # an EXISTS subquery so it composes with the base access filter without
+        # producing duplicate rows from a join.
+        owned = Slice.owners.any(security_manager.user_model.id == get_user_id())

Review Comment:
   **Suggestion:** Add a precise type annotation for this SQLAlchemy expression variable so the new logic is fully typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python local variable holding a SQLAlchemy boolean expression and it lacks a type annotation. The custom rule explicitly requires type hints for relevant variables that can be annotated.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=83c8b615d2dc44d6b06f4f139d6b41c5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=83c8b615d2dc44d6b06f4f139d6b41c5&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/charts/filters.py
   **Line:** 230:230
   **Comment:**
   	*Custom Rule: Add a precise type annotation for this SQLAlchemy expression variable so the new logic is fully typed.
   
   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%2F40129&comment_hash=b005b86d5d01f4fecc4457b4d25715bab6ab2810ca103cfcfb3a7cde787f3790&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=b005b86d5d01f4fecc4457b4d25715bab6ab2810ca103cfcfb3a7cde787f3790&reaction=dislike'>👎</a>



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "78a40c08b4be"
+
+TABLE_NAME = "slices"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"

Review Comment:
   **Suggestion:** Add explicit type annotations to the new module-level variables so the migration satisfies the type-hint requirement for relevant annotatable variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The custom rule requires type hints for new or modified Python variables that can be annotated. These module-level constants are newly introduced and have no type annotations, so the suggestion correctly identifies a real violation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f6f898808160453784508de4df20490c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f6f898808160453784508de4df20490c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py
   **Line:** 38:42
   **Comment:**
   	*Custom Rule: Add explicit type annotations to the new module-level variables so the migration satisfies the type-hint requirement for relevant annotatable variables.
   
   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%2F40129&comment_hash=59e755ac64d014e5d2da7c2b83e0503e55bc4c6e4d8d68d9e1ea5ba09e6d13ca&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=59e755ac64d014e5d2da7c2b83e0503e55bc4c6e4d8d68d9e1ea5ba09e6d13ca&reaction=dislike'>👎</a>



##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:
+        query = super().apply(query, value)
+        normalized = str(value).lower().strip() if value is not None else ""

Review Comment:
   **Suggestion:** Add an explicit type annotation for this newly introduced local variable to satisfy the type-hint requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly introduced Python local variable with an obvious type of str, and it is unannotated. That matches the rule requiring type hints on relevant variables that can be annotated.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ab8cdeb7dddb40b0ac9d3d750b6b508c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ab8cdeb7dddb40b0ac9d3d750b6b508c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/charts/filters.py
   **Line:** 223:223
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this newly introduced local variable to satisfy the type-hint requirement for relevant variables.
   
   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%2F40129&comment_hash=75a6d6cf012c5a2acfa5e2dec623d46c6edd5e63075be9a919255361ae1bf25b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=75a6d6cf012c5a2acfa5e2dec623d46c6edd5e63075be9a919255361ae1bf25b&reaction=dislike'>👎</a>



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )

Review Comment:
   **Suggestion:** Add a concrete type annotation to this dashboard query result variable so it satisfies the rule requiring type hints where feasible. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is another annotatable local ORM result. Since `one_or_none()` returns an optional dashboard instance, the code satisfies the pattern targeted by the type-hint rule but does not include a type annotation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=397db10edf2f4b709e464ed8fef233ac&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=397db10edf2f4b709e464ed8fef233ac&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/integration_tests/charts/soft_delete_tests.py
   **Line:** 57:62
   **Comment:**
   	*Custom Rule: Add a concrete type annotation to this dashboard query result variable so it satisfies the rule requiring type hints where feasible.
   
   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%2F40129&comment_hash=be2478e8fe6d06ea07ac37f733845454ef716e45b55bf530715f6c888064a37a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=be2478e8fe6d06ea07ac37f733845454ef716e45b55bf530715f6c888064a37a&reaction=dislike'>👎</a>



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self) -> None:
+        """DELETE /api/v1/chart/<pk> sets deleted_at instead of removing."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("soft_delete_test", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # Row still exists in DB with deleted_at set
+        row = (
+            db.session.query(Slice)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+            .filter(Slice.id == chart_id)
+            .one_or_none()
+        )
+        assert row is not None
+        assert row.deleted_at is not None
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_excluded_from_get(self) -> None:
+        """GET /api/v1/chart/<pk> returns 404 for a soft-deleted chart."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("invisible_chart", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.get(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_excluded_from_list(self) -> None:
+        """GET /api/v1/chart/ should not include soft-deleted charts."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("listed_then_deleted", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.get("/api/v1/chart/")
+        data = json.loads(rv.data)
+        chart_ids = [c["id"] for c in data["result"]]
+        assert chart_id not in chart_ids
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_soft_deleted_chart_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/chart/ with chart_deleted_state=include returns deleted charts."""  # noqa: E501
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("listed_with_deleted", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+
+        rison_query = "(filters:!((col:id,opr:chart_deleted_state,value:include)))"
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+
+        data = json.loads(rv.data)
+        deleted_row = next(
+            (row for row in data["result"] if row["id"] == chart_id),
+            None,
+        )
+        assert deleted_row is not None
+        assert deleted_row["deleted_at"] is not None
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_only_filter_returns_only_soft_deleted_charts(self) -> None:
+        """chart_deleted_state=only excludes live rows and returns only deleted ones."""
+        admin_id = self.get_user("admin").id
+        live_chart = self.insert_chart("only_live", [admin_id], 1)
+        deleted_chart = self.insert_chart("only_deleted", [admin_id], 1)
+        live_id = live_chart.id
+        deleted_id = deleted_chart.id
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{deleted_id}")
+
+        rison_query = "(filters:!((col:id,opr:chart_deleted_state,value:only)))"
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+
+        data = json.loads(rv.data)
+        returned_ids = {row["id"] for row in data["result"]}
+        assert deleted_id in returned_ids
+        assert live_id not in returned_ids
+
+        # Cleanup
+        _hard_delete_chart(live_id)
+        _hard_delete_chart(deleted_id)
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted charts.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha_id = self.get_user(ALPHA_USERNAME).id
+        chart = self.insert_chart("sd_owner_chart", [alpha_id], 1)
+        chart_id = chart.id
+
+        chart.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:chart_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [c["id"] for c in json.loads(rv.data)["result"]]
+        assert chart_id in ids
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a chart once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the chart's dataset, so
+        ``ChartFilter`` makes the chart visible to gamma while it is live. After
+        soft-delete, the deleted-state list is scoped to the restore audience
+        (owners/admins), so gamma — who could never restore it — must not see it
+        via ``include`` or ``only``.
+        """
+        admin_id = self.get_user(ADMIN_USERNAME).id
+        chart = self.insert_chart("sd_acl_chart", [admin_id], 1)
+        chart_id = chart.id
+
+        table = db.session.query(SqlaTable).get(1)
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu("datasource_access", table.perm)
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the chart while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/chart/?q=(page_size:200)")
+            assert chart_id in [c["id"] for c in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live chart via datasource access"
+            )
+
+            # Soft-delete directly (avoids a mid-test re-login to admin).
+            reloaded = (
+                db.session.query(Slice)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+                .filter(Slice.id == chart_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            # Gamma must not see the soft-deleted chart in either mode.
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:chart_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/chart/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [c["id"] for c in json.loads(rv.data)["result"]]
+                assert chart_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"chart via chart_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", table.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            _hard_delete_chart(chart_id)
+
+    def test_delete_already_soft_deleted_chart_returns_404(self) -> None:
+        """DELETE on an already soft-deleted chart returns 404 (FR-008)."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("double_delete_test", [admin_id], 1)
+        chart_id = chart.id
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_delete_chart_blocked_when_active_report_references_it(self) -> None:
+        """DELETE /api/v1/chart/<id> returns 422 when a report references it.
+
+        Pins down the existing API protection in `DeleteChartCommand.validate()`:
+        when a `report_schedule` row references the chart, the validation
+        raises `ChartDeleteFailedReportsExistError` *before* `ChartDAO.delete()`
+        is invoked, so no soft-delete routing happens. This is the contract
+        soft-delete inherits from the pre-existing API and is what makes the
+        "report-execution against soft-deleted target" crash class
+        (commands/report/execute.py:_get_url) unreachable through the API.
+        """
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("blocked_by_report_test", [admin_id], 1)
+        chart_id = chart.id
+
+        report = ReportSchedule(
+            type=ReportScheduleType.REPORT,
+            name="blocking_report_for_chart_delete",
+            description="Report that should block chart deletion",
+            crontab="0 9 * * *",
+            chart=chart,
+            creation_method=ReportCreationMethod.ALERTS_REPORTS,
+        )
+        db.session.add(report)
+        db.session.commit()
+        report_id = report.id
+
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 422
+        body = json.loads(rv.data)
+        assert "associated alerts or reports" in body.get("message", "").lower() or (
+            "associated" in body.get("message", "").lower()
+            and "report" in body.get("message", "").lower()
+        )
+        assert "blocking_report_for_chart_delete" in body.get("message", "")
+
+        # Confirm the chart was NOT soft-deleted (deleted_at remains NULL).
+        row = (
+            db.session.query(Slice)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+            .filter(Slice.id == chart_id)
+            .one()
+        )
+        assert row.deleted_at is None
+
+        # Cleanup
+        db.session.delete(
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.id == report_id)
+            .one()
+        )
+        db.session.commit()
+        _hard_delete_chart(chart_id)
+
+
+class TestChartRestore(InsertChartMixin, SupersetTestCase):
+    """Tests for chart restore behaviour (T025)."""
+
+    def test_restore_soft_deleted_chart(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore makes the chart visible again."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("restore_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``ChartRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreChartCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``ChartRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.chart.exceptions import (
+            ChartRestoreFailedError,
+        )
+
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("restore_fail_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/chart/{chart_id}")
+
+        with patch(
+            "superset.commands.chart.restore.RestoreChartCommand.run",
+            side_effect=ChartRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_nonexistent_chart_returns_404(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore returns 404 for unknown UUID."""
+        self.login(ADMIN_USERNAME)
+        rv = self.client.post(
+            "/api/v1/chart/00000000-0000-0000-0000-000000000000/restore"
+        )
+        assert rv.status_code == 404
+
+    def test_restore_active_chart_returns_404(self) -> None:
+        """POST /api/v1/chart/<uuid>/restore on active chart returns 404."""
+        admin_id = self.get_user("admin").id
+        chart = self.insert_chart("active_restore_test", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+        self.login(ADMIN_USERNAME)
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 404
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_uses_can_write_permission(self) -> None:
+        """Non-admin owner with ``can_write_Chart`` can hit the restore
+        endpoint.
+
+        Pins the permission contract: ``method_permission_name`` must map
+        ``restore`` to ``write`` so FAB's ``@protect`` resolves the gate to
+        ``can_write_Chart`` (which Alpha already carries), not the implicit
+        fallback ``can_restore_Chart`` (which no standard role carries).
+
+        Without the mapping FAB defaults to ``can_<method>_<class>`` and
+        every non-admin would get 403 here — admins bypass FAB permission
+        checks entirely, so the admin-authed restore tests above don't
+        exercise the mapping.
+        """
+        alpha = self.get_user(ALPHA_USERNAME)
+        chart = self.insert_chart("restore_perm_test", [alpha.id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        self.login(ALPHA_USERNAME)
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200, (
+            f"Alpha owner soft-delete failed: {rv.status_code} {rv.data!r}"
+        )
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200, (
+            f"Expected 200 from Alpha owner restore (can_write_Chart), got "
+            f"{rv.status_code}: {rv.data!r}. If 403, "
+            "method_permission_name is missing 'restore': 'write'."
+        )
+
+        # Cleanup
+        _hard_delete_chart(chart_id)
+
+    def test_restore_chart_reattaches_to_dashboards(self) -> None:
+        """Soft-deleting a chart preserves dashboard_slices junction rows;
+        restore makes the chart reappear in its dashboards automatically.
+
+        This is the positive test that pins down the SIP's "no cascade"
+        contract and the corrected commit ``feat(soft-delete): preserve
+        dashboard_slices on chart soft-delete (MissingChart handles UI)``.
+        Soft-delete leaves the junction intact so:
+
+          - dashboards continue to render the chart slot (frontend uses
+            ``MissingChart`` placeholder while the chart is hidden via the
+            visibility filter)
+          - on restore the chart is automatically a member of every
+            dashboard it was a member of before, with no manual
+            re-attachment step
+        """
+        admin = self.get_user("admin")
+        admin_id = admin.id
+
+        chart = self.insert_chart("reattach_test_chart", [admin_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        dashboard = Dashboard(
+            dashboard_title="reattach_test_dashboard",
+            slug="slug_reattach_test",
+            owners=[admin],
+            published=True,
+        )
+        dashboard.slices = [chart]
+        db.session.add(dashboard)
+        db.session.commit()
+        dashboard_id = dashboard.id
+
+        # Sanity: the junction row exists
+        junction_count = (
+            db.session.query(dashboard_slices)
+            .filter(
+                dashboard_slices.c.dashboard_id == dashboard_id,
+                dashboard_slices.c.slice_id == chart_id,
+            )
+            .count()
+        )
+        assert junction_count == 1, "junction row should exist after dashboard creation"
+
+        self.login(ADMIN_USERNAME)
+
+        # Soft-delete the chart
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        # The junction row is preserved (no cascade)
+        junction_count_after_delete = (
+            db.session.query(dashboard_slices)
+            .filter(
+                dashboard_slices.c.dashboard_id == dashboard_id,
+                dashboard_slices.c.slice_id == chart_id,
+            )
+            .count()
+        )
+        assert junction_count_after_delete == 1, (
+            "junction row should remain intact on chart soft-delete; "
+            "MissingChart placeholder handles the UI gap"
+        )
+
+        # The dashboard's loaded `slices` collection no longer includes the
+        # soft-deleted chart (the global visibility filter applies to
+        # relationship loads via `with_loader_criteria(..., include_aliases=True)`).
+        db.session.expire_all()
+        dashboard_after_delete = (
+            db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+        )
+        assert chart_id not in [s.id for s in dashboard_after_delete.slices], (
+            "soft-deleted chart should be filtered out of dashboard.slices "
+            "by the visibility-filter listener"
+        )
+
+        # Restore the chart
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200
+
+        # The chart automatically reappears in the dashboard — junction row
+        # was preserved, so no manual reattach was needed.
+        db.session.expire_all()
+        dashboard_after_restore = (
+            db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+        )
+        assert chart_id in [s.id for s in dashboard_after_restore.slices], (
+            "restored chart should reappear in dashboard.slices automatically; "
+            "the junction row was never removed by soft-delete"
+        )
+
+        # Cleanup
+        _hard_delete_dashboard_for_charts_test(dashboard_id)
+        _hard_delete_chart(chart_id)
+
+    def test_restore_chart_by_non_admin_owner(self) -> None:
+        """Non-admin owners can restore their own soft-deleted charts.
+
+        The unit-level restore command tests mock security; this
+        integration test exercises the FAB security wiring end-to-end
+        so a future change that breaks the owner check on a non-admin
+        path can't slip through.
+        """
+        alpha = self.get_user(ALPHA_USERNAME)
+        alpha_id = alpha.id
+
+        chart = self.insert_chart("alpha_owned_chart", [alpha_id], 1)
+        chart_id = chart.id
+        chart_uuid = str(chart.uuid)
+
+        self.login(ALPHA_USERNAME)
+        rv = self.client.delete(f"/api/v1/chart/{chart_id}")
+        assert rv.status_code == 200
+
+        rv = self.client.post(f"/api/v1/chart/{chart_uuid}/restore")
+        assert rv.status_code == 200, rv.data
+
+        db.session.expire_all()
+        restored = db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()

Review Comment:
   **Suggestion:** Add an explicit optional type annotation to this restored entity variable to align with the type-hint requirement for relevant local variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The variable `restored` is assigned the result of `one_or_none()`, so it is a relevant local variable that can be annotated as optional. The existing code leaves it untyped, matching the rule violation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6df42d5cb8b74ff8b84720f1dfc36e9d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6df42d5cb8b74ff8b84720f1dfc36e9d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/integration_tests/charts/soft_delete_tests.py
   **Line:** 555:555
   **Comment:**
   	*Custom Rule: Add an explicit optional type annotation to this restored entity variable to align with the type-hint requirement for relevant local variables.
   
   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%2F40129&comment_hash=8edf7355fa168c675b996089efe8f0241b3496ab06c7d273640a58c39b45851f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=8edf7355fa168c675b996089efe8f0241b3496ab06c7d273640a58c39b45851f&reaction=dislike'>👎</a>



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,560 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from datetime import datetime
+
+from superset import security_manager
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard, dashboard_slices
+from superset.models.slice import Slice
+from superset.reports.models import (
+    ReportCreationMethod,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )

Review Comment:
   **Suggestion:** Add an explicit type annotation for this query result variable to comply with the required type-hint rule for annotatable variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The rule requires type hints on relevant variables that can be annotated. This local ORM result variable is assigned from `one_or_none()` and can be typed as an optional `Slice`, but the existing code omits that annotation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f5c0b0262f2846d98c4776d99644a9e4&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f5c0b0262f2846d98c4776d99644a9e4&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/integration_tests/charts/soft_delete_tests.py
   **Line:** 44:49
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this query result variable to comply with the required type-hint rule for annotatable variables.
   
   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%2F40129&comment_hash=cc0150db73394e16037ce102c42cd84df3fbc35bc75d0174bfea544fbaa427df&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=cc0150db73394e16037ce102c42cd84df3fbc35bc75d0174bfea544fbaa427df&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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3492980949


##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "78a40c08b4be"

Review Comment:
   **Suggestion:** The migration is anchored to an unrelated newer revision, which creates an unintended dependency chain for chart soft-delete and can produce an unexpected Alembic branch/head layout. Repoint `down_revision` to the intended soft-delete rollout base revision so this migration composes correctly with sibling entity rollouts and doesn’t force unrelated migrations first. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Chart soft-delete migration depends on SSH tunnel migration.
   - ⚠️ Alembic upgrade path includes unnecessary SSH host key change.
   - ⚠️ Soft-delete entity rollouts cannot share a common base.
   - ⚠️ Future migration rebases risk extra heads and merges.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Inspect the chart soft-delete migration at
   `superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py`.
   At lines 23–25 and 37–39, the docstring and Alembic identifiers show `Revision ID:
   7c4a8d09ca37` and `down_revision = "78a40c08b4be"`, meaning this migration depends on
   revision `78a40c08b4be`.
   
   2. Inspect the referenced parent migration at
   `superset/migrations/versions/2026-06-03_10-00_78a40c08b4be_add_server_host_key_to_ssh_tunnels.py`.
   At lines 17–27 and 35–37, it is clearly an SSH tunnel feature migration (`add
   server_host_key to ssh_tunnels`) with `revision = "78a40c08b4be"` and `down_revision =
   "b7c9d1e2f3a4"`, unrelated to charts or soft-delete infrastructure.
   
   3. Inspect the intended rollout base on the existing migration chain at
   `superset/migrations/versions/2026-04-22_19-00_31dae2559c05_replay_user_favorite_tag_migration.py`
   and its parent `2025-11-04_11-26_33d7e0e21daa_add_semantic_layers_and_views.py`. These
   files (lines 35–46 and 19–41 respectively) show a separate lineage `ce6bd21901ab →
   33d7e0e21daa → 31dae2559c05` that the PR description states is the anchor for the
   soft-delete rollout, but the chart migration is not attached to this chain.
   
   4. Run `superset db upgrade` (or Alembic `upgrade head`) in an environment where
   migrations are applied up to `31dae2559c05` but not yet to `b7c9d1e2f3a4`/`78a40c08b4be`.
   Alembic will resolve the graph such that `7c4a8d09ca37_add_deleted_at_to_slices` cannot be
   applied until the unrelated SSH tunnel migrations
   `b7c9d1e2f3a4_add_password_must_change.py` and
   `78a40c08b4be_add_server_host_key_to_ssh_tunnels.py` are also applied, coupling chart
   soft-delete rollout to SSH tunnel changes and preventing the chart migration from sharing
   the intended common base with sibling soft-delete migrations.
   ```
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=2a8ae812e4ad4503b505e859bdf4fc6b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=2a8ae812e4ad4503b505e859bdf4fc6b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py
   **Line:** 39:39
   **Comment:**
   	*Logic Error: The migration is anchored to an unrelated newer revision, which creates an unintended dependency chain for chart soft-delete and can produce an unexpected Alembic branch/head layout. Repoint `down_revision` to the intended soft-delete rollout base revision so this migration composes correctly with sibling entity rollouts and doesn’t force unrelated migrations first.
   
   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%2F40129&comment_hash=b4d5c3ab3d0fbbe9e2e31cb07f4d6802dd0b0d38cb510f557a5636a412b7780b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=b4d5c3ab3d0fbbe9e2e31cb07f4d6802dd0b0d38cb510f557a5636a412b7780b&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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3358120790


##########
superset/translations/sl/LC_MESSAGES/messages.po:
##########
@@ -3119,6 +3119,9 @@ msgstr "Spremembe grafikona"
 msgid "Chart could not be created."
 msgstr "Grafikona ni mogoče ustvariti."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Slovenian translation</b></div>
   <div id="fix">
   
   The `msgstr` field is empty, so Slovenian users will see the untranslated English error message "Chart could not be restored." Compare with the adjacent translations: "Grafikona ni mogoče ustvariti." (create) and "Grafikona ni mogoče posodobiti." (update) — the same construction applies.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/sl/LC_MESSAGES/messages.po (lines 3122-3123) ---
    3122: msgid "Chart could not be restored."
    3123:-msgstr ""
    3123:+msgstr "Grafikona ni mogoče obnoviti."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #7d71bd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
tests/unit_tests/charts/commands/importers/v1/import_test.py:
##########
@@ -287,6 +288,184 @@ def test_import_existing_chart_with_permission(
     mock_can_access_chart.assert_called_once_with(slice)
 
 
+def test_import_soft_deleted_chart_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session_with_data: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted chart must restore the row in place,
+    not hard-delete-and-replace. Otherwise out-of-archive references
+    (dashboard_slices junctions, report.chart_id) would cascade away.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Extract duplicated test setup</b></div>
   <div id="fix">
   
   This PR contains syntactic duplication in the test file at lines 300-326 and 372-398 where 27 lines of identical test setup code are repeated. Consider extracting this into a shared fixture to reduce maintenance burden and potential inconsistencies. No functional changes to production code detected.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    @@ -298,6 +298,28 @@ class TestChartImport:
    +    def _setup_chart_overwrite_context(
    +        self,
    +        session_with_data,
    +        security_manager,
    +        chart_config,
    +        mocker,
    +    ):
    +        """Shared helper to setup chart overwrite test context."""
    +        mocker.patch.object(security_manager, "can_access", return_value=True)
    +        mocker.patch.object(security_manager, "can_access_chart", return_value=True)
    +
    +        existing = (
    +            session_with_data.query(Slice)
    +            .filter(Slice.uuid == chart_config["uuid"])
    +            .one_or_none()
    +        )
    +        assert existing is not None
    +        original_id = existing.id
    +        existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
    +        session_with_data.flush()
    +
    +        admin = User(
    +            first_name="Alice",
    +            last_name="Doe",
    +            email="adoe@example.org",
    +            username="admin",
    +            roles=[Role(name="Admin")],
    +        )
    +
    +        config = copy.deepcopy(chart_config)
    +        config["datasource_id"] = 1
    +        config["datasource_type"] = "table"
    +
    +        return admin, config
    +
    +
     class TestChartImportOverwrite:
         def test_import_chart_overwrite(self, session_with_data, security_manager, mocker):
    -        mocker.patch.object(security_manager, "can_access", return_value=True)
    -        mocker.patch.object(security_manager, "can_access_chart", return_value=True)
    -
    -        existing = (
    -            session_with_data.query(Slice)
    -            .filter(Slice.uuid == chart_config["uuid"])
    -            .one_or_none()
    -        )
    -        assert existing is not None
    -        original_id = existing.id
    -        existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
    -        session_with_data.flush()
    -
    -        admin = User(
    -            first_name="Alice",
    -            last_name="Doe",
    -            email="adoe@example.org",
    -            username="admin",
    -            roles=[Role(name="Admin")],
    -        )
    -
    -        config = copy.deepcopy(chart_config)
    -        config["datasource_id"] = 1
    -        config["datasource_type"] = "table"
    -
    -        with override_user(admin):
    -            chart = import_chart(config, overwrite=True)
    +        admin, config = self._setup_chart_overwrite_context(
    +            session_with_data, security_manager, chart_config, mocker
    +        )
    +        with override_user(admin):
    +            chart = import_chart(config, overwrite=True)
    @@ -369,6 +391,9 @@ class TestChartImportOverwrite:
             with override_user(admin):
                 chart = import_chart(config, overwrite=True)
    
    +    def test_import_chart_overwrite_with_slice_in_datasource(self, session_with_data, security_manager, mocker):
    +        admin, config = self._setup_chart_overwrite_context(
    +            session_with_data, security_manager, chart_config, mocker
    +        )
             with override_user(admin):
                 chart = import_chart(config, overwrite=True)
   
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #7d71bd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/es/LC_MESSAGES/messages.po:
##########
@@ -3211,6 +3211,9 @@ msgstr "Cambios en el gráfico"
 msgid "Chart could not be created."
 msgstr "No se ha podido crear el gráfico."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Spanish translation</b></div>
   <div id="fix">
   
   The new translation entry at line 3214-3215 has an empty `msgstr` value, while adjacent entries follow the same pattern with proper translations. For consistency with `Chart could not be created.` ("No se ha podido crear el gráfico.") and `Chart could not be updated.` ("No se ha podido actualizar el gráfico."), this should be translated as "No se ha podido restaurar el gráfico." — otherwise Spanish-speaking users will see the untranslated English error message for the restore action.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/es/LC_MESSAGES/messages.po
    +++ superset/translations/es/LC_MESSAGES/messages.po
    @@ -3212,7 +3212,7 @@
     msgstr "No se ha podido crear el gráfico."
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "No se ha podido restaurar el gráfico."
    
     msgid "Chart could not be updated."
     msgstr "No se ha podido actualizar el gráfico."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #7d71bd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/zh/LC_MESSAGES/messages.po:
##########
@@ -3024,6 +3024,9 @@ msgstr "图表变化"
 msgid "Chart could not be created."
 msgstr "您的图表无法创建。"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Chinese translation</b></div>
   <div id="fix">
   
   The Chinese translation for 'Chart could not be restored.' is empty. Chinese users will see untranslated English text. Following the established pattern (e.g., '您的图表无法创建。' for 'Chart could not be created.'), the translation should be '您的图表无法恢复。'
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/zh/LC_MESSAGES/messages.po (lines 3027-3028)
    +++ superset/translations/zh/LC_MESSAGES/messages.po (lines 3027-3028)
    @@ -3025,6 +3025,6 @@ msgstr "您的图表无法创建。"
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "您的图表无法恢复。"
    
     msgid "Chart could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #7d71bd</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4653707750

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4652137593

   **Latest review items addressed** (`9e4d177d29`):
   
   - Deduped the soft-delete import-test setup into a `_soft_delete_existing_chart` helper (and made its timestamp timezone-aware).
   - **Translations:** added `msgid "Chart could not be restored."` to `messages.pot`. Every language `.po` already has the empty-`msgstr` placeholder for translators. Resolving the per-language translation threads as placeholder-complete (actual translations come via the i18n workflow).
   - amin's earlier items (RBAC restore mapping, `user=None` bypass doc, inline-import justification) were addressed in prior commits.
   
   Resolving the corresponding threads.
   


-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3501587545


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,21 +49,107 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    # `user` is None for background / example-loader paths (no Flask request
+    # user). Combined with ``can_write=True`` (typically from
+    # ``ignore_permissions=True``), the ownership checks in the restore /
+    # overwrite branches below are intentionally skipped because the caller has
+    # already established trust at the command level.
     user = get_user()
-    if existing:
-        if overwrite and can_write and user:
-            if not security_manager.can_access_chart(existing) or (
-                user not in existing.owners and not security_manager.is_admin()
+
+    if existing := find_existing_for_import(Slice, config["uuid"]):

Review Comment:
   **Suggestion:** Replace the unannotated walrus assignment with an explicitly declared, typed local variable before the conditional check. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The rule requires type hints for relevant variables that can be annotated in new or modified Python code. This new walrus assignment introduces the local variable `existing` without any type annotation, so the suggestion accurately identifies a real rule violation.
   </details>
   
   [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c710dfced6864ea583c6e68180c72ab7&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c710dfced6864ea583c6e68180c72ab7&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/chart/importers/v1/utils.py
   **Line:** 89:89
   **Comment:**
   	*Custom Rule: Replace the unannotated walrus assignment with an explicitly declared, typed local variable before the conditional check.
   
   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%2F40129&comment_hash=04098756cdc6ecee2158a14d1b69e6b81e69baf1c9fde617a64a4ef7175535b9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=04098756cdc6ecee2158a14d1b69e6b81e69baf1c9fde617a64a4ef7175535b9&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] feat(charts): soft-delete and restore (sc-106189) [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4455111356

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | e53c17e93aba7acccfc9e5b77c25a59e7e246d58 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a0646e431e6390007c275fb |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-40129--superset-docs-preview.netlify.app](https://deploy-preview-40129--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQwMTI5LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.NFBpXhPsnGV2P3Jy88gFc6JaINfK4B6CfPUjTUJEUYY)<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#Dcq7DYAgEADQXa6W5FA81A0cg88RChQCNMa4u3SveC-Umq_S4QCYwFZzuzjcnJBIctuFi6b2JloOXXhO3Hk8zyXl5_RjkkFSxGqRTMuOiNrNeg0Wvh8) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-40129--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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4604884071

   Thanks @aminghadersohi for the thorough re-review.
   
   Both outstanding items addressed in 30e0a3996b:
   
   **BLOCKER — test inline imports (`restore_test.py`)**: all eight moved to module top. The imports (`RestoreChartCommand`, `ChartNotFoundError`, `ChartForbiddenError`, `SupersetSecurityException`) are pure Python class definitions with no app-context dependency and no circular dependency — there was no justification for the inline form. Also took the consistency win on `datetime(...)` calls (added `tzinfo=timezone.utc`).
   
   **NIT — integration test inline imports (`soft_delete_tests.py`)**: both moved to module top. `dashboard_slices` is in the same module as `Dashboard` (already at top); `ReportSchedule`/etc. are SQLAlchemy models that are safe to import at module top in a `SupersetTestCase` integration context.
   
   **MEDIUM — `down_revision` 7 revisions behind master**: updated `7c4a8d09ca37`'s `down_revision` from `33d7e0e21daa` to `a1b2c3d4e5f6` (the current alembic head). The sibling dashboards (#40128) and datasets (#40130) PRs got the same update on their migrations in companion commits. Cross-PR merge-order coordination still applies — whichever lands first stays at `a1b2c3d4e5f6`, the others rebase onto the newly-merged revision.
   
   The branch was also rebased on current master in this push (the previous base was 34 commits behind preset/master; no conflicts).
   
   Thanks again — and good catch on retracting the first BLOCKER (`find_existing_for_import` already at module top from an earlier round).


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4618158871

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4894600580

   Thanks @rusackas — done in `4d8b9653a3`: rebased onto current master and the migration is re-pointed onto `b4a3f2e1d0c9` (#40527's migration, the current single head — verified by graph scan; the docstring's `Revises:` line is updated too). CI is running on the new head.
   
   For future rounds this is now guarded locally: a pre-push hook fails my pushes if the branch's migration graph has more than one head, so a stale `down_revision` can't reach CI again — though it can't help when master's head moves *after* the push, as happened here. All the more reason to merge while it's green 🙂


-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3501576598


##########
tests/unit_tests/dao/dashboard_test.py:
##########
@@ -0,0 +1,95 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy.orm.session import Session
+
+
+def test_set_dash_metadata_preserves_soft_deleted_members(
+    session: Session,
+) -> None:
+    """Saving a dashboard must not sever a soft-deleted member chart.
+
+    ``set_dash_metadata`` rebuilds ``dashboard.slices`` wholesale from the
+    incoming position data. The slice-resolution query must bypass the
+    soft-delete visibility filter: with the filter active, a member chart
+    sitting in the trash would be silently dropped from the assignment —
+    deleting its ``dashboard_slices`` junction row (breaking the
+    restore-reattach contract) and writing ``uuid: None`` into its
+    position slot. This test fails if the bypass is removed.
+    """
+    from superset import db
+    from superset.connectors.sqla.models import Database, SqlaTable
+    from superset.daos.dashboard import DashboardDAO
+    from superset.models.dashboard import Dashboard
+    from superset.models.slice import Slice

Review Comment:
   Fixed in f4d446a8a2 — moved all five `from superset...` imports to the module-level import block and removed the inline copies. ruff/mypy clean, test passes.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_



-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510307709


##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require method-level docstrings when the enclosing class docstring already documents the behavior; avoid duplicating the same explanation.
   
   **Applied to:**
     - `superset/charts/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/daos/dashboard.py:
##########
@@ -276,8 +277,19 @@ def set_dash_metadata(
                 if isinstance(value, dict)
             ]
 
+            # Bypass the soft-delete visibility filter when resolving the
+            # incoming chart ids: a dashboard's ``position_json`` may still
+            # reference a chart that is currently soft-deleted, and this
+            # assignment REBUILDS ``dashboard.slices`` wholesale. With the
+            # filter active, the hidden member would be silently dropped —
+            # deleting its ``dashboard_slices`` junction row (breaking the
+            # documented restore-reattach contract) and writing
+            # ``uuid: None`` into its position slot via ``uuid_map`` below.
             current_slices = (
-                db.session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
+                db.session.query(Slice)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+                .filter(Slice.id.in_(slice_ids))
+                .all()
             )

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for local variables in Python when the type is obvious from surrounding context and the file already follows that convention.
   
   **Applied to:**
     - `superset/daos/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/integration_tests/charts/commands_tests.py:
##########
@@ -721,7 +721,7 @@ def test_fave_unfave_chart_command(self):
     def test_fave_unfave_chart_command_not_found(self):
         """Test that faving / unfaving a non-existing chart raises an exception"""
         with self.client.application.test_request_context():
-            example_chart_id = 1234
+            example_chart_id = 0

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for simple local/test-scaffolding variables when the type is obvious from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for local test-scaffolding variables when the type is already unambiguous from context.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510305990


##########
superset/charts/filters.py:
##########
@@ -196,3 +197,40 @@ def apply(self, query: Query, value: Any) -> Query:
                 FavStar.user_id == get_user_id(),
             )
         )
+
+
+class ChartDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted charts.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the chart's owners (or admins) may enumerate them. This mirrors
+    ``RestoreChartCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the chart via datasource access) cannot list
+    soft-deleted charts they could never restore. Live rows are unaffected —
+    they keep their normal ``ChartFilter`` visibility. The ownership scoping is
+    part of the cross-entity deleted-state contract: only the restore audience
+    may enumerate soft-deleted rows (kept consistent with the deleted-state
+    filters in the dashboard and dataset soft-delete rollouts).
+    """
+
+    arg_name = "chart_deleted_state"
+    model = Slice
+
+    def apply(self, query: Query, value: Any) -> Query:

Review Comment:
   Considered — the class-level docstring documents the filtering and ownership-scoping behavior in detail; a method-level restatement would duplicate it. Declining as style.



##########
superset/translations/ru/LC_MESSAGES/messages.po:
##########
@@ -3060,6 +3060,9 @@ msgstr "Изменения диаграммы"
 msgid "Chart could not be created."
 msgstr "Не удалось создать диаграмму"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/translations/it/LC_MESSAGES/messages.po:
##########
@@ -2999,6 +2999,9 @@ msgstr "Ultima Modifica"
 msgid "Chart could not be created."
 msgstr "La tua query non può essere salvata"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/translations/fa/LC_MESSAGES/messages.po:
##########
@@ -3065,6 +3065,9 @@ msgstr "تغییرات نمودار"
 msgid "Chart could not be created."
 msgstr "نمودار نتوانسته ایجاد شود."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/translations/nl/LC_MESSAGES/messages.po:
##########
@@ -3118,6 +3118,9 @@ msgstr "Veranderingen in de grafiek"
 msgid "Chart could not be created."
 msgstr "Grafiek kon niet worden aangemaakt."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/translations/pt/LC_MESSAGES/messages.po:
##########
@@ -3045,6 +3045,9 @@ msgstr "Modificado pela última vez"
 msgid "Chart could not be created."
 msgstr "Não foi possível gravar a sua query"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   An empty `msgstr` is expected for newly-extracted strings — catalogs carry new ids untranslated until translators fill them in; untranslated strings fall back to source text. Declining.



##########
superset/commands/chart/restore.py:
##########
@@ -0,0 +1,39 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Command to restore a soft-deleted chart."""
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+    ChartRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.daos.chart import ChartDAO
+from superset.models.slice import Slice
+
+
+class RestoreChartCommand(BaseRestoreCommand[Slice]):
+    """Restore a soft-deleted chart by clearing its ``deleted_at`` field.
+
+    All transactional wrapping and validation lives in
+    ``BaseRestoreCommand``; this subclass is purely declarative.
+    """
+
+    dao = ChartDAO
+    not_found_exc = ChartNotFoundError
+    forbidden_exc = ChartForbiddenError
+    restore_failed_exc = ChartRestoreFailedError

Review Comment:
   Following the surrounding file's conventions — local/test-scaffolding variables whose types are unambiguous from context. Declining as style.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3510306628


##########
superset/translations/ru/LC_MESSAGES/messages.po:
##########
@@ -3060,6 +3060,9 @@ msgstr "Изменения диаграммы"
 msgid "Chart could not be created."
 msgstr "Не удалось создать диаграмму"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate because it provides a Russian translation for the previously empty `msgstr` field. Filling this entry ensures that Russian-speaking users see a localized error message instead of the raw English source text when a chart restoration fails, which improves the user experience.
   
   **superset/translations/ru/LC_MESSAGES/messages.po**
   ```
   msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "Не удалось восстановить диаграмму."
   ```



##########
superset/translations/it/LC_MESSAGES/messages.po:
##########
@@ -2999,6 +2999,9 @@ msgstr "Ultima Modifica"
 msgid "Chart could not be created."
 msgstr "La tua query non può essere salvata"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion to complete the Italian translation for the new message ID is appropriate. In the context of localization files, leaving `msgstr` empty for new strings is standard practice, as it allows the system to fall back to the source English text until a translator provides the localized version. 
   
   However, if the goal is to ensure the Italian locale is fully supported immediately, providing the translation is a valid improvement. The suggestion is locally correct and improves the user experience for Italian-speaking users by avoiding untranslated English text.
   
   **superset/translations/it/LC_MESSAGES/messages.po**
   ```
   msgid "Chart could not be updated."
   -msgstr "La tua query non può essere salvata"
   +msgstr "Il grafico non può essere aggiornato"
   ```



##########
superset/translations/nl/LC_MESSAGES/messages.po:
##########
@@ -3118,6 +3118,9 @@ msgstr "Veranderingen in de grafiek"
 msgid "Chart could not be created."
 msgstr "Grafiek kon niet worden aangemaakt."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate for maintaining consistency in the translation catalog. While it is true that untranslated strings fall back to the source text, providing a translation ensures a consistent user experience in the target language, matching the established pattern for other error messages in the file.
   
   **superset/translations/nl/LC_MESSAGES/messages.po**
   ```
   3121: +msgid "Chart could not be restored."
    3122: +msgstr "De grafiek kon niet worden teruggezet."
   ```



##########
superset/translations/fa/LC_MESSAGES/messages.po:
##########
@@ -3065,6 +3065,9 @@ msgstr "تغییرات نمودار"
 msgid "Chart could not be created."
 msgstr "نمودار نتوانسته ایجاد شود."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The reviewer's suggestion to add a Persian translation is technically correct in the context of improving user experience, but the project's established practice for newly-extracted strings in translation catalogs is to leave the `msgstr` empty. This allows the system to fall back to the source text until a translator provides a localized version. Given this convention, declining the suggestion is appropriate.
   
   **superset/translations/fa/LC_MESSAGES/messages.po**
   ```
   +msgid "Chart could not be restored."
   +msgstr ""
   ```



##########
superset/translations/pt/LC_MESSAGES/messages.po:
##########
@@ -3045,6 +3045,9 @@ msgstr "Modificado pela última vez"
 msgid "Chart could not be created."
 msgstr "Não foi possível gravar a sua query"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate to apply. Providing a translation for the error message ensures that Portuguese-speaking users receive clear feedback instead of an empty string or English text when a chart fails to restore.
   
   **superset/translations/pt/LC_MESSAGES/messages.po**
   ```
   msgid "Chart could not be restored."
   -msgstr ""
   +msgstr "Não foi possível restaurar o gráfico."
   ```



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3384871807


##########
superset/translations/ar/LC_MESSAGES/messages.po:
##########
@@ -3103,6 +3103,9 @@ msgstr "تغييرات المخطط"
 msgid "Chart could not be created."
 msgstr "تعذر إنشاء مخطط."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Arabic translation</b></div>
   <div id="fix">
   
   The new msgid entry for 'Chart could not be restored.' has an empty msgstr. Arabic users will see the untranslated English text when this error occurs. Provide the Arabic translation to complete the localization.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/ar/LC_MESSAGES/messages.po (lines 3106-3107) ---
    3106: msgid "Chart could not be restored."
    3107: -msgstr ""
    3107: +msgstr "تعذر استعادة المخطط."
    3108: 
    3109:  msgid "Chart could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/pl/LC_MESSAGES/messages.po:
##########
@@ -3155,6 +3155,9 @@ msgstr "Zmiany wykresu"
 msgid "Chart could not be created."
 msgstr "Nie można utworzyć wykresu."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Polish translation</b></div>
   <div id="fix">
   
   The new message `msgstr ""` is empty, causing Polish users to see the untranslated English text. Compare with the consistent pattern: "Chart could not be created." → "Nie można utworzyć wykresu." and "Chart could not be updated." → "Nie można zaktualizować wykresu.". The suggested translation follows the same structure.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/tr/LC_MESSAGES/messages.po:
##########
@@ -2874,6 +2874,9 @@ msgstr ""
 msgid "Chart could not be created."
 msgstr "Grafik oluşturulamadı."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Turkish translation</b></div>
   <div id="fix">
   
   The `msgstr` is empty for the source string `"Chart could not be restored."` used by `ChartRestoreFailedError` in `superset/commands/chart/exceptions.py`. Turkish users will see the untranslated English error message. Following the established pattern for similar messages ("Grafik oluşturulamadı." for created, "Grafik gencellenemedi." for updated), the translation should be "Grafik geri yüklenemedi.".
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/tr/LC_MESSAGES/messages.po (lines 2877-2879)
    +++ superset/translations/tr/LC_MESSAGES/messages.po (lines 2877-2879)
    @@ -2875,6 +2875,7 @@
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "Grafik geri yüklenemedi."
    
     msgid "Chart could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/ca/LC_MESSAGES/messages.po:
##########
@@ -3121,6 +3121,9 @@ msgstr "Canvis del gràfic"
 msgid "Chart could not be created."
 msgstr "El gràfic no s'ha pogut crear."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Catalan translation</b></div>
   <div id="fix">
   
   Empty `msgstr` on line 3125 means Catalan users will see no error text when chart restore fails. Per the pattern from adjacent translations (lines 3122 and 3128), provide the Catalan translation. Without it, `ChartRestoreFailedError` raises an empty string to users.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/mi/LC_MESSAGES/messages.po:
##########
@@ -3063,6 +3063,9 @@ msgstr "Huringa kauwhata"
 msgid "Chart could not be created."
 msgstr "Kāore i taea te hanga i te kauwhata."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Māori translation</b></div>
   <div id="fix">
   
   The new `msgid "Chart could not be restored."` has an empty `msgstr ""`. This user-facing error message will display untranslated text to Māori-speaking users. Compare with the similar messages on lines 3064 and 3070, which have proper Māori translations. Add the appropriate translation to complete the localization.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/mi/LC_MESSAGES/messages.po (line 3067) ---
    3066: msgid "Chart could not be restored."
    3067:-msgstr ""
    3068:+msgstr "Kāore i taea te whakahoki i te kauwhata."
    3069: 
    3070: msgid "Chart could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/de/LC_MESSAGES/messages.po:
##########
@@ -3149,6 +3149,9 @@ msgstr "Diagrammänderungen"
 msgid "Chart could not be created."
 msgstr "Diagramm konnte nicht erstellt werden."
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing German translation</b></div>
   <div id="fix">
   
   The German translation for the new "Chart could not be restored." message is empty (`msgstr ""`). Adjacent messages have proper German translations (e.g., "Diagramm konnte nicht erstellt werden", "Diagramm konnte nicht aktualisiert werden"). An empty `msgstr` means the English source text will display to German users instead of a localized message.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/fi/LC_MESSAGES/messages.po:
##########
@@ -5342,6 +5342,9 @@ msgstr "Kaaviota ei voitu luoda."
 # de, es, fa, fr, it, ja, ko, lv, mi, nl, pl, pt, pt_BR, ru, sk, sl, tr, uk,
 # zh, zh_TW]
 #, fuzzy
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Finnish translation</b></div>
   <div id="fix">
   
   The new translation entry has an empty `msgstr` value. Finnish users will see the untranslated English message 'Chart could not be restored.' when this error occurs. Compare with similar entries: 'Chart could not be created.' → 'Kaaviota ei voitu luoda.' and 'Chart could not be updated.' → 'Kaaviota ei voitu päivittää.' — the new entry should follow this pattern.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/translations/zh_TW/LC_MESSAGES/messages.po:
##########
@@ -3030,6 +3030,9 @@ msgstr "圖表變化"
 msgid "Chart could not be created."
 msgstr "您的圖表無法創建。"
 
+msgid "Chart could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing zh_TW translation</b></div>
   <div id="fix">
   
   The new translation entry has an empty `msgstr` value. Traditional Chinese users will see the untranslated English string 'Chart could not be restored.' instead of localized text. Compare with adjacent entries: 'Chart could not be created.' → '您的圖表無法創建。' and 'Chart could not be updated.' → '您的圖表無法更新。'
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/zh_TW/LC_MESSAGES/messages.po
    +++ superset/translations/zh_TW/LC_MESSAGES/messages.po
    @@ -3031,7 +3031,7 @@
     msgstr "您的圖表無法創建。"
    
     msgid "Chart could not be restored."
    -msgstr ""
    +msgstr "您的圖表無法恢復。"
    
     msgid "Chart could not be updated."
     msgstr "您的圖表無法更新。"
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #612f1d</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342330668


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   **BLOCKER — inline import without circular-import justification (Scan 1, Rule 6)**
   
   `from superset.commands.importers.v1.utils import find_existing_for_import` is placed inside the function body with no comment.
   
   I traced the full import chain: `superset.commands.importers.v1.utils` imports only `superset.{db, models.core, models.dashboard, models.helpers, tags.models, utils, commands.importers.exceptions, databases.ssh_tunnel.models, extensions}` — none of which import from `superset.commands.chart.importers.v1.utils`. **No cycle exists.**
   
   Move to module top-level alongside the existing imports at lines 19–28.



##########
superset/migrations/versions/2026-05-08_12-00_7c4a8d09ca37_add_deleted_at_to_slices.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Add deleted_at column and index to slices for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``slices`` table to support soft deletion of charts. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 7c4a8d09ca37
+Revises: 33d7e0e21daa
+Create Date: 2026-05-08 12:00:00.000000
+"""
+
+from sqlalchemy import Column, DateTime
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "7c4a8d09ca37"
+down_revision = "33d7e0e21daa"

Review Comment:
   **MEDIUM — sibling `down_revision` conflict must be resolved before any two of the three PRs land together**
   
   This migration shares `down_revision = "33d7e0e21daa"` with #40128 (dashboards) and #40130 (datasets). When any two land in the same DB, Alembic raises `ValueError: Multiple head revisions` on the third.
   
   A merge migration is required:
   ```python
   # merge_charts_dashboards.py  (example)
   down_revision = ("7c4a8d09ca37", "9e1f3b8c4d2a")  # charts + dashboards
   revision = "<new_hash>"
   ```
   Please write and land the merge migration alongside whichever of the three PRs merges second.



##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import
+
     user = get_user()

Review Comment:
   **MEDIUM (×2) — undocumented `user=None` bypass + redundant `get_user()` call**
   
   **1. `user=None` path not in the permission matrix**
   When `can_write=True` (e.g., via `ignore_permissions=True`) and `get_user()` returns `None`, the ownership check at lines 88–93 is silently skipped because the guard `if needs_mutation and can_write and user:` short-circuits. The docstring table has no row for this case. Add a clarifying comment:
   ```python
   # When user is None (background import with ignore_permissions=True),
   # the ownership check below is intentionally skipped — the caller has
   # established trust at the command level.
   user = get_user()
   ```
   
   **2. Redundant `get_user()` call at the end of the function**
   The pre-existing line near the end of `import_chart` reads:
   ```python
   if (user := get_user()) and user not in chart.owners:
   ```
   This calls `get_user()` again despite `user` already being bound here. Since both calls happen in the same request, they return the same value. The walrus rebinding also silently replaces the binding from this line in the outer scope.
   
   Suggested fix for that line:
   ```python
   if user and user not in chart.owners:
       chart.owners.append(user)
   ```



##########
UPDATING.md:
##########
@@ -30,6 +30,18 @@ Importing a dataset now validates the `catalog` field against the target databas
 
 If you relied on importing datasets with a non-default catalog, enable "Allow changing catalogs" on the target connection, or set the dataset's catalog to the connection's default before importing.
 
+### Soft delete and restore for charts
+
+`DELETE /api/v1/chart/<id>` no longer hard-deletes the chart. The row is marked with a `deleted_at` timestamp and hidden from all list, detail, and lookup endpoints. Charts in this state are excluded from default queries and from relationship loads (e.g. `dashboard.slices`).
+
+**New endpoint** — `POST /api/v1/chart/<uuid>/restore` clears `deleted_at` and returns the chart to active state. Requires `can_write on Chart` and ownership of the row (or admin). Soft-deleted charts can also be surfaced in the list endpoint via the new `chart_deleted_state` rison filter: `include` returns both live and soft-deleted rows, `only` returns just the soft-deleted ones. Any other value is ignored.
+
+**Permissions migration:** existing role grants of `can_write on Chart` cover the new restore endpoint automatically; no role migration is required.
+
+**Schema migration:** the migration adds a nullable `deleted_at` column and an index on it (`ix_slices_deleted_at`) to the `slices` table. The column add is instant; the index build runs inline (no `CONCURRENTLY`) and may briefly block reads on the `slices` table for the duration of the build on large Postgres deployments. MySQL InnoDB builds the index online (no blocking).

Review Comment:
   **HIGH — factual error: PostgreSQL `CREATE INDEX` blocks writes, not reads**
   
   > *may briefly block reads on the `slices` table for the duration of the build on large Postgres deployments*
   
   `CREATE INDEX` (non-CONCURRENT) acquires a `ShareLock`, which conflicts with `RowExclusiveLock` (INSERT/UPDATE/DELETE) but **not** with `AccessShareLock` (SELECT). Reads continue uninterrupted; writes are queued during the build.
   
   This also contradicts the PR description, which says *"non-blocking on Postgres."*
   
   Suggested correction:
   > *the index build runs inline (no `CONCURRENTLY`) and may briefly block writes on the `slices` table (INSERT/UPDATE/DELETE are queued while the index builds; reads are unaffected) on large Postgres deployments. MySQL InnoDB builds the index online (no blocking).*



##########
tests/integration_tests/charts/soft_delete_tests.py:
##########
@@ -0,0 +1,406 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for chart soft-delete and restore."""
+
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import ADMIN_USERNAME, ALPHA_USERNAME
+from tests.integration_tests.insert_chart_mixin import InsertChartMixin
+
+
+def _hard_delete_chart(chart_id: int) -> None:
+    """Hard-delete a chart row regardless of soft-delete state."""
+    row = (
+        db.session.query(Slice)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Slice}})
+        .filter(Slice.id == chart_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+def _hard_delete_dashboard_for_charts_test(dashboard_id: int) -> None:
+    """Hard-delete a dashboard row regardless of soft-delete state."""
+    row = (
+        db.session.query(Dashboard)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {Dashboard}})
+        .filter(Dashboard.id == dashboard_id)
+        .one_or_none()
+    )
+    if row:
+        db.session.delete(row)
+        db.session.commit()
+
+
+class TestChartSoftDelete(InsertChartMixin, SupersetTestCase):
+    """Tests for chart soft-delete behaviour (T013, T016)."""
+
+    def test_delete_chart_soft_deletes(self):

Review Comment:
   **NIT (×2) — missing `-> None` on all test methods + cleanup not guarded against failure**
   
   **1. Missing return types (Scan 11)**
   All 12 test methods in this file are missing `-> None`. Affected lines: 58, 81, 95, 111, 135, 159, 174, 240, 258, 266, 280, 378. The unit tests in `restore_test.py` already follow this convention.
   Example fix: `def test_delete_chart_soft_deletes(self) -> None:`
   
   **2. Cleanup not guarded against assertion failure**
   Each test calls `_hard_delete_chart(chart_id)` as a trailing statement. If any assertion above it fails, the chart is orphaned in the test DB. Pattern: add `self.addCleanup(_hard_delete_chart, chart.id)` immediately after creating the chart — it runs unconditionally even when the test raises.
   Applies to every test method in both `TestChartSoftDelete` and `TestChartRestore`.



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342336291


##########
superset/commands/chart/importers/v1/utils.py:
##########
@@ -48,20 +48,86 @@ def import_chart(
     overwrite: bool = False,
     ignore_permissions: bool = False,
 ) -> Slice:
+    """Import a chart from a config dict, handling existing matches.
+
+    Permission model for an existing UUID match:
+
+    +--------------+---------------+---------------------+-----------------+
+    | Existing row | overwrite arg | Caller has perms?   | Outcome         |
+    +==============+===============+=====================+=================+
+    | alive        | False         | (n/a)               | return existing |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write + owner   | UPDATE in place |
+    +--------------+---------------+---------------------+-----------------+
+    | alive        | True          | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write + owner   | restore + UPDATE|
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | can_write,          | raise           |
+    |              |               | not owner/admin     |                 |
+    +--------------+---------------+---------------------+-----------------+
+    | soft-deleted | False or True | not can_write       | raise (Case B)  |
+    +--------------+---------------+---------------------+-----------------+
+
+    Re-importing a soft-deleted UUID is implicitly a restore-with-update:
+    the user is bringing the chart back by uploading it again. We apply
+    the same ownership check as the explicit overwrite path so non-owners
+    cannot resurrect via re-import, and we raise rather than silently
+    returning a soft-deleted row to callers without write permission
+    (which would let them reattach dashboards to a deleted chart).
+    """
     can_write = ignore_permissions or security_manager.can_access("can_write", "Chart")
-    existing = db.session.query(Slice).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import
+
     user = get_user()

Review Comment:
   **MEDIUM (×2) — undocumented `user=None` bypass + redundant `get_user()` call**
   
   **1. `user=None` path not in the permission matrix**
   When `can_write=True` (e.g., via `ignore_permissions=True`) and `get_user()` returns `None`, the ownership check at lines 88–93 is silently skipped because the guard `if needs_mutation and can_write and user:` short-circuits. The docstring table has no row for this case. Suggested inline comment:
   ```python
   # When user is None (background import with ignore_permissions=True),
   # the ownership check below is intentionally skipped — the caller has
   # established trust at the command level.
   user = get_user()
   ```
   
   **2. Redundant `get_user()` call at end of function**
   The pre-existing line near the end of `import_chart` reads:
   ```python
   if (user := get_user()) and user not in chart.owners:
   ```
   This calls `get_user()` again despite `user` already being bound here — same request, same return value. The walrus rebinding also silently replaces the line-83 binding in the outer scope.
   
   Suggested fix for that line:
   ```python
   if user and user not in chart.owners:
       chart.owners.append(user)
   ```



-- 
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] feat(charts): soft-delete and restore [superset]

Posted by "mikebridge (via GitHub)" <gi...@apache.org>.
mikebridge commented on PR #40129:
URL: https://github.com/apache/superset/pull/40129#issuecomment-4614228208

   Thanks @richardfogaca for the approval and the framing in the praise paragraph — the "guardrails the API diff alone wouldn't show" line is exactly the lens I had in mind when I structured the per-entity restore tests around owner / non-owner / no-can_write / trusted-loader paths.
   
   The architectural decisions you called out (mapping \`restore\` back to \`write\`, keeping restore on the shared command path, preserving chart relationships on soft-delete, the importer test matrix) all came directly from earlier-round review feedback — the iterative process did the work. Appreciate the careful trace through them.


-- 
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] feat(charts): soft-delete and restore [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 #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3397905186


##########
superset/commands/chart/exceptions.py:
##########
@@ -123,6 +123,16 @@ class ChartDeleteFailedError(DeleteFailedError):
     message = _("Charts could not be deleted.")
 
 
+class ChartRestoreFailedError(UpdateFailedError):
+    # Restore semantically clears ``deleted_at``; it is an UPDATE, not a new
+    # row. ``UpdateFailedError`` is the nearest typed middle-tier base in the
+    # codebase. A dedicated ``RestoreFailedError`` in
+    # ``superset/commands/exceptions.py`` would be more precise across the
+    # entity rollouts but lives in already-merged infrastructure (#39977);
+    # introducing it can be a cross-entity follow-up.
+    message = _("Chart could not be restored.")

Review Comment:
   **Suggestion:** Add a class docstring to this newly introduced exception class to satisfy the requirement that new Python classes are documented inline. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python class and it does not include a docstring. The
   class only has comments and a class attribute, so it violates the rule that
   new classes should be documented inline.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5bc6e1c5e1a04ce7b9d3d4a8299659ce&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5bc6e1c5e1a04ce7b9d3d4a8299659ce&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/chart/exceptions.py
   **Line:** 126:133
   **Comment:**
   	*Custom Rule: Add a class docstring to this newly introduced exception class to satisfy the requirement that new Python classes are documented inline.
   
   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%2F40129&comment_hash=bce5c5c38a3f8880742fd5557f31c35e422d84de590377c48fdd975ed161f135&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=bce5c5c38a3f8880742fd5557f31c35e422d84de590377c48fdd975ed161f135&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/chart/restore_test.py:
##########
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for RestoreChartCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.commands.chart.exceptions import (
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.chart.restore import RestoreChartCommand
+from superset.exceptions import SupersetSecurityException
+
+
+def test_restore_chart_clears_deleted_at(app_context: None) -> None:
+    """RestoreChartCommand.run() restores a soft-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    chart.id = 1
+
+    with (
+        patch(
+            "superset.daos.chart.ChartDAO.find_by_id", return_value=chart
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreChartCommand("1")
+        cmd.run()
+
+    mock_find.assert_called_once()
+    chart.restore.assert_called_once()
+
+
+def test_restore_chart_not_found_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for missing chart."""
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=None):
+        cmd = RestoreChartCommand("999")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_chart_raises_not_found(app_context: None) -> None:
+    """RestoreChartCommand raises ChartNotFoundError for non-deleted chart."""
+    chart = MagicMock()
+    chart.deleted_at = None  # not soft-deleted
+
+    with patch("superset.daos.chart.ChartDAO.find_by_id", return_value=chart):
+        cmd = RestoreChartCommand("1")
+        with pytest.raises(ChartNotFoundError):
+            cmd.run()
+
+
+def test_restore_chart_forbidden_raises(app_context: None) -> None:
+    """RestoreChartCommand raises ChartForbiddenError on permission check."""
+    chart = MagicMock()
+    chart.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+
+    def raise_security(*args: object, **kwargs: object) -> None:
+        raise SupersetSecurityException(MagicMock())

Review Comment:
   **Suggestion:** Add an inline docstring to the newly introduced helper function so that all new functions in this file are documented. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly introduced function in the added test file, and it does not have a docstring. The custom rule explicitly requires newly added Python functions and classes to include docstrings, so this is a real violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=66b68a1f2120404886cdfcd2329ed8a1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=66b68a1f2120404886cdfcd2329ed8a1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/commands/chart/restore_test.py
   **Line:** 79:80
   **Comment:**
   	*Custom Rule: Add an inline docstring to the newly introduced helper function so that all new functions in this file are documented.
   
   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%2F40129&comment_hash=65d45d6cc3b05a87c1308f350ea8ded8a29225f27ff3242ffebb54b43e14deb6&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40129&comment_hash=65d45d6cc3b05a87c1308f350ea8ded8a29225f27ff3242ffebb54b43e14deb6&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