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:28 UTC

[PR] feat(datasets): soft-delete and restore (sc-106191) [superset]

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

   ### SUMMARY
   
   Wire **datasets** 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 `SqlaTable`.
   
   #### What this PR ships
   
   **Migration** (`superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py`)
   
   - `revision = 3a8e6f2c1b95`, `down_revision = 33d7e0e21daa`. Adds a nullable `deleted_at` column and `ix_tables_deleted_at` index to `tables`. Reversible. Uses `superset.migrations.shared.utils` helpers so the migration is idempotent.
   - **Note**: this PR shares `down_revision = 33d7e0e21daa` with the charts (sc-106189) and dashboards (sc-106190 / #40128) sibling PRs. Whichever lands second/third will need a rebase or merge migration.
   
   **Model + DAO**
   
   - `SqlaTable` inherits `SoftDeleteMixin` (`superset/connectors/sqla/models.py`). The `do_orm_execute` listener from the infrastructure PR begins filtering `SqlaTable` queries (including relationship lazy loads, via `with_loader_criteria(..., propagate_to_loaders=True)`).
   - `DeleteDatasetCommand` 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**
   
   - `RestoreDatasetCommand` (`superset/commands/dataset/restore.py`) — 4 ClassVar declarations subclassing `BaseRestoreCommand[SqlaTable]`. No method overrides; the base class owns validation, ownership checks, and the transactional wrapper.
   - `POST /api/v1/dataset/<uuid>/restore` endpoint (`superset/datasets/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.
   - `DatasetDeletedStateFilter` (`superset/datasets/filters.py`) — 2-line subclass of `BaseDeletedStateFilter` setting `arg_name = "dataset_deleted_state"` and `model = SqlaTable`. Wired into `search_filters` on `DatasetRestApi`.
   - `DatasetRestApi` gains `SoftDeleteApiMixin` and `"restore"` is added to `include_route_methods`.
   - `DatasetRestoreFailedError` exception type added (`superset/commands/dataset/exceptions.py`).
   
   **Import pipeline** (`superset/commands/dataset/importers/v1/utils.py`)
   
   - Updates `import_dataset` 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/dataset/<pk>` | Hard-deletes the row | Sets `deleted_at`; row remains but is hidden from default queries |
   | `GET /api/v1/dataset/?...&dataset_deleted_state=only` | Filter doesn't exist (400) | Returns soft-deleted datasets with `deleted_at` populated |
   | `GET /api/v1/dataset/?...&dataset_deleted_state=include` | Filter doesn't exist (400) | Returns live + soft-deleted; `deleted_at` populated on deleted rows |
   | `POST /api/v1/dataset/<uuid>/restore` | 404 (no such endpoint) | Clears `deleted_at` on the soft-deleted row |
   
   ### TESTING INSTRUCTIONS
   
   ```bash
   # Unit tests
   pytest tests/unit_tests/commands/dataset/restore_test.py -v
   
   # Integration tests
   pytest tests/integration_tests/datasets/soft_delete_tests.py -v
   ```
   
   The integration suite covers:
   
   - DELETE sets `deleted_at` instead of removing the row
   - Soft-deleted datasets excluded from default list and from individual GET (404)
   - `dataset_deleted_state=only` returns soft-deleted with `deleted_at` populated
   - `dataset_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 datasets
   - Re-import of a soft-deleted UUID via the v1 importer succeeds (and only after permission check)
   - Charts referencing a soft-deleted dataset render an error at chart-load time (V1 documented behaviour)
   
   ### ADDITIONAL INFORMATION
   
   - [X] Has associated issue: [sc-106191](https://app.shortcut.com/preset/story/106191), [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 `tables` table. Instant on Postgres/MySQL/SQLite for any realistic deployment size; no lock-holding.*
   - [X] Introduces new feature or API — soft-delete behaviour, `dataset_deleted_state` rison filter, `POST /api/v1/dataset/<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/dataset/<pk>` is now soft.** Existing API consumers that called DELETE expecting permanent removal will see the dataset 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 `tables` table will see the row.
   - **Cascade behaviour (V1, per SIP-208):** soft-delete does **not** cascade from a dataset to its charts. Charts that reference a soft-deleted dataset render an error at chart-load time — the existing behaviour for any unfound dataset. A future ticket may introduce a "degraded chart" state; that's out of scope here. The integration tests cover this case explicitly so the behaviour can't regress unnoticed.
   
   #### Depends on
   
   - #39977 (infrastructure)
   
   #### Coordination with sibling PRs
   
   This PR's migration shares `down_revision = 33d7e0e21daa` with:
   
   - sc-106189 charts — `7c4a8d09ca37`
   - #40128 (sc-106190 dashboards) — `9e1f3b8c4d2a`
   
   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(datasets): soft-delete and restore [superset]

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


##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +36,23 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete. Prefer live rows over
+    # soft-deleted ones via ``ORDER BY deleted_at IS NULL DESC, id`` —
+    # the filter doesn't include ``catalog``, so it can match more than
+    # one row when a soft-deleted row coexists with a live row that
+    # differs only by catalog (e.g. NULL vs ``"public"``). ``.first()``
+    # plus the live-first ordering keeps the behaviour predictable
+    # without surfacing a ``MultipleResultsFound`` for that case.
     return (
         db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
         .filter_by(database_id=database.id, schema=schema, table_name=table_name)
-        .one_or_none()
+        .order_by(SqlaTable.deleted_at.is_(None).desc(), SqlaTable.id)
+        .first()

Review Comment:
   Fixed in d66d661b36 — `get_table` now includes the normalized `catalog` (database default, the same rule `validate_uniqueness` applies) in the lookup, so it can't bind to a different catalog variant when rows share `(database_id, schema, table_name)`.



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

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3357115338


##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +36,23 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete. Prefer live rows over
+    # soft-deleted ones via ``ORDER BY deleted_at IS NULL DESC, id`` —
+    # the filter doesn't include ``catalog``, so it can match more than
+    # one row when a soft-deleted row coexists with a live row that
+    # differs only by catalog (e.g. NULL vs ``"public"``). ``.first()``
+    # plus the live-first ordering keeps the behaviour predictable
+    # without surfacing a ``MultipleResultsFound`` for that case.
     return (
         db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
         .filter_by(database_id=database.id, schema=schema, table_name=table_name)
-        .one_or_none()
+        .order_by(SqlaTable.deleted_at.is_(None).desc(), SqlaTable.id)
+        .first()

Review Comment:
   **Suggestion:** This lookup now silently resolves ambiguous matches by taking the first row after ordering, which can return a dataset from a different catalog when multiple rows share the same `database_id/schema/table_name`. That causes test setup to mutate/reuse the wrong dataset instead of failing fast. Add `catalog` to the lookup criteria (or raise when multiple live matches exist) so setup remains correct and deterministic. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Dashboard fixtures can bind to wrong catalog-specific dataset.
   - ⚠️ Integration tests may mutate unexpected SqlaTable records.
   - ⚠️ Soft-delete restores may target unintended catalog variant.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Observe in `tests/unit_tests/migrations/shared/catalogs_test.py:13-20` and `:80-88`
   that the test suite explicitly creates two `SqlaTable` rows with the same
   `database`/`schema`/`table_name` (`"my_table"` in `"public"`) but different `catalog`
   values (`None` and `"other_catalog"`), proving the ORM and schema allow such duplicates
   distinguished only by `catalog`.
   
   2. In an integration test using the dashboard fixtures (for example,
   `tests/integration_tests/fixtures/world_bank_dashboard.py:29-35` or
   `energy_dashboard.py:13-18`), call `create_table_metadata(table_name, database)` from
   `tests/integration_tests/dashboard_utils.py:59-69` for a `table_name`/`schema`/`database`
   combination where two live `SqlaTable` rows exist that differ only by `catalog`, analogous
   to the setup in `catalogs_test.py`.
   
   3. `create_table_metadata()` calls `get_table()` at
   `tests/integration_tests/dashboard_utils.py:68`, which executes a query built at lines
   50-55: it filters only on `database_id`, `schema`, and `table_name` (line 53) and then
   orders by `SqlaTable.deleted_at.is_(None).desc(), SqlaTable.id` and calls `.first()`
   (lines 54-55), without including `catalog` in the filter.
   
   4. With two live rows matching the filter but with different `catalog` values, both have
   `deleted_at IS NULL`, so the ordering reduces to `id` and `get_table()` deterministically
   returns whichever row was inserted first, regardless of `catalog`.
   `create_table_metadata()` then restores/mutates this potentially wrong dataset (lines
   69-82), so the fixture can attach metrics and descriptions to a dataset in the wrong
   catalog instead of failing fast or selecting the catalog-specific one.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=45a4615ac8de41959e860aee44000158&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=45a4615ac8de41959e860aee44000158&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/dashboard_utils.py
   **Line:** 52:55
   **Comment:**
   	*Logic Error: This lookup now silently resolves ambiguous matches by taking the first row after ordering, which can return a dataset from a different catalog when multiple rows share the same `database_id/schema/table_name`. That causes test setup to mutate/reuse the wrong dataset instead of failing fast. Add `catalog` to the lookup criteria (or raise when multiple live matches exist) so setup remains correct and deterministic.
   
   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%2F40130&comment_hash=181065d026ceef465a50cc05984ded44702dfa4790659c4253ec5bcb66db99cb&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=181065d026ceef465a50cc05984ded44702dfa4790659c4253ec5bcb66db99cb&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(datasets): soft-delete and restore [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3455384208


##########
superset/translations/ko/LC_MESSAGES/messages.po:
##########
@@ -4578,6 +4578,9 @@ msgstr ""
 msgid "Dataset could not be duplicated."
 msgstr "데이터베이스를 업데이트할 수 없습니다."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Korean translation</b></div>
   <div id="fix">
   
   Empty `msgstr` leaves the error message untranslated in Korean UI. Other messages in this group (duplicated, updated, does not exist) all have Korean translations. This user-facing error text should be translated for consistency and Korean locale completeness.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #5248c1</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:
##########
@@ -4618,6 +4618,9 @@ msgstr "Kāore i taea te hanga i te rārangi raraunga."
 msgid "Dataset could not be duplicated."
 msgstr "Kāore i taea te tārua i te rārangi raraunga."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Maori translation</b></div>
   <div id="fix">
   
   The new translation entry for "Dataset could not be restored." has an empty `msgstr`. All adjacent dataset error messages use the pattern "Kāore i taea te [verb] i te rārangi raraunga" (e.g., "created"→"hanga", "duplicated"→"tārua", "updated"→"whakahou"). For consistency, use "whakaora" (restore) to complete the Maori localization.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/translations/mi/LC_MESSAGES/messages.po
    +++ b/superset/translations/mi/LC_MESSAGES/messages.po
    @@ -4618,8 +4618,8 @@ msgstr "Kāore i taea te tārua i te rārangi raraunga."
     msgid "Dataset could not be duplicated."
     msgstr "Kāore i taea te tārua i te rārangi raraunga."
    
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "Kāore i taea te whakaora i te rārangi raraunga."
    
     msgid "Dataset could not be updated."
     msgstr "Kāore i taea te whakahou i te rārangi raraunga."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #5248c1</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/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup: the mocked restore left the example dataset soft-deleted.
+        _restore_dataset(dataset_id)

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing finally block in test cleanup</b></div>
   <div id="fix">
   
   Wrap the dataset restore call and assertion in a `try/finally` block to ensure `_restore_dataset(dataset_id)` always runs, mirroring the pattern in other tests.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a8946</i></small>
   </div><div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing finally for cleanup</b></div>
   <div id="fix">
   
   The cleanup call at line 340 is outside the `try`/`with` block. Any assertion failure inside the `with patch(...)` block will skip the restore, stranding the example dataset as soft-deleted. The rest of this file consistently uses `try`/`finally` blocks for cleanup (e.g. lines 85, 101, 126, 148, 248, 285, 379). Move the call into a `finally` block to match the established pattern.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/tests/integration_tests/datasets/soft_delete_tests.py
    +++ b/tests/integration_tests/datasets/soft_delete_tests.py
    @@ -334,6 +334,8 @@ class TestDatasetRestore(SupersetTestCase):
                 side_effect=DatasetRestoreFailedError(),
             ):
                 rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
    +        finally:
    +            _restore_dataset(dataset_id)
             assert rv.status_code == 422
    
    -        # Cleanup: the mocked restore left the example dataset soft-deleted.
    -        _restore_dataset(dataset_id)
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #5248c1</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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3509996967


##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,474 @@
+# 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 dataset 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.core import Database
+from superset.models.slice import Slice
+from superset.utils import json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.conftest import with_feature_flags
+from tests.integration_tests.constants import (
+    ADMIN_USERNAME,
+    ALPHA_USERNAME,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    @with_feature_flags(SOFT_DELETE=True)
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup: the mocked restore left the example dataset soft-deleted.
+        _restore_dataset(dataset_id)

Review Comment:
   **Suggestion:** The restore cleanup runs only after the status assertion, so if the endpoint returns an unexpected response the example dataset remains soft-deleted and can break following tests. Move `_restore_dataset(dataset_id)` into a `finally` block around the patched restore request/assertion. [missing cleanup]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   ⚠️ Example dataset remains soft-deleted after failing restore test.
   ⚠️ Later tests relying on live dataset may intermittently fail.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Run the integration test suite including
   `TestDatasetRestore.test_restore_failure_returns_422` in
   `tests/integration_tests/datasets/soft_delete_tests.py:322-350`, which uses
   `_get_example_dataset` at lines 300-303 to fetch a shared example dataset and then
   soft-deletes it via `DELETE /api/v1/dataset/<id>` at line 340.
   
   2. The test patches `RestoreDatasetCommand.run` at lines 342-345 to raise
   `DatasetRestoreFailedError` and then posts to `POST /api/v1/dataset/<uuid>/restore` at
   line 346, asserting `rv.status_code == 422` at line 347 to validate the error mapping.
   
   3. Cleanup of the shared example dataset is performed by a bare
   `_restore_dataset(dataset_id)` call at line 350, which is not inside a `try/finally` block
   and runs only if the assertion at line 347 succeeds; a failed assertion stops execution
   before reaching this cleanup.
   
   4. When the restore endpoint behavior changes (e.g., returning 500 or 200 instead of 422),
   the assertion at line 347 fails, `_restore_dataset(dataset_id)` is never called, and the
   shared example dataset remains soft-deleted; subsequent tests such as
   `test_restore_soft_deleted_dataset` at lines 306-320 or any test using
   `_get_example_dataset` now operate on a soft-deleted dataset, causing cascading failures
   and non-deterministic test results.
   ```
   </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=ef996758672145f1bba03afa79659207&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=ef996758672145f1bba03afa79659207&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/datasets/soft_delete_tests.py
   **Line:** 342:350
   **Comment:**
   	*Missing Cleanup: The restore cleanup runs only after the status assertion, so if the endpoint returns an unexpected response the example dataset remains soft-deleted and can break following tests. Move `_restore_dataset(dataset_id)` into a `finally` block around the patched restore request/assertion.
   
   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%2F40130&comment_hash=957f7c6b59c345a9731e8a9ef6314d5427c7bda513d352a4dd2415717f6367ec&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=957f7c6b59c345a9731e8a9ef6314d5427c7bda513d352a4dd2415717f6367ec&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(datasets): soft-delete and restore [superset]

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

   Thanks @rusackas — all five addressed:
   
   1. **Squashed** ✅ — the PR is now a single commit (`123db2618c`); the tree is byte-identical to the last green CI run, only history changed. **Bot threads**: doing one clean triage pass now (the recent pushes triggered bot re-reviews, so sweeping once rather than chasing a moving target) — each will get a reply-with-rationale or a fix, same as the sweep on #39859.
   
   2. **Already rebased** ✅ — the branch sits directly on current master (`393adc45`), which includes #41166, so CI has been running the gated path: the soft-delete suites run under `@with_feature_flags(SOFT_DELETE=True)`, and the full DB matrix is green (the one red ❌ on a previous run was an artifact-upload timeout *after* all 2393 MySQL tests passed — a re-run clears it).
   
   3. **Confirmed intentional** ✅ — both are pre-existing-bug fixes that are correct regardless of the flag: the catalog-NULL-aware uniqueness matching (a `catalog=NULL` row *is* the default-catalog dataset; the old predicate let twin pairs slip through) and the duplicate-scope fix (collisions should be scoped to (database, catalog, schema), not global-by-name). Since they ship un-gated, they're called out explicitly in UPDATING.md under "Uniqueness-validation changes that apply regardless of the feature flag."
   
   4. **Intended** ✅ — deliberate no-orphaned-rows/no-lost-restorables trade-off, documented in UPDATING.md including the operator workaround. The planned resolution is the deletion-retention purge (#41549), which is sequenced after the entity PRs.
   
   5. **Good catch — extracted** ✅ — the `_escape_like` hardening is now #41653 and this branch is back to master's version. Bonus: splitting it out surfaced a real bug in the hardening — coercing `None` to `""` built a wildcard-only pattern (`%%`) that silently matched **every** row. The standalone PR fixes the semantics properly (`None` matches no rows, mirroring SQL's `x LIKE NULL`), with tests that reproduce the original `AttributeError` against master.


-- 
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(datasets): soft-delete and restore (sc-106191) [superset]

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

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | fefb486d51495e2fc1ed6f0a3f7a9e517c52dc46 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a0646e6fb08bd00084cc582 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-40130--superset-docs-preview.netlify.app](https://deploy-preview-40130--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.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQwMTMwLS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.qAw-sxy0gDWC4QHVMkXrwYOya_PHV4iGyCR0fXRtmGM)<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#DcoxDoAgDADAv3SWpBht0B_4DKAlDigEuhjj32W74V6orVxVYQeYIDR_x3O4R2OR7GYNe_VdtJtekhqWLCpjstRcnoPHJY-0kFAK6AIjoltiXN0M3w8) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-40130--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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3365903803


##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,300 @@
+# 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 dataset soft-delete and restore."""
+
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+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
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Restore a soft-deleted dataset (cleanup helper).
+
+        Used in ``finally`` blocks so a failed assertion can't strand a
+        soft-deleted row and leak it into later tests; re-queries with the
+        visibility-filter bypass and only restores if still soft-deleted.
+        """
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row is not None and row.deleted_at is not None:
+            row.restore()
+            db.session.commit()
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            self.client.delete(f"/api/v1/dataset/{dataset_id}")

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>CWE-483: Missing DELETE status assertion</b></div>
   <div id="fix">
   
   Missing assertion for DELETE response status code. The delete call at line 80 should be captured in a variable and asserted to be 200, consistent with the pattern in `test_delete_dataset_soft_deletes` at line 61. Without this, a failed delete (e.g., 403, 404, 500) silently passes through, leaving the dataset alive and causing subsequent assertions to fail for the wrong reason. (See also: [CWE-483](https://cwe.mitre.org/data/definitions/483.html))
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- tests/integration_tests/datasets/soft_delete_tests.py
    +++ tests/integration_tests/datasets/soft_delete_tests.py
    @@ -77,7 +77,8 @@
             self.login(ADMIN_USERNAME)
    
             try:
    -            self.client.delete(f"/api/v1/dataset/{dataset_id}")
    +            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
    +            assert rv.status_code == 200
    
                 rv = self.client.get("/api/v1/dataset/")
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #227619</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/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,300 @@
+# 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 dataset soft-delete and restore."""
+
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+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
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Restore a soft-deleted dataset (cleanup helper).
+
+        Used in ``finally`` blocks so a failed assertion can't strand a
+        soft-deleted row and leak it into later tests; re-queries with the
+        visibility-filter bypass and only restores if still soft-deleted.
+        """
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row is not None and row.deleted_at is not None:
+            row.restore()
+            db.session.commit()
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            self.client.delete(f"/api/v1/dataset/{deleted_id}")

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>CWE-483: Missing DELETE status assertion</b></div>
   <div id="fix">
   
   Missing assertion for DELETE response status code. The delete call at line 121 should be asserted to return 200, consistent with `test_delete_dataset_soft_deletes`. Without this, a failed delete silently passes and the test assertions at lines 129-130 may pass incorrectly. (See also: [CWE-483](https://cwe.mitre.org/data/definitions/483.html))
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- tests/integration_tests/datasets/soft_delete_tests.py
    +++ tests/integration_tests/datasets/soft_delete_tests.py
    @@ -118,7 +118,8 @@
             self.login(ADMIN_USERNAME)
    
             try:
    -            self.client.delete(f"/api/v1/dataset/{deleted_id}")
    +            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
    +            assert rv.status_code == 200
    
                 rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #227619</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/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,300 @@
+# 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 dataset soft-delete and restore."""
+
+from superset.connectors.sqla.models import SqlaTable
+from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+from superset.extensions import db
+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
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Restore a soft-deleted dataset (cleanup helper).
+
+        Used in ``finally`` blocks so a failed assertion can't strand a
+        soft-deleted row and leak it into later tests; re-queries with the
+        visibility-filter bypass and only restores if still soft-deleted.
+        """
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row is not None and row.deleted_at is not None:
+            row.restore()
+            db.session.commit()
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            self.client.delete(f"/api/v1/dataset/{dataset_id}")

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>CWE-483: Missing DELETE status assertion</b></div>
   <div id="fix">
   
   Missing assertion for DELETE response status code. The delete call at line 95 should be asserted to return 200, consistent with `test_delete_dataset_soft_deletes`. Without this, a failed delete silently passes, causing the subsequent assertions to fail for an unintended reason. (See also: [CWE-483](https://cwe.mitre.org/data/definitions/483.html))
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- tests/integration_tests/datasets/soft_delete_tests.py
    +++ tests/integration_tests/datasets/soft_delete_tests.py
    @@ -92,7 +92,8 @@
             self.login(ADMIN_USERNAME)
    
             try:
    -            self.client.delete(f"/api/v1/dataset/{dataset_id}")
    +            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
    +            assert rv.status_code == 200
    
                 rison_query = (
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #227619</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(datasets): soft-delete and restore [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3385131270


##########
superset/translations/ru/LC_MESSAGES/messages.po:
##########
@@ -4586,6 +4586,9 @@ msgstr "Не удалось создать датасет"
 msgid "Dataset could not be duplicated."
 msgstr "Датасет не может быть дублирован"
 
+msgid "Dataset 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 message `Dataset could not be restored.` has an empty `msgstr`. Compare with similar error messages in this file: `Dataset could not be created.` → `msgstr "Не удалось создать датасет"` and `Dataset could not be updated.` → `msgstr "Не удалось обновить датасет"`. Apply the same pattern to produce `msgstr "Не удалось восстановить датасет"`.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/ru/LC_MESSAGES/messages.po (lines 4589-4590) ---
    4589: msgid "Dataset could not be restored."
    4590:-msgstr ""
    4590:+msgstr "Не удалось восстановить датасет"
    4591: 
    4592:  msgid "Dataset could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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:
##########
@@ -4664,6 +4664,9 @@ msgstr "Sadu dat sa nepodarilo vytvoriť."
 msgid "Dataset could not be duplicated."
 msgstr "Sadu dat sa nepodarilo duplikovať."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing translation string</b></div>
   <div id="fix">
   
   The `msgstr` field is empty, causing Slovak users to see untranslated English text "Dataset could not be restored." instead of a proper Slovak translation. Apply the established translation pattern: "Sadu dat sa nepodarilo obnoviť."
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/sk/LC_MESSAGES/messages.po (lines 4667-4668)---
    4667:  msgid "Dataset could not be restored."
    4668: -msgstr ""
    4668: +msgstr "Sadu dat sa nepodarilo obnoviť."
    4669: +
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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/databases/commands/delete_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.
+
+from datetime import datetime
+
+import pytest
+from pytest_mock import MockerFixture
+from sqlalchemy.orm.session import Session
+
+
+def test_delete_database_blocked_by_soft_deleted_dataset(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Flask app context fixture</b></div>
   <div id="fix">
   
   Tests call `DeleteDatabaseCommand.validate()` which imports `db` from `superset.extensions` and performs database operations requiring a Flask app context. Add `app_context: None` fixture parameter alongside `session: Session` to match the established pattern in similar tests (e.g., `test_soft_delete_mixin.py:94`).
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/tests/unit_tests/databases/commands/delete_test.py
    +++ b/tests/unit_tests/databases/commands/delete_test.py
    @@ -22,7 +22,7 @@ from sqlalchemy.orm.session import Session
    
    
     def test_delete_database_blocked_by_soft_deleted_dataset(
    -    mocker: MockerFixture,
    +    app_context: None,
    +    mocker: MockerFixture,
         session: Session,
     ) -> None:
         """A database whose only datasets are soft-deleted must NOT be deletable.
    @@ -64,7 +64,8 @@ def test_delete_database_blocked_by_soft_deleted_dataset(
    
    
     def test_delete_database_allowed_when_no_datasets(
    -    mocker: MockerFixture,
    +    app_context: None,
    +    mocker: MockerFixture,
         session: Session,
     ) -> None:
         """With no datasets at all (soft-deleted or active), validation passes."""
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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:
##########
@@ -4688,6 +4688,9 @@ msgstr "El conjunt de dades no s'ha pogut crear."
 msgid "Dataset could not be duplicated."
 msgstr "El conjunt de dades no s'ha pogut duplicar."
 
+msgid "Dataset could not be restored."
+msgstr ""
+
 msgid "Dataset could not be updated."

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Catalan translation</b></div>
   <div id="fix">
   
   Empty translation string for user-facing error "Dataset could not be restored." will display untranslated English text to Catalan users. The error originates from `_("Dataset could not be restored.")` in `exceptions.py`. Fill in the Catalan translation following the established pattern (e.g., "El conjunt de dades no s'ha pogut [verb].").
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
   msgstr "El conjunt de dades no s'ha pogut restaurar."
    
   msgid "Dataset could not be updated."
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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/uk/LC_MESSAGES/messages.po:
##########
@@ -4574,6 +4574,9 @@ msgstr "Не вдалося створити набір даних."
 msgid "Dataset could not be duplicated."
 msgstr "Не вдалося дублювати набір даних."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Ukrainian translation</b></div>
   <div id="fix">
   
   The `msgstr` for "Dataset could not be restored." is empty (`msgstr ""`). Ukrainian users will see the untranslated English error message when dataset restore operations fail. Add the Ukrainian translation to match the pattern of other dataset error messages in this file (e.g., "Не вдалося оновити набір даних." on line 4581).
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/uk/LC_MESSAGES/messages.po (lines 4577-4578) ---
    4577: msgid "Dataset could not be restored."
    4578:-msgstr ""
    4578:+msgstr "Не вдалося відновити набір даних."
    4579:
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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:
##########
@@ -4822,6 +4822,9 @@ msgstr "Não foi possível criar o conjunto de dados."
 msgid "Dataset could not be duplicated."
 msgstr "Não foi possível duplicar o conjunto de dados."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing translation string</b></div>
   <div id="fix">
   
   The `msgstr` is empty for the new translation entry "Dataset could not be restored.". Portuguese (Brazilian) users will see untranslated English text when this error is displayed. Following the established pattern in this file (e.g., "Dataset could not be duplicated." → "Não foi possível duplicar o conjunto de dados."), the translation should be "Não foi possível restaurar o conjunto de dados.".
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/pt_BR/LC_MESSAGES/messages.po
    +++ superset/translations/pt_BR/LC_MESSAGES/messages.po
    @@ -4823,7 +4823,7 @@ msgstr "Não foi possível duplicar o conjunto de dados."
    
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "Não foi possível restaurar o conjunto de dados."
    
     msgid "Dataset could not be updated."
     msgstr "Não foi possível atualizar o conjunto de dados."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +37,29 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete.
+    #
+    # Match rows whose catalog is either unset (NULL) or the database
+    # default — these are "the same physical table" the way
+    # ``DatasetDAO.validate_uniqueness`` treats them (``table.catalog or
+    # default``). Example rows are seeded with ``catalog = NULL`` while a
+    # connection that reports a default catalog (e.g. Postgres) would
+    # normalize to that default, so both must qualify. This still excludes
+    # an unrelated third catalog variant of the same table_name. Within the
+    # matched set, prefer live rows over soft-deleted ones via
+    # ``ORDER BY deleted_at IS NULL DESC``.
+    catalog = database.get_default_catalog()
     return (
         db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
         .filter_by(database_id=database.id, schema=schema, table_name=table_name)
-        .one_or_none()
+        .filter(or_(SqlaTable.catalog.is_(None), SqlaTable.catalog == catalog))

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Duplicate catalog matching logic</b></div>
   <div id="fix">
   
   The inline `or_(SqlaTable.catalog.is_(None), SqlaTable.catalog == catalog)` logic duplicates `DatasetDAO._catalog_identity_filter` (lines 159-182 in `superset/daos/dataset.py`). The duplicate creates divergence risk if one copy is updated without the other — they must stay in sync to correctly treat NULL and default-catalog tables as the same physical table.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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:
##########
@@ -4603,6 +4603,9 @@ msgstr "Datu kopu nevarēja izveidot."
 msgid "Dataset could not be duplicated."
 msgstr "Datu kopu nevarēja dublēt."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing translation for new msgid</b></div>
   <div id="fix">
   
   The new message `msgid "Dataset could not be restored."` has an empty `msgstr` on line 4607. Users whose locale is set to Latvian will see the untranslated English text. Compare with adjacent messages: line 4604 uses "Datu kopu nevarēja dublēt" and line 4610 uses "Datu kopu nevarēja atjaunināt" — the infinitive form "atjaunot" (from existing translation at line 10797: "Atjaunot filtru") is the correct verb for "restore".
   </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 (lines 4606-4608) ---
    4606: msgid "Dataset could not be restored."
    4607:-msgstr ""
    4607:+msgstr "Datu kopu nevarēja atjaunot."
    4608: 
    4609: msgid "Dataset could not be updated."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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:
##########
@@ -4833,6 +4833,9 @@ msgstr "Nie udało się utworzyć zestawu danych."
 msgid "Dataset could not be duplicated."
 msgstr "Nie udało się zduplikować zestawu danych."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Polish translation</b></div>
   <div id="fix">
   
   Empty `msgstr` leaves Polish users with untranslated error message. Use the consistent pattern from neighboring entries: "Nie udało się [verb] zestawu danych."
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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:
##########
@@ -4664,6 +4664,9 @@ msgstr "Sadu dat se nepodařilo vytvořit."
 msgid "Dataset could not be duplicated."
 msgstr "Sadu dat se nepodařilo duplikovat."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Czech translation</b></div>
   <div id="fix">
   
   The `msgstr` is empty for the new translation entry. Czech users will see the untranslated English message "Dataset could not be restored." instead of a proper translation. Provide the Czech equivalent following the established pattern in this file.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/translations/cs/LC_MESSAGES/messages.po
    +++ b/superset/translations/cs/LC_MESSAGES/messages.po
    @@ -4665,7 +4665,7 @@ msgstr "Sadu dat se nepodařilo duplikovat."
    
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "Sadu dat se nepodařilo obnovit."
    
     msgid "Dataset could not be updated."
     msgstr "Sadu dat se nepodařilo aktualizovat."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a2a80b</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(datasets): soft-delete and restore [superset]

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

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

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

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

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

   1. There are still a TON of bot comments that haven't been resolved (also, there are SO many commits... maybe squashing this will make it more possible to read the gigantic github thread, which you currently have to expand a whole bunch of times to even see everything)
   2. I think you'll want to rebase onto post-#41166 master so CI runs against the gated path?
   3. Two validation changes ship even with SOFT_DELETE offL catalog-NULL-aware uniqueness matching, and duplicate.py's scope change. Please confirm they're meant to be un-gated.
   4. Any DB that has ever had datasets can't be deleted via API once they're soft-deleted (no purge in v1). Sounds like that's intended but just triple checking. 
   5. _escape_like change might be unrelated scope creep? Not a blocker, just noting it in case it's worth splitting out or whatever.


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

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

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

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

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

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


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

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


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -140,21 +141,93 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   Fixed in 1ee9bbdc1a — moved `find_existing_for_import` to module-top imports. Verified no cycle: `superset.commands.importers.v1.utils` does not reach `superset.commands.dataset.importers.v1.utils` via any import chain.



##########
superset/commands/dataset/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 dataset."""
+
+import logging
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+logger = logging.getLogger(__name__)
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    All transactional wrapping and validation lives in
+    ``BaseRestoreCommand``; this subclass is purely declarative.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError

Review Comment:
   Headline functional fix in 0591115434 — `RestoreDatasetCommand.validate()` now overrides the base with an `_has_active_logical_duplicate(model)` check that raises a new `DatasetLogicalDuplicateError` (HTTP 422) when another active dataset references the same `(database_id, catalog, schema, table_name)`. Defense-in-depth: `DatasetDAO.validate_uniqueness` and `validate_update_uniqueness` also bypass the visibility filter so a soft-deleted twin blocks creates from the API side. Importer (`importers/v1/utils.py`) has the same check before clearing `deleted_at`. `build_dataset_query` Core-select gap also closed with explicit `ds_table.c.deleted_at.is_(None)`. Integration tests at `tests/integration_tests/datasets/soft_delete_tests.py:200-289` cover restore-blocked and create-blocked flows. Richard flagged the same shape independently — both findings driving the same fix.



##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,10 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(CommandException):
+    message = _("Dataset could not be restored.")

Review Comment:
   Fixed in 0591115434 — `DatasetRestoreFailedError` now inherits `UpdateFailedError` (restore semantically clears `deleted_at`, so it's an UPDATE). Inline comment cross-references the cross-entity follow-up: a dedicated `RestoreFailedError` in already-merged `superset/commands/exceptions.py` would be more precise across the three entity rollouts but lives in #39977. Charts (`ChartRestoreFailedError`) and dashboards (`DashboardRestoreFailedError`) got the same normalization in companion commits 48efb0b0de and ab41d0c84c.



##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,331 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+

Review Comment:
   Fixed in 18399ce910 — added post-exception assertions that `existing.deleted_at` is still set after `pytest.raises(ImportFailedError)`. A regression that cleared `deleted_at` before raising would silently pass the message check alone; this pins the no-mutation-before-raise contract.



##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,331 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+
+
+def test_import_soft_deleted_dataset_raises_when_caller_lacks_can_write(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Case B: re-import of a soft-deleted UUID by a caller without
+    can_write must raise, not silently return the soft-deleted row.
+
+    Real-world scenario: a user has can_write Dashboard but not
+    can_write Dataset, and they import a dashboard zip that references
+    a soft-deleted dataset. Silently returning the row would let the
+    dashboard importer wire the dashboard's charts to a deleted dataset
+    and produce broken chart loads.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=False)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    # Seed a soft-deleted dataset with the matching UUID directly, so the
+    # test doesn't need to flip permissions mid-test.
+    existing = SqlaTable(
+        table_name="soft_deleted_dataset",
+        database_id=database.id,
+        uuid=config["uuid"],
+        deleted_at=datetime(2026, 1, 1, 12, 0, 0),
+    )
+    db.session.add(existing)
+    db.session.flush()
+
+    with pytest.raises(ImportFailedError) as excinfo:
+        import_dataset(config, overwrite=False)
+    assert "can_write" in str(excinfo.value)
+

Review Comment:
   Same fix as above in 18399ce910 — Case B test now pins that `existing.deleted_at` is unchanged when the can_write check fires. Uses `db.session.refresh(existing)` to defeat any in-session caching that might mask a regression.



##########
tests/unit_tests/commands/dataset/restore_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.
+"""Unit tests for RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1)
+    dataset.id = 1
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id", return_value=dataset
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreDatasetCommand("1")
+        cmd.run()

Review Comment:
   Fixed in 18399ce910 — `restore_test.py` rewritten with realistic UUIDs: `_DATASET_UUID = str(uuid.uuid4())` at module top, used at every `RestoreDatasetCommand(...)` call site. Documents the expected argument type even though the DAO is mocked.



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -152,8 +151,11 @@ def insert_database(self, name: str, allow_multi_catalog: bool = False) -> Datab
         return db_connection
 
     def get_fixture_datasets(self) -> list[SqlaTable]:
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES

Review Comment:
   Fixed in 18399ce910 — `SKIP_VISIBILITY_FILTER_CLASSES` moved to the module-level import block. All three inline import sites in `api_tests.py` (`get_fixture_datasets`, `create_datasets` teardown, `test_delete_dataset_item`) now use the top-level import.



##########
superset/datasets/api.py:
##########
@@ -706,8 +717,9 @@ def refresh(self, pk: int) -> Response:
     @safe
     @statsd_metrics
     @event_logger.log_this_with_context(

Review Comment:
   Reverted in 18399ce910 — all four cosmetic lambda reformats backed out (`detect_datetime_formats`, `related_objects`, `get_or_create_dataset`, `get_drill_info`). Only the genuinely-new `restore` lambda remains in the diff vs master. Diff hygiene point well taken.



##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   Declining — `2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py` follows Alembic's date-prefixed file naming convention; the hyphens in the date prefix are standard and won't cause import issues (alembic loads migrations by revision id, not module name).



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

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

   Thanks @aminghadersohi for the re-review and confirming all prior findings closed.
   
   One follow-up pushed in ea13ca7378:
   
   **Migration `down_revision` update**: updated `3a8e6f2c1b95`'s `down_revision` from `33d7e0e21daa` to `a1b2c3d4e5f6` (the current alembic head). Without this, `alembic upgrade head` would fail with "Multiple head revisions present" once the migration lands on a database that already has master's chain. The sibling charts (#40129) and dashboards (#40128) 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).


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

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


##########
superset/datasets/api.py:
##########
@@ -706,8 +717,9 @@ def refresh(self, pk: int) -> Response:
     @safe
     @statsd_metrics
     @event_logger.log_this_with_context(

Review Comment:
   **NIT — Unrelated cosmetic lambda reformats mixed into the functional diff**
   
   The `detect_datetime_formats` action lambda was reformatted from implicit string concatenation to parenthesized form here. The same cosmetic change was applied to `related_objects` (~line 802), `get_or_create_dataset` (~line 1116), and `get_drill_info` (~line 1338). None of these touch soft-delete logic. They add diff noise and make the functional changes harder to audit during review. Please move to a separate cleanup commit.



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

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

   Closing the batch of bito **empty-`msgstr`** findings on the new *"Dataset 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 — not hand-authored in a feature PR. These entries were deliberately seeded empty (see the `i18n(datasets): 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(datasets): soft-delete and restore [superset]

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

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

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3492945333


##########
tests/integration_tests/security_tests.py:
##########
@@ -560,6 +560,72 @@ def test_after_update_database__perm_datasource_access(self):
         db.session.delete(tmp_db1)
         db.session.commit()
 
+    def test_after_update_database__perm_datasource_access_soft_deleted(self):
+        """A soft-deleted dataset's perm strings must still be rewritten on a
+        database rename. The maintenance query bypasses the soft-delete
+        visibility filter so hidden datasets are updated too; otherwise
+        restoring the dataset later would resurrect stale dataset/schema/catalog
+        permission strings pointing at the old database name.
+        """
+        from datetime import datetime  # noqa: PLC0415
+
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES  # noqa: PLC0415
+
+        security_manager.on_view_menu_after_update = Mock()
+
+        tmp_db1 = Database(database_name="tmp_db1", sqlalchemy_uri="sqlite://")
+        db.session.add(tmp_db1)
+        db.session.commit()
+
+        table1 = SqlaTable(
+            schema="tmp_schema",
+            table_name="tmp_table1",
+            database=tmp_db1,
+        )
+        db.session.add(table1)
+        db.session.commit()
+        table1 = db.session.query(SqlaTable).filter_by(table_name="tmp_table1").one()
+        table1_id = table1.id

Review Comment:
   **Suggestion:** Add a concrete type annotation for this new scalar variable assignment 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 added scalar local variable whose type is readily annotatable as an int. The custom rule requires type hints on relevant variables that can be annotated, so this omission 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=048d5a9ee1964f28bc1664f7da7df6b4&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=048d5a9ee1964f28bc1664f7da7df6b4&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/security_tests.py
   **Line:** 588:588
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for this new scalar variable assignment 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%2F40130&comment_hash=78a19dbb5ed4076660260e8000b7b5711b90620eaa7d4a79770adb05f12be0f1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=78a19dbb5ed4076660260e8000b7b5711b90620eaa7d4a79770adb05f12be0f1&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())

Review Comment:
   **Suggestion:** Add explicit type annotations for the module-level UUID constants to satisfy the type-hint requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   These module-level constants are newly introduced Python variables that can be annotated with `str`; they currently omit type hints, so this matches the requirement to flag relevant variables missing annotations.
   </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=61ff63e163754317b4c0c5f66b043741&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=61ff63e163754317b4c0c5f66b043741&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/dataset/restore_test.py
   **Line:** 30:31
   **Comment:**
   	*Custom Rule: Add explicit type annotations for the module-level UUID constants 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%2F40130&comment_hash=8ef6fcd61873c34abb80a45a9cbd66d08e3e920c21e850c029918a47a809d713&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=8ef6fcd61873c34abb80a45a9cbd66d08e3e920c21e850c029918a47a809d713&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/test_duplicate.py:
##########
@@ -101,3 +102,66 @@ def test_duplicate_dataset_access_check_passes_through() -> None:
                     command.validate()  # should not raise
                     # Confirm access check was called with the base dataset
                     mock_access.assert_called_once_with(datasource=mock_dataset)
+
+
+def test_duplicate_dataset_blocked_by_soft_deleted_twin(session: Session) -> None:
+    """validate() rejects a duplicate whose name matches a soft-deleted
+    dataset at the same (database, schema).
+
+    The previous name-only ``find_one_or_none`` lookup ran through the
+    soft-delete visibility filter, so a soft-deleted twin was invisible and
+    the duplicate proceeded — hitting whichever DB constraint applies as an
+    opaque IntegrityError, or creating an active twin that permanently
+    blocks restore where none does. The shared ``validate_uniqueness``
+    check bypasses the filter and refuses with a clean validation error.
+    """
+    from datetime import datetime, timezone
+
+    from superset import db
+    from superset.commands.dataset.duplicate import DuplicateDatasetCommand
+    from superset.commands.dataset.exceptions import DatasetInvalidError
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.models.core import Database
+
+    SqlaTable.metadata.create_all(session.get_bind())
+
+    database = Database(database_name="dup_db", sqlalchemy_uri="sqlite://")
+    base = SqlaTable(
+        table_name="base_view",
+        schema="main",
+        database=database,
+        sql="select 1",
+    )
+    hidden_twin = SqlaTable(
+        table_name="dup_name",
+        schema="main",
+        database=database,
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )

Review Comment:
   **Suggestion:** Add explicit type annotations for newly introduced local variables in this test to comply with the type-hint requirement. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The added test code introduces new local variables (`database`, `base`, and `hidden_twin`) without type annotations, and they are clearly annotatable. This matches the rule requiring type hints on new or modified Python code where applicable.
   </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=4dda67b7380046a383ab40d4a411c5a7&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=4dda67b7380046a383ab40d4a411c5a7&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/dataset/test_duplicate.py
   **Line:** 128:140
   **Comment:**
   	*Custom Rule: Add explicit type annotations for newly introduced local variables in this test to comply 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%2F40130&comment_hash=84b86188137cbafca873351bd52e31f6201de713e0ae3745796f3b0b3d035138&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=84b86188137cbafca873351bd52e31f6201de713e0ae3745796f3b0b3d035138&reaction=dislike'>👎</a>



##########
superset/commands/database/delete.py:
##########
@@ -61,6 +61,28 @@ def validate(self) -> None:
                     report_names=",".join(report_names),
                 )
             )
-        # Check if there are datasets for this database
-        if self._model.tables:
+        # Check if there are datasets for this database. ``self._model.tables``
+        # would now hide soft-deleted datasets (``SqlaTable`` inherits
+        # ``SoftDeleteMixin``, so the relationship lazy-load applies the
+        # visibility filter), letting a database whose datasets are all
+        # soft-deleted look empty and be hard-deleted while ``tables.database_id``
+        # rows still reference it. Count with the visibility filter bypassed so
+        # soft-deleted datasets still block the delete.
+        from superset.connectors.sqla.models import (  # pylint: disable=import-outside-toplevel
+            SqlaTable,
+        )
+        from superset.extensions import (  # pylint: disable=import-outside-toplevel
+            db,
+        )
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
+        )
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            has_datasets = db.session.query(
+                db.session.query(SqlaTable.id)
+                .filter(SqlaTable.database_id == self._model_id)
+                .exists()
+            ).scalar()

Review Comment:
   **Suggestion:** Add an explicit boolean type annotation for this newly introduced variable to satisfy the type-hint requirement for relevant annotatable variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new local variable `has_datasets` is introduced without a type hint. Since this is new Python code and the value is clearly a boolean-like result from `.scalar()`, it fits the custom rule requiring type hints on 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=56c1ae644fd547268aba5f90638cf8ff&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=56c1ae644fd547268aba5f90638cf8ff&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/database/delete.py
   **Line:** 81:86
   **Comment:**
   	*Custom Rule: Add an explicit boolean type annotation for this newly introduced variable to satisfy 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%2F40130&comment_hash=09b622dd25b3fe6bb32250912d9545c492bbef68dd0112ba2c98206046403dec&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=09b622dd25b3fe6bb32250912d9545c492bbef68dd0112ba2c98206046403dec&reaction=dislike'>👎</a>



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False

Review Comment:
   **Suggestion:** Add an explicit boolean type annotation for this newly introduced state flag 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 local state flag in Python that can clearly be annotated as a bool. The custom rule requires type hints on relevant variables that can be annotated, so omitting the annotation 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=cb6992b280164e8d85b2642b5b01cc9b&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=cb6992b280164e8d85b2642b5b01cc9b&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/dataset/importers/v1/utils.py
   **Line:** 248:248
   **Comment:**
   	*Custom Rule: Add an explicit boolean type annotation for this newly introduced state flag 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%2F40130&comment_hash=efdd3e8ee1ea3c45b464df91f504e686c3ee9c1f13faafa3d1d2eaef6af4fa5d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=efdd3e8ee1ea3c45b464df91f504e686c3ee9c1f13faafa3d1d2eaef6af4fa5d&reaction=dislike'>👎</a>



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, config["uuid"]):
+        if existing.deleted_at is not None:
+            # RESTORE path — re-importing a soft-deleted UUID is an implicit
+            # restore-with-update, a distinct operation from overwriting an
+            # alive row, so it is handled in its own branch.
+            if not can_write:
+                # Case B: don't silently return a soft-deleted row to a caller
+                # without write permission — that would let the importer
+                # reattach charts/dashboards to a deleted dataset and produce
+                # broken charts.
+                raise ImportFailedError(
+                    "Dataset was deleted and re-import requires can_write "
+                    "permission to restore it"
+                )
+            # ``user`` is None on background / example-loader paths; combined
+            # with ``can_write`` (typically from ``ignore_permissions=True``)
+            # the ownership check is intentionally skipped because the caller
+            # already established trust.
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
                 raise ImportFailedError(
-                    "A dataset already exists and user doesn't "
-                    "have permissions to overwrite it"
+                    "A dataset already exists and user doesn't have "
+                    "permissions to restore it"
                 )
-        if not overwrite or not can_write:
-            return existing
-        config["id"] = existing.id
+            # Before clearing ``deleted_at``, refuse if another active dataset
+            # already references the same physical table. Otherwise the
+            # restore would produce two live ``SqlaTable`` rows for one
+            # physical table, breaking the logical-uniqueness contract. The
+            # shared DAO helper relies on the SoftDeleteMixin listener to
+            # consider only active rows, excludes ``existing`` itself via
+            # ``id !=``, and normalizes the catalog the same way create/update
+            # uniqueness does.
+            if DatasetDAO.has_active_logical_duplicate(existing):
+                raise ImportFailedError(
+                    "Dataset cannot be restored via re-import because another "
+                    "active dataset already references the same physical table"
+                )
+            # Restore in place (clear ``deleted_at``) rather than
+            # hard-delete-and-replace: a hard delete would cascade through the
+            # chart back-reference and the delete-orphan child relationships
+            # (table_columns, sql_metrics), which the import would then need to
+            # reconstruct.
+            #
+            # How the restore lands as an UPDATE: clearing
+            # ``existing.deleted_at`` marks the in-session row dirty and the
+            # explicit flush emits the ``deleted_at = NULL`` UPDATE before
+            # ``SqlaTable.import_from_dict`` (below) does its own query-by-uuid
+            # lookup. Without the flush we would be relying on autoflush ahead
+            # of that internal query — correct under default session config but
+            # a hidden contract; the explicit flush makes it robust. The lookup
+            # then finds the now-live row (the listener filters ``deleted_at IS
+            # NULL``) and ``import_from_dict`` applies the config as field
+            # updates on the existing object, preserving the PK. Note:
+            # ``config["id"]`` is set defensively, but
+            # ``ImportExportMixin.import_from_dict`` strips it because
+            # ``SqlaTable.export_fields`` does not contain "id"; what actually
+            # binds to the existing row is the uuid uniqueness constraint used
+            # inside ``import_from_dict``.
+            #
+            # Snapshot ``deleted_at`` first so we can roll back the clear if the
+            # downstream ``import_from_dict`` hits the legacy
+            # ``MultipleResultsFound`` fallback. Without the rollback, an
+            # ambiguous import would leave the dataset half-restored
+            # (``deleted_at = None`` but upload contents unapplied).
+            original_deleted_at = existing.deleted_at
+            existing.restore()
+            db.session.flush()
+            is_soft_deleted_match = True
+            config["id"] = existing.id
+        else:
+            # OVERWRITE path — existing alive row. Without ``overwrite`` or
+            # write permission, return it unchanged (the pre-soft-delete
+            # overwrite-without-permission behaviour).
+            if not overwrite or not can_write:
+                return existing
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
+                raise ImportFailedError(
+                    "A dataset already exists and user doesn't have "
+                    "permissions to overwrite it"
+                )
+            config["id"] = existing.id
 
     elif not can_write:
         raise ImportFailedError(
             "Dataset doesn't exist and user doesn't have permission to create datasets"
         )
+    else:
+        # Creating a brand-new dataset (no UUID match). A soft-deleted dataset
+        # may still claim this physical table; ``import_from_dict`` cannot see it
+        # (the visibility filter hides soft-deleted rows), so without this guard
+        # the import would create an active twin of a hidden dataset. The REST
+        # create path blocks the same collision via ``validate_uniqueness`` —
+        # mirror it here and direct the user to restore the existing dataset
+        # instead of leaving two rows for one physical table.
+        database = (
+            db.session.query(Database).filter_by(id=config["database_id"]).first()
+        )

Review Comment:
   **Suggestion:** Add an explicit type annotation for this newly added query result variable to comply with the rule requiring type hints on relevant variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This new local lookup can be annotated as an optional Database reference. The custom rule specifically requires type hints on relevant variables that can be annotated, so this omission 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=d8f7620201dc4bd9bfb60120501f598a&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=d8f7620201dc4bd9bfb60120501f598a&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/dataset/importers/v1/utils.py
   **Line:** 347:349
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this newly added query result variable to comply with the rule requiring type hints on 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%2F40130&comment_hash=bc11c4fdf777a4cfc044aa0e5b61bcae0a6bd5f294b8165e9c5575b0362ba930&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=bc11c4fdf777a4cfc044aa0e5b61bcae0a6bd5f294b8165e9c5575b0362ba930&reaction=dislike'>👎</a>



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO

Review Comment:
   **Suggestion:** Add an explicit class-variable type annotation for `dao` to satisfy the type-hint requirement for newly introduced variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly introduced class variable in Python and it is left unannotated. The custom rule requires type hints on relevant variables that can be annotated, so this omission 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=02e92168d879465e8dc52e97d3b3ec0c&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=02e92168d879465e8dc52e97d3b3ec0c&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/dataset/restore.py
   **Line:** 46:46
   **Comment:**
   	*Custom Rule: Add an explicit class-variable type annotation for `dao` to satisfy the type-hint requirement for 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%2F40130&comment_hash=fe1fc76a6e9bf3f73bd7bf479816001d4599184064d9d7b97a8678e92046e47b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=fe1fc76a6e9bf3f73bd7bf479816001d4599184064d9d7b97a8678e92046e47b&reaction=dislike'>👎</a>



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, config["uuid"]):
+        if existing.deleted_at is not None:
+            # RESTORE path — re-importing a soft-deleted UUID is an implicit
+            # restore-with-update, a distinct operation from overwriting an
+            # alive row, so it is handled in its own branch.
+            if not can_write:
+                # Case B: don't silently return a soft-deleted row to a caller
+                # without write permission — that would let the importer
+                # reattach charts/dashboards to a deleted dataset and produce
+                # broken charts.
+                raise ImportFailedError(
+                    "Dataset was deleted and re-import requires can_write "
+                    "permission to restore it"
+                )
+            # ``user`` is None on background / example-loader paths; combined
+            # with ``can_write`` (typically from ``ignore_permissions=True``)
+            # the ownership check is intentionally skipped because the caller
+            # already established trust.
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
                 raise ImportFailedError(
-                    "A dataset already exists and user doesn't "
-                    "have permissions to overwrite it"
+                    "A dataset already exists and user doesn't have "
+                    "permissions to restore it"
                 )
-        if not overwrite or not can_write:
-            return existing
-        config["id"] = existing.id
+            # Before clearing ``deleted_at``, refuse if another active dataset
+            # already references the same physical table. Otherwise the
+            # restore would produce two live ``SqlaTable`` rows for one
+            # physical table, breaking the logical-uniqueness contract. The
+            # shared DAO helper relies on the SoftDeleteMixin listener to
+            # consider only active rows, excludes ``existing`` itself via
+            # ``id !=``, and normalizes the catalog the same way create/update
+            # uniqueness does.
+            if DatasetDAO.has_active_logical_duplicate(existing):
+                raise ImportFailedError(
+                    "Dataset cannot be restored via re-import because another "
+                    "active dataset already references the same physical table"
+                )
+            # Restore in place (clear ``deleted_at``) rather than
+            # hard-delete-and-replace: a hard delete would cascade through the
+            # chart back-reference and the delete-orphan child relationships
+            # (table_columns, sql_metrics), which the import would then need to
+            # reconstruct.
+            #
+            # How the restore lands as an UPDATE: clearing
+            # ``existing.deleted_at`` marks the in-session row dirty and the
+            # explicit flush emits the ``deleted_at = NULL`` UPDATE before
+            # ``SqlaTable.import_from_dict`` (below) does its own query-by-uuid
+            # lookup. Without the flush we would be relying on autoflush ahead
+            # of that internal query — correct under default session config but
+            # a hidden contract; the explicit flush makes it robust. The lookup
+            # then finds the now-live row (the listener filters ``deleted_at IS
+            # NULL``) and ``import_from_dict`` applies the config as field
+            # updates on the existing object, preserving the PK. Note:
+            # ``config["id"]`` is set defensively, but
+            # ``ImportExportMixin.import_from_dict`` strips it because
+            # ``SqlaTable.export_fields`` does not contain "id"; what actually
+            # binds to the existing row is the uuid uniqueness constraint used
+            # inside ``import_from_dict``.
+            #
+            # Snapshot ``deleted_at`` first so we can roll back the clear if the
+            # downstream ``import_from_dict`` hits the legacy
+            # ``MultipleResultsFound`` fallback. Without the rollback, an
+            # ambiguous import would leave the dataset half-restored
+            # (``deleted_at = None`` but upload contents unapplied).
+            original_deleted_at = existing.deleted_at

Review Comment:
   **Suggestion:** Add a type annotation for this restored timestamp snapshot variable (for example an optional datetime type) so the new variable is explicitly typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This new local variable stores a deleted_at snapshot and can be annotated with an optional datetime type. Since the rule flags relevant variables that can be annotated, the lack of a type hint is a valid 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=82e7f24b9d9541b5aa2a025836fd0f5c&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=82e7f24b9d9541b5aa2a025836fd0f5c&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/dataset/importers/v1/utils.py
   **Line:** 315:315
   **Comment:**
   	*Custom Rule: Add a type annotation for this restored timestamp snapshot variable (for example an optional datetime type) so the new variable is explicitly 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%2F40130&comment_hash=c1f2d59fe30b82a9e20051e7e9864c026f6be72843633bf9ee044625b1819427&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=c1f2d59fe30b82a9e20051e7e9864c026f6be72843633bf9ee044625b1819427&reaction=dislike'>👎</a>



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError

Review Comment:
   **Suggestion:** Add an explicit class-variable type annotation for `restore_failed_exc` rather than relying on implicit typing. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is an untyped class attribute in newly added Python code. It can be annotated, so it falls under the type-hint requirement.
   </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=4f3ad69e3b0c4b319269bc7a410e74cc&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=4f3ad69e3b0c4b319269bc7a410e74cc&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/dataset/restore.py
   **Line:** 49:49
   **Comment:**
   	*Custom Rule: Add an explicit class-variable type annotation for `restore_failed_exc` rather than relying on implicit typing.
   
   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%2F40130&comment_hash=1fd5a338b6e183b6870bfdd288f26907b77b29118d688f1ee5004f9692010b3c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=1fd5a338b6e183b6870bfdd288f26907b77b29118d688f1ee5004f9692010b3c&reaction=dislike'>👎</a>



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError
+
+    def validate(self) -> SqlaTable:  # type: ignore[override]
+        model = super().validate()

Review Comment:
   **Suggestion:** Add a local variable annotation for `model` when assigning the result of `super().validate()`. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This local variable is introduced in modified Python code and is a clear candidate for annotation. The custom rule requires type hints for relevant variables that can be annotated, 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=b377d405de464182af8b96834394cbd8&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=b377d405de464182af8b96834394cbd8&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/dataset/restore.py
   **Line:** 52:52
   **Comment:**
   	*Custom Rule: Add a local variable annotation for `model` when assigning the result of `super().validate()`.
   
   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%2F40130&comment_hash=d5800e51437c9cca6ea4c16816b2e302b218de8f0400cdc390b6538f0505c21f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=d5800e51437c9cca6ea4c16816b2e302b218de8f0400cdc390b6538f0505c21f&reaction=dislike'>👎</a>



##########
superset/daos/dataset.py:
##########
@@ -163,20 +188,45 @@ def validate_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.database_id == database.id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog

Review Comment:
   **Suggestion:** Add explicit type annotations for the newly introduced local variables that hold catalog normalization values in this method. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new code introduces local variables that hold catalog normalization values, and they are not type-annotated even though their types can be expressed. This matches the 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=bc52bd8212454c0eb2c3e44574f6ce3e&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=bc52bd8212454c0eb2c3e44574f6ce3e&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/dataset.py
   **Line:** 191:192
   **Comment:**
   	*Custom Rule: Add explicit type annotations for the newly introduced local variables that hold catalog normalization values in this method.
   
   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%2F40130&comment_hash=e6fee46c1bca5a837e28891afb27a12fa5e0653624bf297573902952217545c7&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=e6fee46c1bca5a837e28891afb27a12fa5e0653624bf297573902952217545c7&reaction=dislike'>👎</a>



##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog

Review Comment:
   **Suggestion:** Add explicit type annotations for the newly introduced local variables before building the soft-deleted duplicate query. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The code in the final file introduces local catalog-normalization variables without explicit type hints, which falls under the stated requirement to annotate relevant variables when possible.
   </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=dafa660c433a4c658dfdc151b5ad40a9&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=dafa660c433a4c658dfdc151b5ad40a9&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/dataset.py
   **Line:** 239:240
   **Comment:**
   	*Custom Rule: Add explicit type annotations for the newly introduced local variables before building the soft-deleted duplicate query.
   
   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%2F40130&comment_hash=f2e89b1d8319299fd28470b34e779e2e914b1f3d19fc1e8fa274ab2d742f7030&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=f2e89b1d8319299fd28470b34e779e2e914b1f3d19fc1e8fa274ab2d742f7030&reaction=dislike'>👎</a>



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    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 derived local value to satisfy the required variable type-hint rule. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is new Python code adding a derived local variable without any type annotation. The custom rule explicitly requires type hints for relevant variables that can be annotated, 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=0d0720a2f80d429fa6c5c64001f16939&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=0d0720a2f80d429fa6c5c64001f16939&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/datasets/filters.py
   **Line:** 83:83
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this derived local value to satisfy the required variable 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%2F40130&comment_hash=18c157936bcca6521b6e085155ef00ed915310e5569d1b76162df77f32cf3c5e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=18c157936bcca6521b6e085155ef00ed915310e5569d1b76162df77f32cf3c5e&reaction=dislike'>👎</a>



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    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 datasets they own. ``any()`` emits
+        # an EXISTS subquery so it composes with the base access filter without
+        # producing duplicate rows from a join.
+        owned = SqlaTable.owners.any(security_manager.user_model.id == get_user_id())

Review Comment:
   **Suggestion:** Add a concrete type annotation for this SQLAlchemy expression variable so newly added relevant variables are typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is also a newly introduced local variable in Python code and it lacks an explicit type hint. Since it is a relevant variable that can be annotated, it violates 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=35e68edda4bc45ff846dc38f1fc6e600&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=35e68edda4bc45ff846dc38f1fc6e600&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/datasets/filters.py
   **Line:** 90:90
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for this SQLAlchemy expression variable so newly added relevant variables are 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%2F40130&comment_hash=d92a34c7f282c962e9e17344e61d6ddd45b73d868fafb76da2161ffabf3c6596&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=d92a34c7f282c962e9e17344e61d6ddd45b73d868fafb76da2161ffabf3c6596&reaction=dislike'>👎</a>



##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog
+
+        # Same rationale as ``validate_uniqueness`` above: a soft-deleted
+        # twin must block the update rather than being silently ignored.
+        # The bypass is session-scoped, not per-query, because the EXISTS
+        # subquery pattern below leaves the inner Query's execution_options
+        # invisible to the outer execute (where the listener fires).
+        #
+        # avoid app-init regression: see ``validate_uniqueness`` above — a
+        # module-top import from ``superset.models.helpers`` raises
+        # "App not initialized yet" outside an app context (see PR #40573).
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
         )
-        return not db.session.query(dataset_query.exists()).scalar()
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            dataset_query = db.session.query(SqlaTable).filter(
+                SqlaTable.table_name == table.table,
+                SqlaTable.database_id == database.id,
+                SqlaTable.schema == table.schema,
+                DatasetDAO._catalog_identity_filter(catalog, default_catalog),
+                SqlaTable.id != dataset_id,
+            )
+            return not db.session.query(dataset_query.exists()).scalar()
+
+    @staticmethod
+    def has_active_logical_duplicate(model: SqlaTable) -> bool:
+        """Return True iff another *active* dataset shares model's physical table.
+
+        Physical identity is ``(database_id, catalog, schema, table_name)``.
+        ``model``'s catalog is normalized to the database default when unset —
+        the same rule ``validate_uniqueness``/``validate_update_uniqueness``
+        apply — so create, update, restore, and re-import agree on what counts
+        as the same physical table. Catalog matching is null-aware via
+        ``_catalog_identity_filter``: when the normalized catalog is the database
+        default, both ``catalog = default`` and ``catalog IS NULL`` rows match,
+        so a default-catalog twin is caught whichever way either row stored its
+        catalog.
+
+        Unlike ``validate_uniqueness``, this does NOT use
+        ``skip_visibility_filter``: it relies on the ``SoftDeleteMixin`` listener
+        to auto-append ``deleted_at IS NULL`` so only *active* rows match. Do not
+        add the bypass here — it would broaden the check to soft-deleted rows and
+        silently refuse legitimate restores. ``id != model.id`` excludes the row
+        itself.
+
+        Assumes an active app context and a session-attached ``model`` so
+        ``db.session`` and the lazy ``model.database`` relationship resolve.
+        """
+        # The catalog might not be set even if the database supports catalogs,
+        # in case multi-catalog is disabled.
+        default_catalog = model.database.get_default_catalog()
+        catalog = model.catalog or default_catalog

Review Comment:
   **Suggestion:** Type-annotate the newly added local variables in this duplicate-check method to comply with the rule on variable hints. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This duplicate-check helper introduces unannotated local variables for catalog normalization. Since the rule explicitly covers relevant variables in new or modified Python code, this is a verified 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=5ff7f8965cbe483fb8baf0ad7957eb26&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=5ff7f8965cbe483fb8baf0ad7957eb26&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/dataset.py
   **Line:** 291:292
   **Comment:**
   	*Custom Rule: Type-annotate the newly added local variables in this duplicate-check method to comply with the rule on variable hints.
   
   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%2F40130&comment_hash=f8e62317b4c40e9afbbd52b32a7b570eff97469b0d209f215a9afe8b8966f59c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=f8e62317b4c40e9afbbd52b32a7b570eff97469b0d209f215a9afe8b8966f59c&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3501609471


##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -1957,17 +1974,32 @@ def test_delete_dataset_item(self):
         """
 
         dataset = self.insert_default_dataset()
+        dataset_id = dataset.id

Review Comment:
   **Suggestion:** Add an explicit scalar type annotation for this newly added identifier variable. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This added scalar local is an integer identifier and can be annotated directly. The custom type-hint rule applies to relevant variables, so the missing annotation is a real issue.
   </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=bba73fa5f85048c198eff15cf41a13a9&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=bba73fa5f85048c198eff15cf41a13a9&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/datasets/api_tests.py
   **Line:** 1977:1977
   **Comment:**
   	*Custom Rule: Add an explicit scalar type annotation for this newly added identifier 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%2F40130&comment_hash=0a5749030c9622e1c8cad93eb2e3eb8e6af2aac2d92057867e179b2e7463c74d&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=0a5749030c9622e1c8cad93eb2e3eb8e6af2aac2d92057867e179b2e7463c74d&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()

Review Comment:
   **Suggestion:** Add an explicit type annotation for this newly introduced local variable to satisfy the type-hint requirement. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is newly added Python code and the local variable is inferable as a list of SqlaTable objects, so it can be type-annotated. The custom rule requires type hints on relevant variables that can be annotated, 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=5612cb3b57dc4d15b7dc81375df29cf9&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=5612cb3b57dc4d15b7dc81375df29cf9&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/datasets/api_tests.py
   **Line:** 197:197
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this newly introduced local 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%2F40130&comment_hash=9e62b1025ed6f7dfa07f7408fde9cd489229df3f650a6fa095f7afd7bfc1a949&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=9e62b1025ed6f7dfa07f7408fde9cd489229df3f650a6fa095f7afd7bfc1a949&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/test_duplicate.py:
##########
@@ -101,3 +102,66 @@ def test_duplicate_dataset_access_check_passes_through() -> None:
                     command.validate()  # should not raise
                     # Confirm access check was called with the base dataset
                     mock_access.assert_called_once_with(datasource=mock_dataset)
+
+
+def test_duplicate_dataset_blocked_by_soft_deleted_twin(session: Session) -> None:
+    """validate() rejects a duplicate whose name matches a soft-deleted
+    dataset at the same (database, schema).
+
+    The previous name-only ``find_one_or_none`` lookup ran through the
+    soft-delete visibility filter, so a soft-deleted twin was invisible and
+    the duplicate proceeded — hitting whichever DB constraint applies as an
+    opaque IntegrityError, or creating an active twin that permanently
+    blocks restore where none does. The shared ``validate_uniqueness``
+    check bypasses the filter and refuses with a clean validation error.
+    """
+    from datetime import datetime, timezone
+
+    from superset import db
+    from superset.commands.dataset.duplicate import DuplicateDatasetCommand
+    from superset.commands.dataset.exceptions import DatasetInvalidError
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.models.core import Database
+
+    SqlaTable.metadata.create_all(session.get_bind())
+
+    database = Database(database_name="dup_db", sqlalchemy_uri="sqlite://")
+    base = SqlaTable(
+        table_name="base_view",
+        schema="main",
+        database=database,
+        sql="select 1",
+    )
+    hidden_twin = SqlaTable(
+        table_name="dup_name",
+        schema="main",
+        database=database,
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )
+    db.session.add_all([database, base, hidden_twin])
+    db.session.flush()
+
+    with (
+        # find_by_id applies the security base filter, which needs a request
+        # user; return the seeded row directly. validate_uniqueness — the
+        # behaviour under test — runs for real against the session.
+        patch(
+            "superset.commands.dataset.duplicate.DatasetDAO.find_by_id",
+            return_value=base,
+        ),
+        patch("superset.commands.dataset.duplicate.security_manager.raise_for_access"),
+        patch(
+            "superset.commands.dataset.duplicate."
+            "DuplicateDatasetCommand.populate_owners",
+            return_value=[],
+        ),
+    ):
+        command = DuplicateDatasetCommand(
+            {
+                "base_model_id": base.id,
+                "table_name": "dup_name",
+                "is_managed_externally": False,
+            }
+        )

Review Comment:
   **Suggestion:** Add an explicit type annotation for this newly introduced command variable. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new command variable is a relevant local variable in Python code and it does not include an explicit type hint.
   </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=4b8ad907bf01474191e2ca9399d22afb&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=4b8ad907bf01474191e2ca9399d22afb&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/dataset/test_duplicate.py
   **Line:** 159:165
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this newly introduced command 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%2F40130&comment_hash=42e6cb3045a57af6d90724b5ca9ff67063e0cd383eb9a5d154d6e085e11e57e3&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=42e6cb3045a57af6d90724b5ca9ff67063e0cd383eb9a5d154d6e085e11e57e3&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]

Review Comment:
   **Suggestion:** Add a concrete list type annotation for this new variable so its element type is explicit. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This newly added local list is clearly typed as a list of integers, so a concrete annotation is possible. Because the rule flags omitted type hints on relevant variables, this is a verified 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=62002cd46d8e43748df8aa31ffe2c819&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=62002cd46d8e43748df8aa31ffe2c819&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/datasets/api_tests.py
   **Line:** 210:210
   **Comment:**
   	*Custom Rule: Add a concrete list type annotation for this new variable so its element type is explicit.
   
   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%2F40130&comment_hash=522847e630c94b0b65c17646bb2dce6cd994c1aa611385a52c9148c31e643e68&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=522847e630c94b0b65c17646bb2dce6cd994c1aa611385a52c9148c31e643e68&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)

Review Comment:
   **Suggestion:** Provide a type annotation for this mock variable declaration to comply with the rule requiring hints on relevant annotatable variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This local variable is newly introduced and is annotatable, but it has no type hint. That fits the custom 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=802c0e5e77e8422089a63dca1cdbd76d&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=802c0e5e77e8422089a63dca1cdbd76d&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/dataset/restore_test.py
   **Line:** 39:39
   **Comment:**
   	*Custom Rule: Provide a type annotation for this mock variable declaration to comply with the rule requiring hints on 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%2F40130&comment_hash=5833126bd57ffd925e56e9c7c97ac1f65040e7046d19b4df14b3e8684f505e3b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=5833126bd57ffd925e56e9c7c97ac1f65040e7046d19b4df14b3e8684f505e3b&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -1957,17 +1974,32 @@ def test_delete_dataset_item(self):
         """
 
         dataset = self.insert_default_dataset()
+        dataset_id = dataset.id
         view_menu = security_manager.find_view_menu(dataset.get_perm())
         assert view_menu is not None
         view_menu_id = view_menu.id
         self.login(ADMIN_USERNAME)
         uri = f"api/v1/dataset/{dataset.id}"
         rv = self.client.delete(uri)
         assert rv.status_code == 200
+        # With soft delete, the row still exists (with deleted_at set) so
+        # FAB permissions are preserved for potential restore.
         non_view_menu = db.session.query(security_manager.viewmenu_model).get(
             view_menu_id
         )
-        assert non_view_menu is None
+        assert non_view_menu is not None
+
+        # Hard-delete the soft-deleted row to avoid unique constraint
+        # collisions in subsequent tests
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )

Review Comment:
   **Suggestion:** Annotate this new query result variable with an optional model type to comply with type-hinting requirements. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is newly added Python code and the query result is an optional SqlaTable value, which can be annotated. Since the rule requires type hints for relevant variables that can be annotated, this omission is verified.
   </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=7b7eb039191c471dbf466dcda157a61b&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=7b7eb039191c471dbf466dcda157a61b&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/datasets/api_tests.py
   **Line:** 1994:1999
   **Comment:**
   	*Custom Rule: Annotate this new query result variable with an optional model type to comply with type-hinting requirements.
   
   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%2F40130&comment_hash=64e03b003b3ad9f8b79ded6b82e610dca843a81bb7d16711f065423b9025550e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=64e03b003b3ad9f8b79ded6b82e610dca843a81bb7d16711f065423b9025550e&reaction=dislike'>👎</a>



##########
superset/commands/database/exceptions.py:
##########
@@ -156,6 +156,18 @@ class DatabaseDeleteDatasetsExistFailedError(DeleteFailedError):
     message = _("Cannot delete a database that has datasets attached")
 
 
+class DatabaseDeleteSoftDeletedDatasetsExistFailedError(
+    DatabaseDeleteDatasetsExistFailedError
+):
+    # Subclasses the live-datasets error so the existing API handler catches
+    # both; only the message differs, telling the operator that the blockers
+    # are hidden (soft-deleted) rows even though their dataset list looks empty.
+    message = _(
+        "Cannot delete a database whose only remaining datasets are "
+        "soft-deleted. Restore or permanently purge them first."
+    )

Review Comment:
   **Suggestion:** Add an explicit type annotation to the new class-level message attribute. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new class-level `message` attribute is a relevant variable that can be annotated, and it is introduced without a type hint. This matches the Python type-hinting rule for newly added 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=b5dfafd712494dfdbf0f5bcf89d7ea10&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=b5dfafd712494dfdbf0f5bcf89d7ea10&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/database/exceptions.py
   **Line:** 165:168
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to the new class-level message attribute.
   
   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%2F40130&comment_hash=f5b292e538e5f92d4d9aa291bbbf108de83331e0b167f03ca28c811b67da8850&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=f5b292e538e5f92d4d9aa291bbbf108de83331e0b167f03ca28c811b67da8850&reaction=dislike'>👎</a>



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"

Review Comment:
   **Suggestion:** Add an explicit type annotation for this class-level attribute to satisfy the type-hint requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The custom rule requires type hints for relevant variables that can be annotated. This class-level string attribute is newly introduced and could be annotated as a class variable, but it is left untyped, so the suggestion 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=e246e1ebee174b6781bb4ddc158ac94e&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=e246e1ebee174b6781bb4ddc158ac94e&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/datasets/filters.py
   **Line:** 78:78
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this class-level attribute 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%2F40130&comment_hash=2d2c68c8403992d9d3b9ed510bdd5412b29c01cd620c4f8e7b358f5f61b45f23&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=2d2c68c8403992d9d3b9ed510bdd5412b29c01cd620c4f8e7b358f5f61b45f23&reaction=dislike'>👎</a>



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable

Review Comment:
   **Suggestion:** Add a concrete type annotation for this class-level model reference instead of leaving it unannotated. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added class attribute whose type is clear and annotatable, but it is left untyped. That matches the type-hint requirement for relevant variables, so the suggestion is verified.
   </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=0ebf35766ace4f5089bca84240db27b5&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=0ebf35766ace4f5089bca84240db27b5&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/datasets/filters.py
   **Line:** 79:79
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for this class-level model reference instead of leaving it unannotated.
   
   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%2F40130&comment_hash=5462481758bb5af4ad348427716a6378f05c8a619b9447785c407ec47aff90b0&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=5462481758bb5af4ad348427716a6378f05c8a619b9447785c407ec47aff90b0&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(datasets): soft-delete and restore [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3338025215


##########
superset/commands/dataset/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 dataset."""
+
+import logging
+

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Dead code: unused logger</b></div>
   <div id="fix">
   
   The `logger` variable is assigned at line 30 but never referenced anywhere in the file, making it dead code. Additionally, line 19 imports `logging` solely for this unused declaration.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c2d19a</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/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Invalid module name with hyphens</b></div>
   <div id="fix">
   
   The module name `2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables` contains hyphens which violate Python naming conventions. Alembic migration files should use underscores instead of hyphens in the timestamp portion of the filename.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c2d19a</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(datasets): soft-delete and restore [superset]

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

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

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


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

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



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)

Review Comment:
   Considered — keeping as-is: these are internal helpers/test scaffolding following the surrounding file's documentation and style conventions. Declining as style-tier; happy to revisit if a maintainer feels differently.



##########
tests/integration_tests/security_tests.py:
##########
@@ -560,6 +560,72 @@ def test_after_update_database__perm_datasource_access(self):
         db.session.delete(tmp_db1)
         db.session.commit()
 
+    def test_after_update_database__perm_datasource_access_soft_deleted(self):
+        """A soft-deleted dataset's perm strings must still be rewritten on a
+        database rename. The maintenance query bypasses the soft-delete
+        visibility filter so hidden datasets are updated too; otherwise
+        restoring the dataset later would resurrect stale dataset/schema/catalog
+        permission strings pointing at the old database name.
+        """
+        from datetime import datetime  # noqa: PLC0415
+
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES  # noqa: PLC0415
+
+        security_manager.on_view_menu_after_update = Mock()
+
+        tmp_db1 = Database(database_name="tmp_db1", sqlalchemy_uri="sqlite://")
+        db.session.add(tmp_db1)
+        db.session.commit()
+
+        table1 = SqlaTable(
+            schema="tmp_schema",
+            table_name="tmp_table1",
+            database=tmp_db1,
+        )
+        db.session.add(table1)
+        db.session.commit()
+        table1 = db.session.query(SqlaTable).filter_by(table_name="tmp_table1").one()
+        table1_id = table1.id

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/unit_tests/commands/dataset/test_duplicate.py:
##########
@@ -101,3 +102,66 @@ def test_duplicate_dataset_access_check_passes_through() -> None:
                     command.validate()  # should not raise
                     # Confirm access check was called with the base dataset
                     mock_access.assert_called_once_with(datasource=mock_dataset)
+
+
+def test_duplicate_dataset_blocked_by_soft_deleted_twin(session: Session) -> None:
+    """validate() rejects a duplicate whose name matches a soft-deleted
+    dataset at the same (database, schema).
+
+    The previous name-only ``find_one_or_none`` lookup ran through the
+    soft-delete visibility filter, so a soft-deleted twin was invisible and
+    the duplicate proceeded — hitting whichever DB constraint applies as an
+    opaque IntegrityError, or creating an active twin that permanently
+    blocks restore where none does. The shared ``validate_uniqueness``
+    check bypasses the filter and refuses with a clean validation error.
+    """
+    from datetime import datetime, timezone
+
+    from superset import db
+    from superset.commands.dataset.duplicate import DuplicateDatasetCommand
+    from superset.commands.dataset.exceptions import DatasetInvalidError
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.models.core import Database
+
+    SqlaTable.metadata.create_all(session.get_bind())
+
+    database = Database(database_name="dup_db", sqlalchemy_uri="sqlite://")
+    base = SqlaTable(
+        table_name="base_view",
+        schema="main",
+        database=database,
+        sql="select 1",
+    )
+    hidden_twin = SqlaTable(
+        table_name="dup_name",
+        schema="main",
+        database=database,
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/database/delete.py:
##########
@@ -61,6 +61,28 @@ def validate(self) -> None:
                     report_names=",".join(report_names),
                 )
             )
-        # Check if there are datasets for this database
-        if self._model.tables:
+        # Check if there are datasets for this database. ``self._model.tables``
+        # would now hide soft-deleted datasets (``SqlaTable`` inherits
+        # ``SoftDeleteMixin``, so the relationship lazy-load applies the
+        # visibility filter), letting a database whose datasets are all
+        # soft-deleted look empty and be hard-deleted while ``tables.database_id``
+        # rows still reference it. Count with the visibility filter bypassed so
+        # soft-deleted datasets still block the delete.
+        from superset.connectors.sqla.models import (  # pylint: disable=import-outside-toplevel
+            SqlaTable,
+        )
+        from superset.extensions import (  # pylint: disable=import-outside-toplevel
+            db,
+        )
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
+        )
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            has_datasets = db.session.query(
+                db.session.query(SqlaTable.id)
+                .filter(SqlaTable.database_id == self._model_id)
+                .exists()
+            ).scalar()

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510301404


##########
superset/commands/database/delete.py:
##########
@@ -61,6 +61,28 @@ def validate(self) -> None:
                     report_names=",".join(report_names),
                 )
             )
-        # Check if there are datasets for this database
-        if self._model.tables:
+        # Check if there are datasets for this database. ``self._model.tables``
+        # would now hide soft-deleted datasets (``SqlaTable`` inherits
+        # ``SoftDeleteMixin``, so the relationship lazy-load applies the
+        # visibility filter), letting a database whose datasets are all
+        # soft-deleted look empty and be hard-deleted while ``tables.database_id``
+        # rows still reference it. Count with the visibility filter bypassed so
+        # soft-deleted datasets still block the delete.
+        from superset.connectors.sqla.models import (  # pylint: disable=import-outside-toplevel
+            SqlaTable,
+        )
+        from superset.extensions import (  # pylint: disable=import-outside-toplevel
+            db,
+        )
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
+        )
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            has_datasets = db.session.query(
+                db.session.query(SqlaTable.id)
+                .filter(SqlaTable.database_id == self._model_id)
+                .exists()
+            ).scalar()

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



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for obvious local variables/state flags in this importer utility area when the type is unambiguous from context; keep the code concise where inference is sufficient.
   
   **Applied to:**
     - `superset/commands/dataset/importers/v1/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, config["uuid"]):
+        if existing.deleted_at is not None:
+            # RESTORE path — re-importing a soft-deleted UUID is an implicit
+            # restore-with-update, a distinct operation from overwriting an
+            # alive row, so it is handled in its own branch.
+            if not can_write:
+                # Case B: don't silently return a soft-deleted row to a caller
+                # without write permission — that would let the importer
+                # reattach charts/dashboards to a deleted dataset and produce
+                # broken charts.
+                raise ImportFailedError(
+                    "Dataset was deleted and re-import requires can_write "
+                    "permission to restore it"
+                )
+            # ``user`` is None on background / example-loader paths; combined
+            # with ``can_write`` (typically from ``ignore_permissions=True``)
+            # the ownership check is intentionally skipped because the caller
+            # already established trust.
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
                 raise ImportFailedError(
-                    "A dataset already exists and user doesn't "
-                    "have permissions to overwrite it"
+                    "A dataset already exists and user doesn't have "
+                    "permissions to restore it"
                 )
-        if not overwrite or not can_write:
-            return existing
-        config["id"] = existing.id
+            # Before clearing ``deleted_at``, refuse if another active dataset
+            # already references the same physical table. Otherwise the
+            # restore would produce two live ``SqlaTable`` rows for one
+            # physical table, breaking the logical-uniqueness contract. The
+            # shared DAO helper relies on the SoftDeleteMixin listener to
+            # consider only active rows, excludes ``existing`` itself via
+            # ``id !=``, and normalizes the catalog the same way create/update
+            # uniqueness does.
+            if DatasetDAO.has_active_logical_duplicate(existing):
+                raise ImportFailedError(
+                    "Dataset cannot be restored via re-import because another "
+                    "active dataset already references the same physical table"
+                )
+            # Restore in place (clear ``deleted_at``) rather than
+            # hard-delete-and-replace: a hard delete would cascade through the
+            # chart back-reference and the delete-orphan child relationships
+            # (table_columns, sql_metrics), which the import would then need to
+            # reconstruct.
+            #
+            # How the restore lands as an UPDATE: clearing
+            # ``existing.deleted_at`` marks the in-session row dirty and the
+            # explicit flush emits the ``deleted_at = NULL`` UPDATE before
+            # ``SqlaTable.import_from_dict`` (below) does its own query-by-uuid
+            # lookup. Without the flush we would be relying on autoflush ahead
+            # of that internal query — correct under default session config but
+            # a hidden contract; the explicit flush makes it robust. The lookup
+            # then finds the now-live row (the listener filters ``deleted_at IS
+            # NULL``) and ``import_from_dict`` applies the config as field
+            # updates on the existing object, preserving the PK. Note:
+            # ``config["id"]`` is set defensively, but
+            # ``ImportExportMixin.import_from_dict`` strips it because
+            # ``SqlaTable.export_fields`` does not contain "id"; what actually
+            # binds to the existing row is the uuid uniqueness constraint used
+            # inside ``import_from_dict``.
+            #
+            # Snapshot ``deleted_at`` first so we can roll back the clear if the
+            # downstream ``import_from_dict`` hits the legacy
+            # ``MultipleResultsFound`` fallback. Without the rollback, an
+            # ambiguous import would leave the dataset half-restored
+            # (``deleted_at = None`` but upload contents unapplied).
+            original_deleted_at = existing.deleted_at

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations on local/test-scaffolding variables when the type is already clear from context and the annotation would only add noise without improving mypy coverage.
   
   **Applied to:**
     - `superset/commands/dataset/importers/v1/**`
   
   ---
   💡 *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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510300847


##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,26 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(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 = _("Dataset could not be restored.")
+
+
+class DatasetLogicalDuplicateError(CommandException):
+    status = 422
+    message = _(
+        "Dataset cannot be restored because another active dataset already "
+        "references the same physical table (same database, catalog, schema, "
+        "and table name). Delete the duplicate or rename the table before "
+        "restoring."
+    )

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag test-scaffolding duplication when setup blocks are intentionally kept local to each test for readability.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require docstrings for internal helper functions in test scaffolding; follow the surrounding test-file style conventions instead.
   
   **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/security_tests.py:
##########
@@ -560,6 +560,72 @@ def test_after_update_database__perm_datasource_access(self):
         db.session.delete(tmp_db1)
         db.session.commit()
 
+    def test_after_update_database__perm_datasource_access_soft_deleted(self):
+        """A soft-deleted dataset's perm strings must still be rewritten on a
+        database rename. The maintenance query bypasses the soft-delete
+        visibility filter so hidden datasets are updated too; otherwise
+        restoring the dataset later would resurrect stale dataset/schema/catalog
+        permission strings pointing at the old database name.
+        """
+        from datetime import datetime  # noqa: PLC0415
+
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES  # noqa: PLC0415
+
+        security_manager.on_view_menu_after_update = Mock()
+
+        tmp_db1 = Database(database_name="tmp_db1", sqlalchemy_uri="sqlite://")
+        db.session.add(tmp_db1)
+        db.session.commit()
+
+        table1 = SqlaTable(
+            schema="tmp_schema",
+            table_name="tmp_table1",
+            database=tmp_db1,
+        )
+        db.session.add(table1)
+        db.session.commit()
+        table1 = db.session.query(SqlaTable).filter_by(table_name="tmp_table1").one()
+        table1_id = table1.id

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require concrete type annotations for local test-scaffolding scalar variables in test files when their types are unambiguous from context; avoid flagging this as a style issue.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())

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



##########
tests/unit_tests/commands/dataset/test_duplicate.py:
##########
@@ -101,3 +102,66 @@ def test_duplicate_dataset_access_check_passes_through() -> None:
                     command.validate()  # should not raise
                     # Confirm access check was called with the base dataset
                     mock_access.assert_called_once_with(datasource=mock_dataset)
+
+
+def test_duplicate_dataset_blocked_by_soft_deleted_twin(session: Session) -> None:
+    """validate() rejects a duplicate whose name matches a soft-deleted
+    dataset at the same (database, schema).
+
+    The previous name-only ``find_one_or_none`` lookup ran through the
+    soft-delete visibility filter, so a soft-deleted twin was invisible and
+    the duplicate proceeded — hitting whichever DB constraint applies as an
+    opaque IntegrityError, or creating an active twin that permanently
+    blocks restore where none does. The shared ``validate_uniqueness``
+    check bypasses the filter and refuses with a clean validation error.
+    """
+    from datetime import datetime, timezone
+
+    from superset import db
+    from superset.commands.dataset.duplicate import DuplicateDatasetCommand
+    from superset.commands.dataset.exceptions import DatasetInvalidError
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.models.core import Database
+
+    SqlaTable.metadata.create_all(session.get_bind())
+
+    database = Database(database_name="dup_db", sqlalchemy_uri="sqlite://")
+    base = SqlaTable(
+        table_name="base_view",
+        schema="main",
+        database=database,
+        sql="select 1",
+    )
+    hidden_twin = SqlaTable(
+        table_name="dup_name",
+        schema="main",
+        database=database,
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for local test-scaffolding variables in test files when their types are unambiguous from context and annotations would add noise without improving checks.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *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(datasets): soft-delete and restore [superset]

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

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

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


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -140,21 +141,93 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   Addressed — the import was moved to the top-level import block (`importers/v1/utils.py:40`); it's no longer inline in `import_dataset()`.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
superset/commands/dataset/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 dataset."""
+
+import logging
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+logger = logging.getLogger(__name__)
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    All transactional wrapping and validation lives in
+    ``BaseRestoreCommand``; this subclass is purely declarative.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError

Review Comment:
   Addressed — `RestoreDatasetCommand` now overrides `validate()` and refuses the restore when `DatasetDAO.has_active_logical_duplicate(model)` finds a live row with the same logical identity `(database_id, catalog, schema, table_name)`, before `deleted_at` is cleared.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,10 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(CommandException):
+    message = _("Dataset could not be restored.")

Review Comment:
   Addressed — `DatasetRestoreFailedError` now inherits `UpdateFailedError` (the nearest domain-specific middle-tier base) rather than `CommandException` directly.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,331 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+

Review Comment:
   Addressed — added `assert existing.deleted_at is not None` after the `pytest.raises(ImportFailedError)` block, so a regression that clears `deleted_at` before raising would fail the test.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,331 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+
+
+def test_import_soft_deleted_dataset_raises_when_caller_lacks_can_write(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Case B: re-import of a soft-deleted UUID by a caller without
+    can_write must raise, not silently return the soft-deleted row.
+
+    Real-world scenario: a user has can_write Dashboard but not
+    can_write Dataset, and they import a dashboard zip that references
+    a soft-deleted dataset. Silently returning the row would let the
+    dashboard importer wire the dashboard's charts to a deleted dataset
+    and produce broken chart loads.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=False)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    # Seed a soft-deleted dataset with the matching UUID directly, so the
+    # test doesn't need to flip permissions mid-test.
+    existing = SqlaTable(
+        table_name="soft_deleted_dataset",
+        database_id=database.id,
+        uuid=config["uuid"],
+        deleted_at=datetime(2026, 1, 1, 12, 0, 0),
+    )
+    db.session.add(existing)
+    db.session.flush()
+
+    with pytest.raises(ImportFailedError) as excinfo:
+        import_dataset(config, overwrite=False)
+    assert "can_write" in str(excinfo.value)
+

Review Comment:
   Addressed — the same post-exception `assert existing.deleted_at is not None` was added on the Case B path.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
tests/unit_tests/commands/dataset/restore_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.
+"""Unit tests for RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1)
+    dataset.id = 1
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id", return_value=dataset
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreDatasetCommand("1")
+        cmd.run()

Review Comment:
   Addressed — the restore test (now at `tests/unit_tests/commands/dataset/restore_test.py`) uses real UUIDs: `_DATASET_UUID = str(uuid.uuid4())` / `_MISSING_UUID`, not an integer-like string.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -152,8 +151,11 @@ def insert_database(self, name: str, allow_multi_catalog: bool = False) -> Datab
         return db_connection
 
     def get_fixture_datasets(self) -> list[SqlaTable]:
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES

Review Comment:
   Addressed — `SKIP_VISIBILITY_FILTER_CLASSES` is now a module-level import (`api_tests.py:37`).
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_
   



##########
superset/datasets/api.py:
##########
@@ -706,8 +717,9 @@ def refresh(self, pk: int) -> Response:
     @safe
     @statsd_metrics
     @event_logger.log_this_with_context(

Review Comment:
   These are normalizations of the existing action lambdas to a single-line form, matching the new `restore` action lambda — kept for stylistic consistency. Happy to revert them to keep the diff minimal if you'd prefer; leaving this thread open for your call.
   
   _— 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3391964820


##########
tests/unit_tests/databases/commands/delete_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.
+
+from datetime import datetime
+
+import pytest
+from pytest_mock import MockerFixture
+from sqlalchemy.orm.session import Session
+
+
+def test_delete_database_blocked_by_soft_deleted_dataset(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:

Review Comment:
   <!-- Bito Reply -->
   The user's assessment is correct. Since the `app_context` fixture is already configured as `autouse=True` in the test suite's configuration, the explicit parameter is redundant. The suggestion can be safely ignored.



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,456 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Restore a soft-deleted dataset (cleanup helper).
+
+        Used in ``finally`` blocks so a failed assertion can't strand a
+        soft-deleted row and leak it into later tests; re-queries with the
+        visibility-filter bypass and only restores if still soft-deleted.
+        """
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row is not None and row.deleted_at is not None:
+            row.restore()
+            db.session.commit()
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422

Review Comment:
   <!-- Bito Reply -->
   The `/resolve` command is not supported on inline comments. Please use it in a top-level comment instead.



##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +37,29 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete.
+    #
+    # Match rows whose catalog is either unset (NULL) or the database
+    # default — these are "the same physical table" the way
+    # ``DatasetDAO.validate_uniqueness`` treats them (``table.catalog or
+    # default``). Example rows are seeded with ``catalog = NULL`` while a
+    # connection that reports a default catalog (e.g. Postgres) would
+    # normalize to that default, so both must qualify. This still excludes
+    # an unrelated third catalog variant of the same table_name. Within the
+    # matched set, prefer live rows over soft-deleted ones via
+    # ``ORDER BY deleted_at IS NULL DESC``.
+    catalog = database.get_default_catalog()
     return (
         db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
         .filter_by(database_id=database.id, schema=schema, table_name=table_name)
-        .one_or_none()
+        .filter(or_(SqlaTable.catalog.is_(None), SqlaTable.catalog == catalog))

Review Comment:
   <!-- Bito Reply -->
   The user has decided to keep the inline catalog matching logic as-is, noting that it is an intentional, well-commented duplication in a test helper. They argue that coupling the helper to a private method would create a worse dependency than the current approach.



-- 
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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3397307201


##########
tests/integration_tests/security_tests.py:
##########
@@ -560,6 +560,72 @@ def test_after_update_database__perm_datasource_access(self):
         db.session.delete(tmp_db1)
         db.session.commit()
 
+    def test_after_update_database__perm_datasource_access_soft_deleted(self):

Review Comment:
   **Suggestion:** Add explicit type hints to this newly added test method, including a return annotation (`-> None`), to meet the requirement that new Python code be fully typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python test method, and it has no return type annotation.
   Under the stated rule, new Python code should be fully typed, so omitting `-> None`
   is a real violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=900b697e97844ab1afc8573ddf50cca6&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=900b697e97844ab1afc8573ddf50cca6&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/security_tests.py
   **Line:** 563:563
   **Comment:**
   	*Custom Rule: Add explicit type hints to this newly added test method, including a return annotation (`-> None`), to meet the requirement that new Python code be 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%2F40130&comment_hash=c789363f4c171ec882784943e842a1e4b7575af5a97046b5911e82485421b25c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=c789363f4c171ec882784943e842a1e4b7575af5a97046b5911e82485421b25c&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3398716268


##########
superset/datasets/api.py:
##########
@@ -908,6 +930,64 @@ def bulk_delete(self, **kwargs: Any) -> Response:
         except DatasetDeleteFailedError as ex:
             return self.response_422(message=str(ex))
 
+    @expose("/<uuid>/restore", methods=("POST",))
+    @protect()
+    @safe
+    @statsd_metrics
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.restore",
+        log_to_statsd=False,
+    )
+    def restore(self, uuid: str) -> Response:
+        """Restore a soft-deleted dataset.
+        ---
+        post:
+          summary: Restore a soft-deleted dataset
+          parameters:
+          - in: path
+            schema:
+              type: string
+              format: uuid
+            name: uuid
+          responses:
+            200:
+              description: Dataset restored
+              content:
+                application/json:
+                  schema:
+                    type: object
+                    properties:
+                      message:
+                        type: string
+            401:
+              $ref: '#/components/responses/401'
+            403:
+              $ref: '#/components/responses/403'
+            404:
+              $ref: '#/components/responses/404'
+            422:
+              $ref: '#/components/responses/422'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        try:
+            RestoreDatasetCommand(uuid).run()
+            return self.response(200, message="OK")
+        except DatasetNotFoundError:
+            return self.response_404()
+        except DatasetForbiddenError:
+            return self.response_403()
+        except DatasetLogicalDuplicateError as ex:
+            return self.response_422(message=str(ex))
+        except DatasetRestoreFailedError as ex:
+            logger.error(
+                "Error restoring model %s: %s",
+                self.__class__.__name__,
+                str(ex),
+                exc_info=True,
+            )
+            return self.response_422(message=str(ex))

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing integration tests for error paths</b></div>
   <div id="fix">
   
   The `restore` endpoint has no integration test for `DatasetLogicalDuplicateError` → 422. The unit test `test_restore_dataset_logical_duplicate_raises` covers the command, but not the API contract. Similarly, the 404 (non-existent UUID) and 403 (non-owner) paths lack integration coverage. Per BITO.md rule [11730], new features should include tests for error scenarios.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a8946</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:
##########
@@ -4640,6 +4640,9 @@ msgstr "無法創建數據集。"
 msgid "Dataset could not be duplicated."
 msgstr "數據集無法複製。"
 
+msgid "Dataset 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 msgstr field is empty. Users in the zh_TW locale will see untranslated English text "Dataset could not be restored." instead of a proper Chinese translation. Compare with adjacent entries which follow the pattern "無法/無法+[verb]+數據集" (e.g., "無法創建數據集", "無法更新數據集"). Apply rule [6516]: provide complete translations for all user-facing text.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a8946</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(datasets): soft-delete and restore [superset]

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

   **Latest review items addressed** (`9582bbfdc0`):
   
   - Added `assert rv.status_code == 200` on the soft-delete `DELETE` calls in the list/filter/no-cascade tests (bito CWE-483).
   - **Translations:** added `msgid "Dataset could not be restored."` to `messages.pot`. All language `.po` files already carry the empty-`msgstr` placeholder. Resolving the per-language translation threads as placeholder-complete.
   - The `get_table` catalog determinism (codeant) was fixed in `891486b615`.
   
   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(datasets): soft-delete and restore [superset]

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

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

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


##########
superset/translations/it/LC_MESSAGES/messages.po:
##########
@@ -4602,6 +4602,9 @@ msgstr "La tua query non può essere salvata"
 msgid "Dataset could not be duplicated."
 msgstr "La tua query non può essere salvata"
 
+msgid "Dataset could not be restored."
+msgstr ""

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



##########
superset/translations/fa/LC_MESSAGES/messages.po:
##########
@@ -4634,6 +4634,9 @@ msgstr "گزارش نمی‌تواند ایجاد شود."
 msgid "Dataset could not be duplicated."
 msgstr "مجموعه داده نمی‌تواند تکرار شود."
 
+msgid "Dataset could not be restored."
+msgstr ""

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



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -1957,17 +1974,32 @@ def test_delete_dataset_item(self):
         """
 
         dataset = self.insert_default_dataset()
+        dataset_id = dataset.id
         view_menu = security_manager.find_view_menu(dataset.get_perm())
         assert view_menu is not None
         view_menu_id = view_menu.id
         self.login(ADMIN_USERNAME)
         uri = f"api/v1/dataset/{dataset.id}"
         rv = self.client.delete(uri)
         assert rv.status_code == 200
+        # With soft delete, the row still exists (with deleted_at set) so
+        # FAB permissions are preserved for potential restore.
         non_view_menu = db.session.query(security_manager.viewmenu_model).get(
             view_menu_id
         )
-        assert non_view_menu is None
+        assert non_view_menu is not None
+
+        # Hard-delete the soft-deleted row to avoid unique constraint
+        # collisions in subsequent tests
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -1957,17 +1974,32 @@ def test_delete_dataset_item(self):
         """
 
         dataset = self.insert_default_dataset()
+        dataset_id = dataset.id

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/unit_tests/commands/dataset/test_duplicate.py:
##########
@@ -101,3 +102,66 @@ def test_duplicate_dataset_access_check_passes_through() -> None:
                     command.validate()  # should not raise
                     # Confirm access check was called with the base dataset
                     mock_access.assert_called_once_with(datasource=mock_dataset)
+
+
+def test_duplicate_dataset_blocked_by_soft_deleted_twin(session: Session) -> None:
+    """validate() rejects a duplicate whose name matches a soft-deleted
+    dataset at the same (database, schema).
+
+    The previous name-only ``find_one_or_none`` lookup ran through the
+    soft-delete visibility filter, so a soft-deleted twin was invisible and
+    the duplicate proceeded — hitting whichever DB constraint applies as an
+    opaque IntegrityError, or creating an active twin that permanently
+    blocks restore where none does. The shared ``validate_uniqueness``
+    check bypasses the filter and refuses with a clean validation error.
+    """
+    from datetime import datetime, timezone
+
+    from superset import db
+    from superset.commands.dataset.duplicate import DuplicateDatasetCommand
+    from superset.commands.dataset.exceptions import DatasetInvalidError
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.models.core import Database
+
+    SqlaTable.metadata.create_all(session.get_bind())
+
+    database = Database(database_name="dup_db", sqlalchemy_uri="sqlite://")
+    base = SqlaTable(
+        table_name="base_view",
+        schema="main",
+        database=database,
+        sql="select 1",
+    )
+    hidden_twin = SqlaTable(
+        table_name="dup_name",
+        schema="main",
+        database=database,
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )
+    db.session.add_all([database, base, hidden_twin])
+    db.session.flush()
+
+    with (
+        # find_by_id applies the security base filter, which needs a request
+        # user; return the seeded row directly. validate_uniqueness — the
+        # behaviour under test — runs for real against the session.
+        patch(
+            "superset.commands.dataset.duplicate.DatasetDAO.find_by_id",
+            return_value=base,
+        ),
+        patch("superset.commands.dataset.duplicate.security_manager.raise_for_access"),
+        patch(
+            "superset.commands.dataset.duplicate."
+            "DuplicateDatasetCommand.populate_owners",
+            return_value=[],
+        ),
+    ):
+        command = DuplicateDatasetCommand(
+            {
+                "base_model_id": base.id,
+                "table_name": "dup_name",
+                "is_managed_externally": False,
+            }
+        )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/database/exceptions.py:
##########
@@ -156,6 +156,18 @@ class DatabaseDeleteDatasetsExistFailedError(DeleteFailedError):
     message = _("Cannot delete a database that has datasets attached")
 
 
+class DatabaseDeleteSoftDeletedDatasetsExistFailedError(
+    DatabaseDeleteDatasetsExistFailedError
+):
+    # Subclasses the live-datasets error so the existing API handler catches
+    # both; only the message differs, telling the operator that the blockers
+    # are hidden (soft-deleted) rows even though their dataset list looks empty.
+    message = _(
+        "Cannot delete a database whose only remaining datasets are "
+        "soft-deleted. Restore or permanently purge them first."
+    )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510304039


##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]
+
             yield datasets
 
-            # rollback changes
-            for dataset in datasets:
-                state = inspect(dataset)
-                if not state.was_deleted:
-                    db.session.delete(dataset)
+            # rollback changes (including soft-deleted rows)
+            for dataset_id in dataset_ids:
+                row = (
+                    db.session.query(SqlaTable)
+                    .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                    .filter(SqlaTable.id == dataset_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 clear from context; adding annotations there is considered noise.
   
   **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/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]
+
             yield datasets
 
-            # rollback changes
-            for dataset in datasets:
-                state = inspect(dataset)
-                if not state.was_deleted:
-                    db.session.delete(dataset)
+            # rollback changes (including soft-deleted rows)
+            for dataset_id in dataset_ids:

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 and the annotation would add noise.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/databases/sync_permissions_test.py:
##########
@@ -409,3 +409,49 @@ def test_sync_permissions_command_rename_db_in_perms(
     assert (
         mock_chart.schema_perm == f"[{database_with_catalog.name}].[catalog1].[schema1]"
     )
+
+
+def test_sync_permissions_command_rename_bypasses_visibility_filter(
+    mocker: MockerFixture, database_with_catalog: MagicMock
+):
+    """The dataset/chart perm rewrite must run with the soft-delete
+    visibility filter bypassed for ``SqlaTable`` and ``Slice``.
+
+    A soft-deleted dataset's ``schema_perm``/``catalog_perm`` (and its
+    charts') must still be rewritten on a database rename; without the
+    bypass, the listener hides those rows from ``get_datasets`` and a
+    later restore resurrects stale perm strings referencing the old
+    database name — matchable by a ``schema_access`` grant on a new
+    database reusing that name.
+    """
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+    from superset.models.slice import Slice
+
+    mocker.patch(
+        "superset.commands.database.sync_permissions."
+        "security_manager.find_permission_view_menu",
+        return_value=None,
+    )
+    observed_bypass: list[set[type]] = []
+
+    def capture_bypass(*args, **kwargs):
+        observed_bypass.append(
+            set(db.session.info.get(SKIP_VISIBILITY_FILTER_CLASSES, set()))
+        )
+        return []
+

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing type annotations for local helper functions or test-scaffolding variables in test files when the types are already unambiguous from context and adding annotations would only add noise.
   
   **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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3501639180


##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()

Review Comment:
   **Suggestion:** The pre-test purge is intended to remove only soft-deleted fixture rows, but it currently deletes every matching dataset returned by `get_fixture_datasets()`. Because that query now bypasses visibility filters, this can hard-delete active rows too and cause cross-test state corruption. Restrict the purge to rows where `deleted_at` is set before deleting. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Fixture purge hard-deletes live datasets for AB tables.
   - ⚠️ Later tests may run without expected fixture datasets.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. In `TestDatasetApi` (tests/integration_tests/datasets/api_tests.py:70-120), create a
   live dataset for one of `fixture_tables_names` by calling `insert_default_dataset()` or
   `insert_dataset()` so a `SqlaTable` row with `table_name` in `("ab_permission",
   "ab_permission_view", "ab_view_menu")` exists with `deleted_at is None`.
   
   2. Verify the live dataset exists by calling `get_fixture_datasets()`
   (tests/integration_tests/datasets/api_tests.py:155-162), which queries `SqlaTable` with
   `.execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})` and
   `.filter(SqlaTable.table_name.in_(self.fixture_tables_names))`, returning both active and
   soft-deleted rows.
   
   3. Run a test using the `create_datasets` fixture, e.g. `test_delete_dataset_column` at
   tests/integration_tests/datasets/api_tests.py:2045-2058, which triggers the fixture body
   at lines 196-203.
   
   4. Observe in the fixture that the loop at
   tests/integration_tests/datasets/api_tests.py:197-201 calls `db.session.delete(ds)` for
   every row returned by `get_fixture_datasets()` and commits, hard-deleting active datasets
   (not just soft-deleted ones) and potentially removing rows relied on by other tests.
   ```
   </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=e25cab74025441be8ee678017798e9b7&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=e25cab74025441be8ee678017798e9b7&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/datasets/api_tests.py
   **Line:** 196:201
   **Comment:**
   	*Incorrect Condition Logic: The pre-test purge is intended to remove only soft-deleted fixture rows, but it currently deletes every matching dataset returned by `get_fixture_datasets()`. Because that query now bypasses visibility filters, this can hard-delete active rows too and cause cross-test state corruption. Restrict the purge to rows where `deleted_at` is set before deleting.
   
   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%2F40130&comment_hash=41a6238c5ae2299b26c28db4e50cd84be712f02be0d20a78aaadb28ae81628a1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=41a6238c5ae2299b26c28db4e50cd84be712f02be0d20a78aaadb28ae81628a1&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)

Review Comment:
   **Suggestion:** This test creates and soft-deletes persistent rows but performs teardown only at the end of the happy path. If any assertion fails earlier, cleanup is skipped and leaves leaked dataset/database rows that can trigger later uniqueness collisions and test flakiness. Move teardown into a `finally` block. [missing cleanup]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Test-created database and dataset can leak on failures.
   - ⚠️ Subsequent tests may see stray ACL-scoped datasets.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Open `TestDatasetSoftDelete.test_deleted_state_list_shows_owner_their_own_deleted` in
   tests/integration_tests/datasets/soft_delete_tests.py:164-191; it creates a `Database`
   named `"sd_owner_db"` and a `SqlaTable` `"sd_owner_tbl"` owned by Alpha (lines 168-176)
   and sets `deleted_at` on the dataset (lines 179-180).
   
   2. The test logs in as Alpha and calls `GET
   /api/v1/dataset/?q=...dataset_deleted_state=value:only` (lines 182-187), then asserts the
   soft-deleted dataset’s ID appears in the response (lines 187-189).
   
   3. Cleanup is performed by `self._hard_delete_created(dataset_id, database)` at line 191,
   which hard-deletes the test-created dataset and database using a
   visibility-filter-bypassing query (lines 151-162), but this call is not inside a
   `try/finally` block.
   
   4. If any earlier step raises (for example, the response does not include `dataset_id` and
   the assertion at line 189 fails), the test aborts before calling `_hard_delete_created`,
   leaving the extra `Database` and `SqlaTable` rows in the database and risking later
   uniqueness collisions or unexpected extra rows with the same names.
   ```
   </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=e2e5221992264a09911a9383d5d62357&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=e2e5221992264a09911a9383d5d62357&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/datasets/soft_delete_tests.py
   **Line:** 182:191
   **Comment:**
   	*Missing Cleanup: This test creates and soft-deletes persistent rows but performs teardown only at the end of the happy path. If any assertion fails earlier, cleanup is skipped and leaves leaked dataset/database rows that can trigger later uniqueness collisions and test flakiness. Move teardown into a `finally` block.
   
   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%2F40130&comment_hash=483dcf74bf5976305432ca46df35e699bd956c9d840429884733a8f1a925a9b3&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=483dcf74bf5976305432ca46df35e699bd956c9d840429884733a8f1a925a9b3&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())

Review Comment:
   **Suggestion:** The comment says these UUIDs are stable, but using `uuid.uuid4()` makes them random on every run. Update the comment (or switch to fixed UUID literals) so the test documentation matches the actual behavior and avoids misleading future maintainers. [comment mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Minor 🧹</summary>
   
   ```mdx
   - ⚠️ Misleading comment about UUID stability in restore tests.
   - ⚠️ Could confuse maintainers reading dataset restore test setup.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Open `tests/unit_tests/commands/dataset/restore_test.py` and inspect lines 27-31, where
   the comment states “Stable UUIDs make the test boundary realistic”.
   
   2. Observe that `_DATASET_UUID` and `_MISSING_UUID` are defined on lines 30-31 as
   `str(uuid.uuid4())`, which creates new random UUIDs on every test run.
   
   3. Confirm there is no seeding, fixture, or override elsewhere in the file that would make
   these UUIDs deterministic or stable across runs.
   
   4. Conclude that the comment is misleading because the UUIDs are not stable; this is a
   documentation mismatch, not a functional test failure.
   ```
   </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=84a38bdbff1040a2b9a5f92f29658ae8&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=84a38bdbff1040a2b9a5f92f29658ae8&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/dataset/restore_test.py
   **Line:** 27:31
   **Comment:**
   	*Comment Mismatch: The comment says these UUIDs are stable, but using `uuid.uuid4()` makes them random on every run. Update the comment (or switch to fixed UUID literals) so the test documentation matches the actual behavior and avoids misleading future maintainers.
   
   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%2F40130&comment_hash=ed583c5e0ee84e7fa6cf04808aa1eecfb220aaf6ba46468404a18ea9c65e4d6b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=ed583c5e0ee84e7fa6cf04808aa1eecfb220aaf6ba46468404a18ea9c65e4d6b&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3501647542


##########
superset/daos/base.py:
##########
@@ -81,9 +81,15 @@ def apply(self, column: Any, value: Any) -> Any:
         return op_func(column, value)
 
 
-def _escape_like(value: str) -> str:
-    """Escape LIKE/ILIKE wildcards to prevent wildcard injection."""
-    return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+def _escape_like(value: Any) -> str:
+    """Escape LIKE/ILIKE wildcards to prevent wildcard injection.
+
+    ``ColumnOperator.value`` is typed ``Any``, so a non-string payload (e.g. a
+    numeric JSON value) can reach a LIKE-family operator. Coerce to ``str`` so
+    such input degrades to a literal match instead of raising ``AttributeError``.
+    """
+    text = "" if value is None else str(value)
+    return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")

Review Comment:
   **Suggestion:** Converting `None` to an empty string makes LIKE-family filters generate wildcard-only patterns (`%`, `%%`, etc.), so a request with a null filter value can unintentionally match almost all rows. Treat `None` as an invalid value for LIKE operators (or convert it to the literal string `"None"`) instead of collapsing it to `""`. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Dataset MCP list filters with null values match all datasets.
   - ⚠️ Generic DAO LIKE filters can misbehave on missing values.
   - ⚠️ Chart and dashboard DAO filters may return overly broad results.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Start Superset with this PR code and focus on the MCP dataset listing tool defined at
   `superset/mcp_service/dataset/tool/list_datasets.py:1-33`, which calls
   `ModelListCore.run_tool()` (see `superset/mcp_service/mcp_core.py:41-52`) and in turn
   `_call_dao_list()` (lines 16-39) to invoke `DatasetDAO.list()` with `filters` forwarded as
   `column_operators`.
   
   2. Craft a DatasetFilter-like object (or JSON) where `opr` is a LIKE-family operator such
   as `"sw"` (starts-with) and `value` is null/omitted, e.g. `{"col": "table_name", "opr":
   "sw"}`; when parsed to a `ColumnOperator` (base model at `superset/daos/base.py:7-10` with
   `value: Any = Field(None, ...)`), this produces an instance with `c.value is None`.
   
   3. When `ModelListCore._call_dao_list()` calls `DatasetDAO.list(column_operators=filters)`
   (see `superset/mcp_service/mcp_core.py:30-39`), `BaseDAO.list()` at
   `superset/daos/base.py:11-23, 63-79` eventually calls `cls.apply_column_operators(query,
   column_operators)`; inside `apply_column_operators` (lines 16-64), the `ColumnOperator` is
   processed and `operator_enum.apply(column, value)` is invoked with `value=None`.
   
   4. `ColumnOperatorEnum.sw` is mapped in `operator_map` (see `superset/daos/base.py:37-47`)
   to `lambda col, val: col.like(f"{_escape_like(val)}%", escape="\\")`; `_escape_like`
   (lines 25-33) sees `value is None`, sets `text = ""`, and returns an empty string, so the
   pattern becomes `"%"`, which in SQL LIKE matches almost every row, causing the filter
   intended to be empty/invalid to act as a match-all and return an unfiltered dataset list.
   ```
   </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=88f092378ef943d5abd0614045b6f4c9&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=88f092378ef943d5abd0614045b6f4c9&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/base.py
   **Line:** 91:92
   **Comment:**
   	*Incorrect Condition Logic: Converting `None` to an empty string makes LIKE-family filters generate wildcard-only patterns (`%`, `%%`, etc.), so a request with a null filter value can unintentionally match almost all rows. Treat `None` as an invalid value for LIKE operators (or convert it to the literal string `"None"`) instead of collapsing it to `""`.
   
   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%2F40130&comment_hash=0eb32009e835bbfe1fb594460fd3829b6c5580c15217c58a99f8e6564f37efdf&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=0eb32009e835bbfe1fb594460fd3829b6c5580c15217c58a99f8e6564f37efdf&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510001047


##########
superset/commands/database/sync_permissions.py:
##########
@@ -283,17 +286,29 @@ def _rename_database_in_permissions(
             if existing_pvm:
                 existing_pvm.view_menu.name = new_schema_perm_name
 
-            # rename permissions on datasets and charts
-            for dataset in DatabaseDAO.get_datasets(
-                self.db_connection_id,
-                catalog=catalog,
-                schema=schema,
-            ):
-                dataset.catalog_perm = new_catalog_perm_name
-                dataset.schema_perm = new_schema_perm_name
-                for chart in DatasetDAO.get_related_objects(dataset.id)["charts"]:
-                    chart.catalog_perm = new_catalog_perm_name
-                    chart.schema_perm = new_schema_perm_name
+            # Rename permissions on datasets and charts. Bypass the
+            # soft-delete visibility filter: a soft-deleted dataset's
+            # ``schema_perm``/``catalog_perm`` (and its charts') must still be
+            # rewritten on a database rename — otherwise restoring the dataset
+            # later brings back stale perm strings referencing the old
+            # database name (fail-closed for legitimate users, and matchable
+            # by a schema_access grant on a new database reusing the old
+            # name). Mirrors the same bypass in
+            # ``security_manager._update_vm_datasources_access``, which
+            # maintains the dataset-level ``perm`` string. ``Slice`` is
+            # included so chart perm rewrites keep working once charts gain
+            # soft delete (a no-op until then).
+            with skip_visibility_filter(db.session, SqlaTable, Slice):
+                for dataset in DatabaseDAO.get_datasets(
+                    self.db_connection_id,
+                    catalog=catalog,
+                    schema=schema,
+                ):
+                    dataset.catalog_perm = new_catalog_perm_name
+                    dataset.schema_perm = new_schema_perm_name

Review Comment:
   **Suggestion:** The dataset rewrite loop is catalog-strict, so when the renamed database has a non-NULL default catalog, legacy datasets stored with `catalog = NULL` are skipped and keep stale permission strings. Use a null-aware catalog match for this rename path (default catalog should match both explicit default and NULL) so restored datasets and their charts do not retain old database-based perms. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Default-catalog datasets retain stale schema/catalog permission strings.
   - ⚠️ Restored datasets fail for authorized users post-database rename.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Configure a database that supports catalogs with a non-NULL default catalog, so
   `SyncPermissionsCommand._get_catalog_names()` in
   `superset/commands/database/sync_permissions.py:188-207` returns
   `{self.db_connection.get_default_catalog()}` instead of `{None}`.
   
   2. Ensure there is at least one legacy dataset row for this database whose physical table
   is in the default catalog but whose `SqlaTable.catalog` column is `NULL` (semantics
   documented in `DatasetDAO._catalog_identity_filter()` at
   `superset/daos/dataset.py:159-176`, which treats `catalog = NULL` as the default catalog).
   
   3. Rename the database connection (changing `Database.database_name`) so that
   `SyncPermissionsCommand.sync_database_permissions()` at
   `superset/commands/database/sync_permissions.py:138-187` runs and enters
   `_rename_database_in_permissions()` when `self.old_db_connection_name !=
   self.db_connection.database_name`.
   
   4. During `_rename_database_in_permissions()` the loop at
   `superset/commands/database/sync_permissions.py:301-308` calls
   `DatabaseDAO.get_datasets(self.db_connection_id, catalog=catalog, schema=schema)`, which
   filters with strict equality on `SqlaTable.catalog == catalog`
   (`superset/daos/database.py:255-259`). The legacy dataset with `catalog = NULL` is not
   returned, so its `catalog_perm` and `schema_perm` fields are not updated to the new
   database name and remain stale, causing restored datasets/charts to carry old permission
   identifiers.
   ```
   </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=7d3d209db65a426daadb06c5fafc0a64&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=7d3d209db65a426daadb06c5fafc0a64&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/database/sync_permissions.py
   **Line:** 301:308
   **Comment:**
   	*Logic Error: The dataset rewrite loop is catalog-strict, so when the renamed database has a non-NULL default catalog, legacy datasets stored with `catalog = NULL` are skipped and keep stale permission strings. Use a null-aware catalog match for this rename path (default catalog should match both explicit default and NULL) so restored datasets and their charts do not retain old database-based perms.
   
   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%2F40130&comment_hash=a93b6c2f0b695bd1d43725b45258abe37551bcb3e4872a3881d8209423c949ef&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=a93b6c2f0b695bd1d43725b45258abe37551bcb3e4872a3881d8209423c949ef&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(datasets): soft-delete and restore [superset]

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

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

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

   ### 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.
   
   Datasets 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3343890010


##########
superset/datasets/filters.py:
##########
@@ -51,3 +53,10 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(BaseDeletedStateFilter):  # pylint: disable=too-few-public-methods
+    """Rison filter for the GET list that exposes soft-deleted datasets."""
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing type annotation on model</b></div>
   <div id="fix">
   
   Add a type annotation to the `model` attribute to match the `BaseDeletedStateFilter` contract: declare `model: ClassVar[type[SoftDeleteMixin]] = SqlaTable`, and import both `ClassVar` from `typing` and `SoftDeleteMixin` from its module.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #e19a98</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(datasets): soft-delete and restore [superset]

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


##########
superset/commands/dataset/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 dataset."""
+
+import logging
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+logger = logging.getLogger(__name__)
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    All transactional wrapping and validation lives in
+    ``BaseRestoreCommand``; this subclass is purely declarative.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError

Review Comment:
   **HIGH — `RestoreDatasetCommand` does not check for live logical duplicates before restoring**
   
   `validate()` (in `BaseRestoreCommand`) confirms the row exists, is soft-deleted, and the caller owns it — but it does **not** check whether a live dataset with the same `(database_id, catalog, schema, table_name)` was created while this one was soft-deleted.
   
   Because `SqlaTable` uniqueness is logical-only (not a DB constraint — see the comment at `models.py:1249`), and `DatasetDAO.validate_uniqueness` now excludes soft-deleted rows via the ORM listener, the following sequence is valid today:
   
   1. `DELETE /api/v1/dataset/{pk}` — soft-deletes dataset A (`db.public.users`)
   2. `POST /api/v1/dataset/` — creates dataset B, same physical table — uniqueness check misses soft-deleted A
   3. `POST /api/v1/dataset/{uuid_A}/restore` — restores A
   
   Result: **two live `SqlaTable` rows for the same physical table**, producing chart-lookup ambiguity and undefined behavior in anything that assumes one dataset per physical table.
   
   Fix: add a dataset-specific `validate()` override (or a pre-restore hook) that queries for a live row with the same logical identity before clearing `deleted_at`. Also fix `DatasetDAO.validate_uniqueness` / `validate_update_uniqueness` to bypass the visibility filter so soft-deleted rows block re-creation at the API level.
   
   This is the root cause of the issue richardfogaca noted at `api.py:963`.



##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,10 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(CommandException):
+    message = _("Dataset could not be restored.")

Review Comment:
   **MEDIUM — `DatasetRestoreFailedError` should inherit a domain-specific base, not `CommandException` directly**
   
   All sibling exceptions use typed middle-tier bases:
   - `DatasetDeleteFailedError(DeleteFailedError)`
   - `DatasetUpdateFailedError(UpdateFailedError)`
   - `DatasetRefreshFailedError(UpdateFailedError)` (nearest analogy)
   
   Inheriting `CommandException` directly skips the tier. Either define `RestoreFailedError` in `superset/commands/exceptions.py` (mirroring `DeleteFailedError` / `UpdateFailedError`) and inherit from that, or inherit from the nearest analogy (`UpdateFailedError`) with a comment explaining the choice.



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

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


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -140,21 +141,93 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).first()
+    from superset.commands.importers.v1.utils import find_existing_for_import

Review Comment:
   **BLOCKER (Scan 1 / Rule 6) — Inline import inside function body, no circular-import justification**
   
   This import lives inside `import_dataset()` with no justification comment. `superset.commands.importers.v1.utils` does **not** import from `superset.commands.dataset.importers.v1.utils`, so there is no circular dependency preventing a module-level placement. Move it to the top-level import block alongside the other `superset.commands.*` imports. Per project convention, inline imports require a `# avoid circular import: …` comment; without one they are always a BLOCKER.



-- 
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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3350036747


##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,349 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+    # Verify the permission check fired before any mutation: if a regression
+    # cleared ``deleted_at`` before raising, this would silently produce a
+    # half-restored row and the test would still pass on the message check
+    # alone.
+    db.session.refresh(existing)
+    assert existing.deleted_at is not None, (
+        "deleted_at was cleared before the exception — restore mutation "
+        "happened before the ownership check"
+    )
+
+
+def test_import_soft_deleted_dataset_raises_when_caller_lacks_can_write(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Case B: re-import of a soft-deleted UUID by a caller without
+    can_write must raise, not silently return the soft-deleted row.
+
+    Real-world scenario: a user has can_write Dashboard but not
+    can_write Dataset, and they import a dashboard zip that references
+    a soft-deleted dataset. Silently returning the row would let the
+    dashboard importer wire the dashboard's charts to a deleted dataset
+    and produce broken chart loads.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=False)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    # Seed a soft-deleted dataset with the matching UUID directly, so the
+    # test doesn't need to flip permissions mid-test.
+    existing = SqlaTable(
+        table_name="soft_deleted_dataset",
+        database_id=database.id,
+        uuid=config["uuid"],
+        deleted_at=datetime(2026, 1, 1, 12, 0, 0),
+    )
+    db.session.add(existing)
+    db.session.flush()
+
+    with pytest.raises(ImportFailedError) as excinfo:
+        import_dataset(config, overwrite=False)
+    assert "can_write" in str(excinfo.value)
+    # Case B contract: deleted_at must remain set after the exception. A
+    # regression that clears deleted_at before the can_write check would
+    # leave the row in a half-restored state and silently pass the message
+    # assertion above.
+    db.session.refresh(existing)
+    assert existing.deleted_at is not None, (
+        "Case B: deleted_at was cleared before raising — mutation happened "
+        "before the can_write check"
+    )
+
+
+def test_import_soft_deleted_dataset_restore_removes_orphan_children(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Restoring a soft-deleted dataset via re-import (non-overwrite,
+    Option C) syncs columns and metrics — children present in the live
+    row but absent from the uploaded config are removed, not silently
+    merged.
+
+    Without forcing sync on the implicit-restore path, ``sync=[]``
+    would mean "upsert by UUID, leave non-matching children alone",
+    so the restored dataset would carry stale columns from before the
+    soft-delete. That's a surprising merge of two states; treating
+    re-import as a clean replacement is what an explicit ``overwrite``
+    would do anyway.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    # Add an orphan column that the upload doesn't know about.
+    orphan = TableColumn(
+        column_name="orphan_col",
+        type="STRING",
+        table=existing,
+    )
+    db.session.add(orphan)
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+    orphan_uuid = orphan.uuid
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+    assert orphan_uuid not in {c.uuid for c in restored.columns}, (
+        "orphan column survived restore-via-import; the implicit-restore "
+        "path must force sync so re-import is a clean replacement"
+    )
+
+
+def test_import_dataset_multiple_results_fallback_finds_soft_deleted(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    The MultipleResultsFound exception handler inside import_dataset does
+    a second lookup by uuid via ``.one()``. That fallback bypasses the
+    soft-delete visibility filter so a soft-deleted duplicate is still
+    returnable — without the bypass the listener would hide it and the
+    fallback's ``.one()`` would raise ``NoResultFound``, masking the
+    original ``MultipleResultsFound`` with a misleading error.
+
+    Reproduce: monkey-patch ``SqlaTable.import_from_dict`` to raise
+    ``MultipleResultsFound`` and seed two rows with the same uuid (one
+    live, one soft-deleted). The fallback's ``.one()`` would normally
+    return ambiguous, so we narrow with the bypass-aware filter.
+    """
+    from sqlalchemy.exc import MultipleResultsFound
+
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+    mocker.patch.object(
+        SqlaTable,
+        "import_from_dict",
+        side_effect=MultipleResultsFound("simulated duplicate"),
+    )
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    # Seed a soft-deleted row with the target uuid directly. Without the
+    # bypass on the fallback query, the listener would hide this row and
+    # .one() would raise NoResultFound.
+    soft_deleted = SqlaTable(
+        table_name="ambiguous_dataset",
+        database_id=database.id,
+        uuid=config["uuid"],
+        deleted_at=datetime(2026, 1, 1, 12, 0, 0),
+    )
+    db.session.add(soft_deleted)
+    db.session.flush()
+
+    # Should return the row (the only one matching the uuid), not raise
+    # NoResultFound. The importer clears ``deleted_at`` on the soft-deleted
+    # match before ``import_from_dict`` is called, so the row returned by
+    # the fallback no longer reports as soft-deleted — what we verify here
+    # is that the bypass found the row at all rather than masking the
+    # original ``MultipleResultsFound`` with a misleading error.
+    result = import_dataset(config)
+    assert result.uuid == config["uuid"]

Review Comment:
   **Suggestion:** This assertion path is incompatible with the current importer contract for soft-deleted matches when `SqlaTable.import_from_dict` raises `MultipleResultsFound`: `import_dataset` now rolls back the restore and raises `ImportFailedError` instead of returning a dataset. The test should assert the expected exception (or use a non-soft-deleted setup) to avoid a deterministic failure. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Unit test for soft-deleted MultipleResultsFound path always fails.
   - ⚠️ Importer's new soft-delete contract not correctly asserted by tests.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. In `tests/unit_tests/datasets/commands/importers/v1/import_test.py:281-337`, test
   `test_import_dataset_multiple_results_fallback_finds_soft_deleted` patches
   `SqlaTable.import_from_dict` to raise `MultipleResultsFound` and seeds a soft-deleted
   `SqlaTable` row with `uuid=config["uuid"]`.
   
   2. The test then calls `result = import_dataset(config)` at line 1324 expecting a
   successful return and asserts `result.uuid == config["uuid"]` at line 1325.
   
   3. In the importer implementation at
   `superset/commands/dataset/importers/v1/utils.py:10-103`, `import_dataset()` calls
   `find_existing_for_import(SqlaTable, config["uuid"])` (line 61), which returns the
   soft-deleted row while bypassing the visibility filter (`find_existing_for_import` at
   lines 405-426).
   
   4. Because `existing.deleted_at` is not `None`, `import_dataset()` takes the soft-deleted
   mutation path (lines 103-135), clears `deleted_at`, and sets `is_soft_deleted_match =
   True`; when the patched `SqlaTable.import_from_dict` raises `MultipleResultsFound`, the
   `except MultipleResultsFound` block at lines 178-203 detects `is_soft_deleted_match` and,
   by design, restores `existing.deleted_at` and raises `ImportFailedError` instead of
   returning a dataset, so the assertion `result.uuid == config["uuid"]` at line 1325 is
   never reached and the test deterministically fails.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e10f38ce53a44b169f573366f7cc211b&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=e10f38ce53a44b169f573366f7cc211b&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/datasets/commands/importers/v1/import_test.py
   **Line:** 1324:1325
   **Comment:**
   	*Api Mismatch: This assertion path is incompatible with the current importer contract for soft-deleted matches when `SqlaTable.import_from_dict` raises `MultipleResultsFound`: `import_dataset` now rolls back the restore and raises `ImportFailedError` instead of returning a dataset. The test should assert the expected exception (or use a non-soft-deleted setup) to avoid a deterministic failure.
   
   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%2F40130&comment_hash=078cba8ff4c422ab7dd9b7f97c4b539be264626956442c32e51968489f4ee47c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=078cba8ff4c422ab7dd9b7f97c4b539be264626956442c32e51968489f4ee47c&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(datasets): soft-delete and restore [superset]

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

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

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

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

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

   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.
   - **"Missing integration test" for the restore-failure 422 handler**: it exists — `tests/integration_tests/datasets/soft_delete_tests.py::TestDatasetRestore::test_restore_failure_returns_422` patches the command to raise and asserts the 422 mapping.


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

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


##########
superset/commands/database/delete.py:
##########
@@ -61,6 +61,28 @@ def validate(self) -> None:
                     report_names=",".join(report_names),
                 )
             )
-        # Check if there are datasets for this database
-        if self._model.tables:
+        # Check if there are datasets for this database. ``self._model.tables``
+        # would now hide soft-deleted datasets (``SqlaTable`` inherits
+        # ``SoftDeleteMixin``, so the relationship lazy-load applies the
+        # visibility filter), letting a database whose datasets are all
+        # soft-deleted look empty and be hard-deleted while ``tables.database_id``
+        # rows still reference it. Count with the visibility filter bypassed so
+        # soft-deleted datasets still block the delete.
+        from superset.connectors.sqla.models import (  # pylint: disable=import-outside-toplevel
+            SqlaTable,
+        )
+        from superset.extensions import (  # pylint: disable=import-outside-toplevel
+            db,
+        )
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
+        )
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            has_datasets = db.session.query(
+                db.session.query(SqlaTable.id)
+                .filter(SqlaTable.database_id == self._model_id)
+                .exists()
+            ).scalar()
+        if has_datasets:
             raise DatabaseDeleteDatasetsExistFailedError()

Review Comment:
   Fixed in b9f6282765 — the guard now counts live vs. any datasets separately: a live dataset raises the existing error, while a database whose only remaining datasets are soft-deleted raises a new `DatabaseDeleteSoftDeletedDatasetsExistFailedError` (a subclass of the existing one, so the `databases/api.py` handler catches it unchanged) whose message tells the operator to restore or purge the hidden datasets first.
   
   _— posted by Claude (AI agent) on behalf of @mikebridge_



##########
superset/commands/dataset/duplicate.py:
##########
@@ -121,7 +121,19 @@ def validate(self) -> None:
         if self._base_model and self._base_model.kind != "virtual":
             exceptions.append(DatasourceTypeInvalidError())
 
-        if DatasetDAO.find_one_or_none(table_name=duplicate_name):
+        # Use the shared uniqueness check (same as create/update) rather than a
+        # name-only filtered lookup: it scopes to the base model's
+        # database/schema, is catalog-NULL-aware, and bypasses the soft-delete
+        # visibility filter. A filtered lookup misses a soft-deleted twin, so
+        # the duplicate would proceed and either hit a DB constraint as an
+        # opaque IntegrityError or — where no constraint applies (the
+        # model-level UniqueConstraint is metadata-only and the legacy
+        # _customer_location_uc is NULL-leaky) — create an active twin that
+        # permanently blocks restore of the soft-deleted dataset.
+        if base_model and not DatasetDAO.validate_uniqueness(
+            base_model.database,
+            Table(duplicate_name, base_model.schema),

Review Comment:
   Fixed in b9f6282765 — `validate()` now probes `Table(duplicate_name, base_model.schema, base_model.catalog)`, and `run()` stamps `table.catalog = self._base_model.catalog` on the new row, so a soft-deleted twin in a non-default catalog is detected instead of being missed via the default catalog.
   
   _— 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(datasets): soft-delete and restore (sc-106191) [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3344699117


##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   <!-- Bito Reply -->
   The suggestion to rename the migration file is not necessary. Alembic identifies migration files by their revision ID (the alphanumeric string in the filename), not by the module name or the presence of hyphens in the timestamp prefix. The current naming convention is standard for Alembic and will not cause import issues.



##########
superset/commands/dataset/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 dataset."""
+
+import logging
+

Review Comment:
   <!-- Bito Reply -->
   The suggestion to remove the unused logger and its import is appropriate, as it eliminates dead code and unnecessary dependencies, which improves code cleanliness. You can safely apply this change to keep the codebase lean.
   
   **superset/commands/dataset/restore.py**
   ```
   import logging
   ```



##########
superset/datasets/filters.py:
##########
@@ -51,3 +53,10 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(BaseDeletedStateFilter):  # pylint: disable=too-few-public-methods
+    """Rison filter for the GET list that exposes soft-deleted datasets."""
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable

Review Comment:
   <!-- Bito Reply -->
   The reviewer's suggestion to add a type annotation is not required in this case. As you noted, the `model` attribute is already defined in the `BaseDeletedStateFilter` parent class, and the subclass assignment `model = SqlaTable` is correctly type-checked against that existing annotation. Following the established pattern used by the sibling filters is appropriate here.



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

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

   Follow-up correction: I reverted the `down_revision` change in 42e732a1e2.
   
   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 42e732a1e2.
   
   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(datasets): soft-delete and restore [superset]

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


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, config["uuid"]):
+        if existing.deleted_at is not None:
+            # RESTORE path — re-importing a soft-deleted UUID is an implicit
+            # restore-with-update, a distinct operation from overwriting an
+            # alive row, so it is handled in its own branch.
+            if not can_write:
+                # Case B: don't silently return a soft-deleted row to a caller
+                # without write permission — that would let the importer
+                # reattach charts/dashboards to a deleted dataset and produce
+                # broken charts.
+                raise ImportFailedError(
+                    "Dataset was deleted and re-import requires can_write "
+                    "permission to restore it"
+                )
+            # ``user`` is None on background / example-loader paths; combined
+            # with ``can_write`` (typically from ``ignore_permissions=True``)
+            # the ownership check is intentionally skipped because the caller
+            # already established trust.
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
                 raise ImportFailedError(
-                    "A dataset already exists and user doesn't "
-                    "have permissions to overwrite it"
+                    "A dataset already exists and user doesn't have "
+                    "permissions to restore it"
                 )
-        if not overwrite or not can_write:
-            return existing
-        config["id"] = existing.id
+            # Before clearing ``deleted_at``, refuse if another active dataset
+            # already references the same physical table. Otherwise the
+            # restore would produce two live ``SqlaTable`` rows for one
+            # physical table, breaking the logical-uniqueness contract. The
+            # shared DAO helper relies on the SoftDeleteMixin listener to
+            # consider only active rows, excludes ``existing`` itself via
+            # ``id !=``, and normalizes the catalog the same way create/update
+            # uniqueness does.
+            if DatasetDAO.has_active_logical_duplicate(existing):
+                raise ImportFailedError(
+                    "Dataset cannot be restored via re-import because another "
+                    "active dataset already references the same physical table"
+                )
+            # Restore in place (clear ``deleted_at``) rather than
+            # hard-delete-and-replace: a hard delete would cascade through the
+            # chart back-reference and the delete-orphan child relationships
+            # (table_columns, sql_metrics), which the import would then need to
+            # reconstruct.
+            #
+            # How the restore lands as an UPDATE: clearing
+            # ``existing.deleted_at`` marks the in-session row dirty and the
+            # explicit flush emits the ``deleted_at = NULL`` UPDATE before
+            # ``SqlaTable.import_from_dict`` (below) does its own query-by-uuid
+            # lookup. Without the flush we would be relying on autoflush ahead
+            # of that internal query — correct under default session config but
+            # a hidden contract; the explicit flush makes it robust. The lookup
+            # then finds the now-live row (the listener filters ``deleted_at IS
+            # NULL``) and ``import_from_dict`` applies the config as field
+            # updates on the existing object, preserving the PK. Note:
+            # ``config["id"]`` is set defensively, but
+            # ``ImportExportMixin.import_from_dict`` strips it because
+            # ``SqlaTable.export_fields`` does not contain "id"; what actually
+            # binds to the existing row is the uuid uniqueness constraint used
+            # inside ``import_from_dict``.
+            #
+            # Snapshot ``deleted_at`` first so we can roll back the clear if the
+            # downstream ``import_from_dict`` hits the legacy
+            # ``MultipleResultsFound`` fallback. Without the rollback, an
+            # ambiguous import would leave the dataset half-restored
+            # (``deleted_at = None`` but upload contents unapplied).
+            original_deleted_at = existing.deleted_at

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -200,27 +203,159 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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 user not in existing.owners and not security_manager.is_admin():
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, config["uuid"]):
+        if existing.deleted_at is not None:
+            # RESTORE path — re-importing a soft-deleted UUID is an implicit
+            # restore-with-update, a distinct operation from overwriting an
+            # alive row, so it is handled in its own branch.
+            if not can_write:
+                # Case B: don't silently return a soft-deleted row to a caller
+                # without write permission — that would let the importer
+                # reattach charts/dashboards to a deleted dataset and produce
+                # broken charts.
+                raise ImportFailedError(
+                    "Dataset was deleted and re-import requires can_write "
+                    "permission to restore it"
+                )
+            # ``user`` is None on background / example-loader paths; combined
+            # with ``can_write`` (typically from ``ignore_permissions=True``)
+            # the ownership check is intentionally skipped because the caller
+            # already established trust.
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
                 raise ImportFailedError(
-                    "A dataset already exists and user doesn't "
-                    "have permissions to overwrite it"
+                    "A dataset already exists and user doesn't have "
+                    "permissions to restore it"
                 )
-        if not overwrite or not can_write:
-            return existing
-        config["id"] = existing.id
+            # Before clearing ``deleted_at``, refuse if another active dataset
+            # already references the same physical table. Otherwise the
+            # restore would produce two live ``SqlaTable`` rows for one
+            # physical table, breaking the logical-uniqueness contract. The
+            # shared DAO helper relies on the SoftDeleteMixin listener to
+            # consider only active rows, excludes ``existing`` itself via
+            # ``id !=``, and normalizes the catalog the same way create/update
+            # uniqueness does.
+            if DatasetDAO.has_active_logical_duplicate(existing):
+                raise ImportFailedError(
+                    "Dataset cannot be restored via re-import because another "
+                    "active dataset already references the same physical table"
+                )
+            # Restore in place (clear ``deleted_at``) rather than
+            # hard-delete-and-replace: a hard delete would cascade through the
+            # chart back-reference and the delete-orphan child relationships
+            # (table_columns, sql_metrics), which the import would then need to
+            # reconstruct.
+            #
+            # How the restore lands as an UPDATE: clearing
+            # ``existing.deleted_at`` marks the in-session row dirty and the
+            # explicit flush emits the ``deleted_at = NULL`` UPDATE before
+            # ``SqlaTable.import_from_dict`` (below) does its own query-by-uuid
+            # lookup. Without the flush we would be relying on autoflush ahead
+            # of that internal query — correct under default session config but
+            # a hidden contract; the explicit flush makes it robust. The lookup
+            # then finds the now-live row (the listener filters ``deleted_at IS
+            # NULL``) and ``import_from_dict`` applies the config as field
+            # updates on the existing object, preserving the PK. Note:
+            # ``config["id"]`` is set defensively, but
+            # ``ImportExportMixin.import_from_dict`` strips it because
+            # ``SqlaTable.export_fields`` does not contain "id"; what actually
+            # binds to the existing row is the uuid uniqueness constraint used
+            # inside ``import_from_dict``.
+            #
+            # Snapshot ``deleted_at`` first so we can roll back the clear if the
+            # downstream ``import_from_dict`` hits the legacy
+            # ``MultipleResultsFound`` fallback. Without the rollback, an
+            # ambiguous import would leave the dataset half-restored
+            # (``deleted_at = None`` but upload contents unapplied).
+            original_deleted_at = existing.deleted_at
+            existing.restore()
+            db.session.flush()
+            is_soft_deleted_match = True
+            config["id"] = existing.id
+        else:
+            # OVERWRITE path — existing alive row. Without ``overwrite`` or
+            # write permission, return it unchanged (the pre-soft-delete
+            # overwrite-without-permission behaviour).
+            if not overwrite or not can_write:
+                return existing
+            if user and (
+                user not in existing.owners and not security_manager.is_admin()
+            ):
+                raise ImportFailedError(
+                    "A dataset already exists and user doesn't have "
+                    "permissions to overwrite it"
+                )
+            config["id"] = existing.id
 
     elif not can_write:
         raise ImportFailedError(
             "Dataset doesn't exist and user doesn't have permission to create datasets"
         )
+    else:
+        # Creating a brand-new dataset (no UUID match). A soft-deleted dataset
+        # may still claim this physical table; ``import_from_dict`` cannot see it
+        # (the visibility filter hides soft-deleted rows), so without this guard
+        # the import would create an active twin of a hidden dataset. The REST
+        # create path blocks the same collision via ``validate_uniqueness`` —
+        # mirror it here and direct the user to restore the existing dataset
+        # instead of leaving two rows for one physical table.
+        database = (
+            db.session.query(Database).filter_by(id=config["database_id"]).first()
+        )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError
+
+    def validate(self) -> SqlaTable:  # type: ignore[override]
+        model = super().validate()

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/daos/dataset.py:
##########
@@ -163,20 +188,45 @@ def validate_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.database_id == database.id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. 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(datasets): soft-delete and restore [superset]

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


##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog
+
+        # Same rationale as ``validate_uniqueness`` above: a soft-deleted
+        # twin must block the update rather than being silently ignored.
+        # The bypass is session-scoped, not per-query, because the EXISTS
+        # subquery pattern below leaves the inner Query's execution_options
+        # invisible to the outer execute (where the listener fires).
+        #
+        # avoid app-init regression: see ``validate_uniqueness`` above — a
+        # module-top import from ``superset.models.helpers`` raises
+        # "App not initialized yet" outside an app context (see PR #40573).
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
         )
-        return not db.session.query(dataset_query.exists()).scalar()
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            dataset_query = db.session.query(SqlaTable).filter(
+                SqlaTable.table_name == table.table,
+                SqlaTable.database_id == database.id,
+                SqlaTable.schema == table.schema,
+                DatasetDAO._catalog_identity_filter(catalog, default_catalog),
+                SqlaTable.id != dataset_id,
+            )
+            return not db.session.query(dataset_query.exists()).scalar()
+
+    @staticmethod
+    def has_active_logical_duplicate(model: SqlaTable) -> bool:
+        """Return True iff another *active* dataset shares model's physical table.
+
+        Physical identity is ``(database_id, catalog, schema, table_name)``.
+        ``model``'s catalog is normalized to the database default when unset —
+        the same rule ``validate_uniqueness``/``validate_update_uniqueness``
+        apply — so create, update, restore, and re-import agree on what counts
+        as the same physical table. Catalog matching is null-aware via
+        ``_catalog_identity_filter``: when the normalized catalog is the database
+        default, both ``catalog = default`` and ``catalog IS NULL`` rows match,
+        so a default-catalog twin is caught whichever way either row stored its
+        catalog.
+
+        Unlike ``validate_uniqueness``, this does NOT use
+        ``skip_visibility_filter``: it relies on the ``SoftDeleteMixin`` listener
+        to auto-append ``deleted_at IS NULL`` so only *active* rows match. Do not
+        add the bypass here — it would broaden the check to soft-deleted rows and
+        silently refuse legitimate restores. ``id != model.id`` excludes the row
+        itself.
+
+        Assumes an active app context and a session-attached ``model`` so
+        ``db.session`` and the lazy ``model.database`` relationship resolve.
+        """
+        # The catalog might not be set even if the database supports catalogs,
+        # in case multi-catalog is disabled.
+        default_catalog = model.database.get_default_catalog()
+        catalog = model.catalog or default_catalog

Review Comment:
   Test-scaffolding duplication noted; the setup blocks intentionally stay local to each test for readability (per the avoid-nesting-when-testing convention this suite follows). Declining as style.



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    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 — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    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 datasets they own. ``any()`` emits
+        # an EXISTS subquery so it composes with the base access filter without
+        # producing duplicate rows from a join.
+        owned = SqlaTable.owners.any(security_manager.user_model.id == get_user_id())

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/datasets/api.py:
##########
@@ -87,25 +94,40 @@
     statsd_metrics,
 )
 from superset.views.error_handling import handle_api_exception
-from superset.views.filters import BaseFilterRelatedUsers, FilterRelatedOwners
+from superset.views.filters import (
+    BaseFilterRelatedUsers,
+    FilterRelatedOwners,
+    SoftDeleteApiMixin,
+)
 
 logger = logging.getLogger(__name__)
 
 
-class DatasetRestApi(BaseSupersetModelRestApi):
+class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
     datamodel = SQLAInterface(SqlaTable)
     base_filters = [["id", DatasourceFilter, lambda: []]]
 
     resource_name = "dataset"
     allow_browser_login = True
     class_permission_name = "Dataset"
-    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_Dataset``) 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 — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,54 @@
+# 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 tables for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``tables`` table to support soft deletion of datasets. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 3a8e6f2c1b95
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:10: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 = "3a8e6f2c1b95"
+down_revision = "78a40c08b4be"

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,54 @@
+# 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 tables for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``tables`` table to support soft deletion of datasets. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 3a8e6f2c1b95
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:10: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 = "3a8e6f2c1b95"
+down_revision = "78a40c08b4be"
+
+TABLE_NAME = "tables"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/security/manager.py:
##########
@@ -2344,11 +2347,16 @@ def _update_vm_datasources_access(  # pylint: disable=too-many-locals
         sqlatable_table = SqlaTable.__table__  # pylint: disable=no-member
         chart_table = Slice.__table__  # pylint: disable=no-member
         new_database_name = target.database_name
-        datasets = (
-            self.session.query(SqlaTable)
-            .filter(SqlaTable.database_id == target.id)
-            .all()
-        )
+        # Bypass the soft-delete visibility filter: a soft-deleted dataset's perm
+        # strings (and its charts') must still be rewritten on a database rename,
+        # otherwise restoring that dataset later brings back stale dataset/schema/
+        # catalog permission strings referencing the old database name.
+        with skip_visibility_filter(self.session, SqlaTable):
+            datasets = (
+                self.session.query(SqlaTable)
+                .filter(SqlaTable.database_id == target.id)
+                .all()
+            )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +37,29 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete.
+    #
+    # Match rows whose catalog is either unset (NULL) or the database
+    # default — these are "the same physical table" the way
+    # ``DatasetDAO.validate_uniqueness`` treats them (``table.catalog or
+    # default``). Example rows are seeded with ``catalog = NULL`` while a
+    # connection that reports a default catalog (e.g. Postgres) would
+    # normalize to that default, so both must qualify. This still excludes
+    # an unrelated third catalog variant of the same table_name. Within the
+    # matched set, prefer live rows over soft-deleted ones via
+    # ``ORDER BY deleted_at IS NULL DESC``.
+    catalog = database.get_default_catalog()

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510302018


##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,54 @@
+# 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 tables for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``tables`` table to support soft deletion of datasets. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 3a8e6f2c1b95
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:10: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 = "3a8e6f2c1b95"
+down_revision = "78a40c08b4be"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Avoid flagging missing explicit type annotations for Alembic revision metadata variables in migration scripts when the types are obvious from context; keep this relaxed in one-time migration files.
   
   **Applied to:**
     - `**/migration*/**`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    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:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for clearly derived local variables in Python when the type is unambiguous from context, including local/test-scaffolding variables.
   
   **Applied to:**
     - `**/*.py`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()

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



##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,54 @@
+# 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 tables for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``tables`` table to support soft deletion of datasets. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 3a8e6f2c1b95
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:10: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 = "3a8e6f2c1b95"
+down_revision = "78a40c08b4be"
+
+TABLE_NAME = "tables"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit type annotations for obvious module-level string constants in Alembic migration files when the types are already unambiguous and the annotations would add noise.
   
   **Applied to:**
     - `**/migration*/**`
   
   ---
   💡 *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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510302983


##########
superset/translations/ar/LC_MESSAGES/messages.po:
##########
@@ -4697,6 +4697,9 @@ msgstr "تعذر إنشاء مجموعة بيانات."
 msgid "Dataset could not be duplicated."
 msgstr "تعذر تكرار مجموعة البيانات."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate as it ensures that all user-facing error messages are translated, maintaining consistency with the existing localization practices in the project. Applying this change improves the user experience for Arabic-speaking users by providing a clear error message instead of falling back to English text.
   
   **superset/translations/ar/LC_MESSAGES/messages.po**
   ```
   msgid "Dataset 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3530097204


##########
superset/commands/database/exceptions.py:
##########
@@ -156,6 +178,21 @@ class DatabaseDeleteDatasetsExistFailedError(DeleteFailedError):
     message = _("Cannot delete a database that has datasets attached")
 
 
+class DatabaseDeleteSoftDeletedDatasetsExistFailedError(
+    DatabaseDeleteDatasetsExistFailedError
+):
+    # Subclasses the live-datasets error so the existing API handler catches
+    # both; only the message differs, telling the operator that the blockers
+    # are hidden (soft-deleted) rows even though their dataset list looks empty.
+    message = _(
+        "Cannot delete a database whose only remaining datasets are "
+        "soft-deleted. Restore them (POST /api/v1/dataset/<uuid>/restore) "
+        "and delete them permanently once a purge capability ships, or "
+        "remove the underlying rows out-of-band, before deleting the "
+        "database."
+    )

Review Comment:
   **Suggestion:** Add an explicit type annotation for the new class-level `message` attribute so newly introduced variables in modified Python code remain type-hinted. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new class introduces a class-level `message` attribute without a type annotation. Since the custom rule requires type hints on newly added Python variables that can be annotated, this is a real rule violation in the 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=7797f17c161c415fb3448505e87d44ec&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=7797f17c161c415fb3448505e87d44ec&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/database/exceptions.py
   **Line:** 187:193
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for the new class-level `message` attribute so newly introduced variables in modified Python code remain type-hinted.
   
   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%2F40130&comment_hash=2ebf6014d4fc16451198ed4225974d360ef2f5e9c1a9f40119829db4b8975f70&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=2ebf6014d4fc16451198ed4225974d360ef2f5e9c1a9f40119829db4b8975f70&reaction=dislike'>👎</a>



##########
superset/views/base.py:
##########
@@ -769,7 +770,23 @@ def apply(self, query: Query, value: Any) -> Query:
             models.Database,
             models.Database.id == self.model.database_id,
         )
-        return query.filter(get_dataset_access_filters(self.model))
+        access_filter = get_dataset_access_filters(self.model)
+        # Owners keep sight of their own soft-deleted rows regardless of
+        # datasource grants: ``raise_for_access`` counts ownership as
+        # datasource access, and the restore audience is owners/admins.
+        # The leg is inert for live rows (``deleted_at IS NULL`` fails it)
+        # and only ever matters when a deleted-state rison filter has opted
+        # the request in to seeing soft-deleted rows — without that session
+        # bypass, no soft-deleted row reaches this query at all.
+        deleted_at = getattr(self.model, "deleted_at", None)
+        owners = getattr(self.model, "owners", None)
+        if deleted_at is not None and owners is not None:
+            owned_trash = and_(
+                deleted_at.is_not(None),
+                owners.any(security_manager.user_model.id == utils.get_user_id()),

Review Comment:
   **Suggestion:** Add explicit type annotations for the newly introduced local SQLAlchemy expression variables to satisfy the type-hint requirement for relevant new variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new code introduces several local variables without type annotations in a Python file. This matches the rule requiring type hints for newly added relevant variables that can be annotated, so the suggestion 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=84f88e930c3f4d5cabacdd02ff351aac&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=84f88e930c3f4d5cabacdd02ff351aac&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/views/base.py
   **Line:** 773:786
   **Comment:**
   	*Custom Rule: Add explicit type annotations for the newly introduced local SQLAlchemy expression variables to satisfy the type-hint requirement for relevant new 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%2F40130&comment_hash=9e1e3726c6591e7bafb67e928fe04d7657aaa7736b377e845ada622b8898c200&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=9e1e3726c6591e7bafb67e928fe04d7657aaa7736b377e845ada622b8898c200&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(datasets): soft-delete and restore [superset]

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

   Follow-up on the CI failure: pushed c4560c1b39 to fix it. The honest read is that I introduced a test whose premise the DB constraint contradicts.
   
   **What was failing:** `test_restore_blocked_by_active_logical_duplicate` was hitting `IntegrityError: UNIQUE constraint failed` (SQLite) / `_customer_location_uc` violation (Postgres) at the `db.session.commit()` that tried to seed the active twin while the original was soft-deleted.
   
   **Root cause:** the `tables` table carries two DB-level unique constraints on the logical identity:
   
   1. `UniqueConstraint("database_id", "catalog", "schema", "table_name")` declared in the `SqlaTable` model.
   2. The legacy `_customer_location_uc` on `(database_id, schema, table_name)` from the 2016 `b4456560d4f3` migration — still present in test DBs (the 2024 `df3d7e2eb9a4` removal migration runs only on a fresh upgrade chain).
   
   Either constraint rejects the twin insert before the application-level restore check can be exercised. The "two live datasets pointing at the same physical table" scenario the test was written for is unreachable in practice — the DB stops step 2 (the create) with an IntegrityError before step 3 (the restore) ever runs.
   
   **What this means for the original review concerns:**
   
   @richardfogaca's `api.py:963` concern and @aminghadersohi's matching HIGH at `restore.py:46` were about the *application layer* `validate_uniqueness` being filtered by the SoftDeleteMixin listener — which they were, before the fix. The DB-level constraint masks this in production today: the create returns an opaque 500 IntegrityError instead of a clean 422.
   
   The application-level fixes are kept as defense-in-depth and still pay off — they convert the 500 to a clean 422:
   
   - `DatasetDAO.validate_uniqueness` / `validate_update_uniqueness` use `execution_options(SKIP_VISIBILITY_FILTER_CLASSES={SqlaTable})` so the create path returns 422. Exercised end-to-end by the surviving `test_create_blocked_by_soft_deleted_logical_duplicate`.
   - `RestoreDatasetCommand._has_active_logical_duplicate` is retained for symmetry — fires cleanly if the DB constraint is ever relaxed (it has been removed once before via `df3d7e2eb9a4`, so it's not theoretical).
   - Unit coverage of the restore-side check is preserved in `tests/unit_tests/commands/dataset/restore_test.py::test_restore_dataset_logical_duplicate_raises` (mocked).
   
   The deleted integration test is replaced with a comment block at the same location explaining why it's unreachable, so the next contributor doesn't re-introduce it.
   
   Sorry for the noise.


-- 
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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510299550


##########
superset/translations/mi/LC_MESSAGES/messages.po:
##########
@@ -4618,6 +4618,9 @@ msgstr "Kāore i taea te hanga i te rārangi raraunga."
 msgid "Dataset could not be duplicated."
 msgstr "Kāore i taea te tārua i te rārangi raraunga."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate because it maintains consistency with the existing Maori localization pattern used for other dataset error messages in the file. Providing a translation instead of an empty string ensures that users receive localized feedback when a restoration operation fails, rather than falling back to the source text.
   
   **superset/translations/mi/LC_MESSAGES/messages.po**
   ```
   msgid "Dataset could not be restored."
   -msgstr ""
   +msgstr "Kāore i taea te whakaora i te rārangi raraunga."
   ```



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

Review Comment:
   <!-- Bito Reply -->
   The suggestion is appropriate as it provides a missing Finnish translation for a dataset error message, ensuring consistency with other similar error messages in the file. Applying this change improves the user experience by providing a localized message instead of falling back to English.
   
   **superset/translations/fi/LC_MESSAGES/messages.po**
   ```
   8226: -msgstr ""
    8226:+msgstr "Tietojoukkoa ei voitu palauttaa."
   ```



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)

Review Comment:
   <!-- Bito Reply -->
   The decision to maintain the current implementation is appropriate. These helpers are scoped as internal test scaffolding, and adhering to the existing style conventions of the test suite is a reasonable approach for this context.



##########
superset/translations/ko/LC_MESSAGES/messages.po:
##########
@@ -4578,6 +4578,9 @@ msgstr ""
 msgid "Dataset could not be duplicated."
 msgstr "데이터베이스를 업데이트할 수 없습니다."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion to add a Korean translation for the error message is appropriate. Providing localized error messages ensures consistency across the user interface, as other similar error messages in the same group already include Korean translations.
   
   **superset/translations/ko/LC_MESSAGES/messages.po**
   ```
   +msgid "Dataset 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3501258471


##########
superset/translations/it/LC_MESSAGES/messages.po:
##########
@@ -4602,6 +4602,9 @@ msgstr "La tua query non può essere salvata"
 msgid "Dataset could not be duplicated."
 msgstr "La tua query non può essere salvata"
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Italian translation</b></div>
   <div id="fix">
   
   The Italian translation (`msgstr`) is empty. Italian-speaking users will see the untranslated English text 'Dataset could not be restored.' when this error occurs in the UI. Comparing with similar error messages in this file (e.g., lines 4598-4609), the established pattern uses Italian translations such as 'La tua query non può essere salvata'. Please provide a semantically appropriate Italian translation for this new error message.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #bacad8</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:
##########
@@ -4634,6 +4634,9 @@ msgstr "گزارش نمی‌تواند ایجاد شود."
 msgid "Dataset could not be duplicated."
 msgstr "مجموعه داده نمی‌تواند تکرار شود."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Persian translation</b></div>
   <div id="fix">
   
   The newly added `msgid "Dataset could not be restored."` has an empty `msgstr ""`, causing the English message to display to Persian-speaking users. Similar dataset error messages (lines 4635, 4641) have proper Persian translations. Provide a translation using the established pattern for consistency.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #bacad8</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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3509988346


##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]
+
             yield datasets
 
-            # rollback changes
-            for dataset in datasets:
-                state = inspect(dataset)
-                if not state.was_deleted:
-                    db.session.delete(dataset)
+            # rollback changes (including soft-deleted rows)
+            for dataset_id in dataset_ids:
+                row = (
+                    db.session.query(SqlaTable)
+                    .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                    .filter(SqlaTable.id == dataset_id)
+                    .one_or_none()
+                )

Review Comment:
   **Suggestion:** Add a type annotation for this new query-result variable to make the optional model type explicit. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This query result variable is newly added and left unannotated. Since it can be annotated as an optional SqlaTable, the suggestion identifies a real type-hint 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=d4f267bae7de4570a3b793df92cb4fd1&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=d4f267bae7de4570a3b793df92cb4fd1&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/datasets/api_tests.py
   **Line:** 216:221
   **Comment:**
   	*Custom Rule: Add a type annotation for this new query-result variable to make the optional model type explicit.
   
   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%2F40130&comment_hash=e21edee2539058310422560962730383220c267a2dffe622dbe0ee387ef45967&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=e21edee2539058310422560962730383220c267a2dffe622dbe0ee387ef45967&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]
+
             yield datasets
 
-            # rollback changes
-            for dataset in datasets:
-                state = inspect(dataset)
-                if not state.was_deleted:
-                    db.session.delete(dataset)
+            # rollback changes (including soft-deleted rows)
+            for dataset_id in dataset_ids:

Review Comment:
   **Suggestion:** Annotate this new scalar identifier variable with its expected primitive type. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a new scalar local variable introduced in modified code and it lacks an explicit annotation. It falls under the type-hint requirement.
   </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=7105fb078baa485ba13ea639bbeddbe4&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=7105fb078baa485ba13ea639bbeddbe4&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/datasets/api_tests.py
   **Line:** 215:215
   **Comment:**
   	*Custom Rule: Annotate this new scalar identifier variable with its expected primitive type.
   
   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%2F40130&comment_hash=e4a068b9683006f7a710fcd1c601609c775ed497cce1f28b7dd7a2f1377e0243&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=e4a068b9683006f7a710fcd1c601609c775ed497cce1f28b7dd7a2f1377e0243&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()

Review Comment:
   **Suggestion:** Add a type annotation to this local mock variable. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The variable is newly introduced in test code and is unannotated despite being annotatable (for example, `dataset: MagicMock = MagicMock()`). This matches the type-hints rule for relevant 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=4bcff6d630f94c289a33af93789ba2fa&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=4bcff6d630f94c289a33af93789ba2fa&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/dataset/restore_test.py
   **Line:** 38:38
   **Comment:**
   	*Custom Rule: Add a type annotation to this local mock 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%2F40130&comment_hash=ace0c80fd7aeceb36eabeadd889f9d7de215b16eb68a393d02d1e2a6840dcac8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=ace0c80fd7aeceb36eabeadd889f9d7de215b16eb68a393d02d1e2a6840dcac8&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/databases/sync_permissions_test.py:
##########
@@ -409,3 +409,49 @@ def test_sync_permissions_command_rename_db_in_perms(
     assert (
         mock_chart.schema_perm == f"[{database_with_catalog.name}].[catalog1].[schema1]"
     )
+
+
+def test_sync_permissions_command_rename_bypasses_visibility_filter(
+    mocker: MockerFixture, database_with_catalog: MagicMock
+):

Review Comment:
   **Suggestion:** Add an explicit return type annotation to this new test function signature. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python function and it omits an explicit return type annotation. The custom rule requires type hints on new or modified Python functions when they can be annotated, 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=79b9c1daa1e749fcb7edc8f3754033ca&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=79b9c1daa1e749fcb7edc8f3754033ca&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/databases/sync_permissions_test.py
   **Line:** 414:416
   **Comment:**
   	*Custom Rule: Add an explicit return type annotation to this new test function signature.
   
   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%2F40130&comment_hash=2b8a11165fe13518da2e8e8f7ac6cde4624ba001348ac2494f2e8c996b726d39&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=2b8a11165fe13518da2e8e8f7ac6cde4624ba001348ac2494f2e8c996b726d39&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/databases/sync_permissions_test.py:
##########
@@ -409,3 +409,49 @@ def test_sync_permissions_command_rename_db_in_perms(
     assert (
         mock_chart.schema_perm == f"[{database_with_catalog.name}].[catalog1].[schema1]"
     )
+
+
+def test_sync_permissions_command_rename_bypasses_visibility_filter(
+    mocker: MockerFixture, database_with_catalog: MagicMock
+):
+    """The dataset/chart perm rewrite must run with the soft-delete
+    visibility filter bypassed for ``SqlaTable`` and ``Slice``.
+
+    A soft-deleted dataset's ``schema_perm``/``catalog_perm`` (and its
+    charts') must still be rewritten on a database rename; without the
+    bypass, the listener hides those rows from ``get_datasets`` and a
+    later restore resurrects stale perm strings referencing the old
+    database name — matchable by a ``schema_access`` grant on a new
+    database reusing that name.
+    """
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+    from superset.models.slice import Slice
+
+    mocker.patch(
+        "superset.commands.database.sync_permissions."
+        "security_manager.find_permission_view_menu",
+        return_value=None,
+    )
+    observed_bypass: list[set[type]] = []
+
+    def capture_bypass(*args, **kwargs):
+        observed_bypass.append(
+            set(db.session.info.get(SKIP_VISIBILITY_FILTER_CLASSES, set()))
+        )
+        return []
+

Review Comment:
   **Suggestion:** Add type annotations for this nested helper function parameters and return type. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This nested helper function is newly introduced and has neither parameter type annotations nor a return type annotation. That violates the type-hint requirement for new Python code 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=2203c311d415410eaf6459674d107a43&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=2203c311d415410eaf6459674d107a43&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/databases/sync_permissions_test.py
   **Line:** 438:443
   **Comment:**
   	*Custom Rule: Add type annotations for this nested helper function parameters and return type.
   
   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%2F40130&comment_hash=fb9fdf21c2865daccf12485d97627a44ce52f02ec346bdd88c46de4d0643e242&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=fb9fdf21c2865daccf12485d97627a44ce52f02ec346bdd88c46de4d0643e242&reaction=dislike'>👎</a>



##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog
+
+        # Same rationale as ``validate_uniqueness`` above: a soft-deleted
+        # twin must block the update rather than being silently ignored.
+        # The bypass is session-scoped, not per-query, because the EXISTS
+        # subquery pattern below leaves the inner Query's execution_options
+        # invisible to the outer execute (where the listener fires).
+        #
+        # avoid app-init regression: see ``validate_uniqueness`` above — a
+        # module-top import from ``superset.models.helpers`` raises
+        # "App not initialized yet" outside an app context (see PR #40573).
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
         )
-        return not db.session.query(dataset_query.exists()).scalar()
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            dataset_query = db.session.query(SqlaTable).filter(

Review Comment:
   **Suggestion:** Add an explicit type annotation for this query variable so the modified method includes complete type hints. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is another newly added unannotated local query variable in a modified Python method, so it matches the type-hint requirement for annotatable locals.
   </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=6fa5f4a2dd8a4dd88a68bb4fb8b83708&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=6fa5f4a2dd8a4dd88a68bb4fb8b83708&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/dataset.py
   **Line:** 256:256
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this query variable so the modified method includes complete type hints.
   
   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%2F40130&comment_hash=309ab9998c7d93d087af3c27f870ebe78cbaa5e087a416b24bebddc2155f6409&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=309ab9998c7d93d087af3c27f870ebe78cbaa5e087a416b24bebddc2155f6409&reaction=dislike'>👎</a>



##########
superset/daos/dataset.py:
##########
@@ -163,20 +188,45 @@ def validate_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.database_id == database.id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog
+
+        # Bypass the soft-delete visibility filter so a soft-deleted row with
+        # the same physical identity still blocks the create. Otherwise a
+        # delete-then-create-then-restore sequence could produce two live
+        # datasets pointing at the same physical table.
+        #
+        # The bypass MUST be session-scoped, not per-query. The
+        # ``db.session.query(dataset_query.exists()).scalar()`` pattern below
+        # builds an OUTER query whose ``execution_options`` are independent
+        # of the inner ``dataset_query`` — the listener fires on the outer
+        # execute and would attach ``deleted_at IS NULL`` to all SqlaTable
+        # references in the statement (including inside the EXISTS
+        # subquery) via ``with_loader_criteria(include_aliases=True)``.
+        # A per-query option on the inner query never reaches that listener.
+        #
+        # avoid app-init regression: a module-top import from
+        # ``superset.models.helpers`` eagerly loads ``core.py``, whose model
+        # classes evaluate ``encrypted_field_factory.create(...)`` at
+        # class-definition time and raise "App not initialized yet" when no
+        # Flask app context exists (see PR #40573).
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
         )
 
-        if dataset_id:
-            # make sure the dataset found is different from the target (if any)
-            dataset_query = dataset_query.filter(SqlaTable.id != dataset_id)
+        with skip_visibility_filter(db.session, SqlaTable):
+            dataset_query = db.session.query(SqlaTable).filter(

Review Comment:
   **Suggestion:** Add an explicit type annotation for this query variable to satisfy the type-hint requirement for relevant local variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The modified method introduces a new local `dataset_query` without any type annotation, and this variable is a relevant query local 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=5c94b294c3d341c5885acbcc1b174efb&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=5c94b294c3d341c5885acbcc1b174efb&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/dataset.py
   **Line:** 218:218
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this query variable to satisfy 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%2F40130&comment_hash=c04555b42ae7ecc1314c74f0152bdd042a130049cb23050b94b1e844fd8cb17b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=c04555b42ae7ecc1314c74f0152bdd042a130049cb23050b94b1e844fd8cb17b&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510006852


##########
superset/datasets/api.py:
##########
@@ -59,7 +62,11 @@
 from superset.daos.dashboard import DashboardDAO
 from superset.daos.dataset import DatasetDAO
 from superset.databases.filters import DatabaseFilter

Review Comment:
   **Suggestion:** This API documentation states deletion is always a soft delete, but the actual delete path is feature-flagged and can still hard-delete when `SOFT_DELETE` is disabled, so the description is factually incorrect. Update the docs to reflect the conditional behavior (or remove the unconditional claim) to avoid a contract mismatch for clients/operators. [comment mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Docs misrepresent destructive delete as recoverable soft delete.
   - ⚠️ Operators may assume restores work and lose datasets.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Ensure the `SOFT_DELETE` feature flag is disabled in configuration so
   `is_feature_enabled("SOFT_DELETE")` returns `False`. The flag gate is checked in
   `_should_attach_soft_delete_criteria` in `superset/models/helpers.py:23-32` and in
   `BaseDAO.delete` in `superset/daos/base.py:18-29, 520-29, where
   `is_feature_enabled("SOFT_DELETE")` controls whether soft or hard delete is used.
   
   2. Call the dataset deletion endpoint `DELETE /api/v1/dataset/<pk>`, which is implemented
   by `DatasetRestApi.delete` in `superset/datasets/api.py:47-92`. That method’s OpenAPI
   block documents: `summary: Delete a dataset (soft delete; recoverable via restore)` (line
   64) and the docstring explains that the dataset is “soft-deleted” and “recoverable via
   POST /api/v1/dataset/<uuid>/restore”.
   
   3. The `delete` method invokes `DeleteDatasetCommand([pk]).run()`
   (superset/commands/dataset/delete.py:41-45). `DeleteDatasetCommand.run` validates the
   models via `DatasetDAO.find_by_ids(self._model_ids)` and then calls
   `DatasetDAO.delete(self._models)`, which uses the inherited `BaseDAO.delete`
   implementation in `superset/daos/base.py:6-29, 520-29`.
   
   4. In `BaseDAO.delete`, because `cls.model_cls` is `SqlaTable` (bound by `DatasetDAO` at
   superset/daos/dataset.py:52-59) and `issubclass(cls.model_cls, SoftDeleteMixin)` is true
   but `is_feature_enabled("SOFT_DELETE")` is false, the conditional at base.py:22-29 falls
   into the `else` branch and calls `cls.hard_delete(items)`. `hard_delete` (base.py:247-259)
   loops over items and calls `db.session.delete(item)` for each dataset row, permanently
   removing them from the database instead of setting `deleted_at` for soft delete.
   
   5. After this hard deletion, a client following the documented contract and calling `POST
   /api/v1/dataset/<uuid>/restore` (implemented by `DatasetRestApi.restore` in
   `superset/datasets/api.py:511-553`) receives a 404 (`DatasetNotFoundError` at
   restore.py:552-555) because the dataset row no longer exists. This demonstrates that, when
   `SOFT_DELETE` is disabled, the runtime behavior is hard delete while the API documentation
   on line 64 still claims a soft delete “recoverable via restore”, creating a factual
   mismatch between docs and behavior.
   ```
   </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=b1aeb7fff60e42eba43aae19879a5074&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=b1aeb7fff60e42eba43aae19879a5074&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/datasets/api.py
   **Line:** 64:64
   **Comment:**
   	*Comment Mismatch: This API documentation states deletion is always a soft delete, but the actual delete path is feature-flagged and can still hard-delete when `SOFT_DELETE` is disabled, so the description is factually incorrect. Update the docs to reflect the conditional behavior (or remove the unconditional claim) to avoid a contract mismatch for clients/operators.
   
   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%2F40130&comment_hash=8f955cfb0dc2c29bd89bd159b6cee881a5012d30c0a703067cfff637f3f411a1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=8f955cfb0dc2c29bd89bd159b6cee881a5012d30c0a703067cfff637f3f411a1&reaction=dislike'>👎</a>



##########
superset/connectors/sqla/models.py:
##########
@@ -1303,6 +1304,7 @@ def data(self) -> dict[str, Any]:
 
 class SqlaTable(
     CoreDataset,
+    SoftDeleteMixin,
     BaseDatasource,
     ExploreMixin,
 ):  # pylint: disable=too-many-public-methods

Review Comment:
   **Suggestion:** `SoftDeleteMixin` is placed after `CoreDataset` in the base-class list, which can prevent `SoftDeleteMixin.__init_subclass__()` from running in Python's MRO unless earlier bases cooperatively call `super()`. If registration is skipped, `SqlaTable` won’t be added to the soft-delete subclass registry, so the global visibility listener won’t auto-filter `deleted_at` rows and soft-deleted datasets can still appear in normal queries. Make `SoftDeleteMixin` the first base (or otherwise guarantee its `__init_subclass__` runs) so dataset soft-delete filtering is actually enforced. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Soft-deleted datasets still appear in dataset list API.
   - ⚠️ Deleted datasets continue to surface in related-object lookups.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Soft-delete a dataset via `DELETE /api/v1/dataset/<pk>`, which is implemented by
   `DatasetRestApi.delete` in `superset/datasets/api.py:47-92` and calls
   `DeleteDatasetCommand([pk]).run()` (superset/commands/dataset/delete.py:41-45), ultimately
   routing to `DatasetDAO.delete()` which delegates to `BaseDAO.delete()`
   (superset/daos/base.py:6-29, 520-29). With `SOFT_DELETE` enabled, `BaseDAO.delete` detects
   `SqlaTable` as a `SoftDeleteMixin` subclass and calls `soft_delete()`, setting
   `deleted_at` on the dataset row.
   
   2. Global soft-delete visibility is enforced by `_add_soft_delete_filter` in
   `superset/models/helpers.py:52-123`, which is registered as a `do_orm_execute` listener
   and, when `is_feature_enabled("SOFT_DELETE")` is true
   (`_should_attach_soft_delete_criteria` in helpers.py:2-32), iterates
   `_all_soft_delete_subclasses()` (helpers.py:35-49) to attach `with_loader_criteria(cls,
   lambda c: c.deleted_at.is_(None), include_aliases=True)` for each registered
   `SoftDeleteMixin` subclass.
   
   3. The subclass registry used by `_all_soft_delete_subclasses()` is populated exclusively
   via `SoftDeleteMixin.__init_subclass__` in `superset/models/helpers.py:194-203`, which
   appends each concrete subclass to `SoftDeleteMixin._registered_subclasses` when
   `__init_subclass__` runs. For `SqlaTable`, declared as `class SqlaTable(CoreDataset,
   SoftDeleteMixin, BaseDatasource, ExploreMixin)` in
   `superset/connectors/sqla/models.py:106-111`, Python resolves `__init_subclass__` via the
   MRO: if the leftmost external base `CoreDataset` (imported from
   `superset_core.common.models.Dataset` at models.py:71) defines its own `__init_subclass__`
   and does not call `super().__init_subclass__`, `SoftDeleteMixin.__init_subclass__` is
   never invoked, leaving `SqlaTable` absent from `_registered_subclasses`.
   
   4. Once `SOFT_DELETE` is enabled, repeat a dataset listing call such as `GET
   /api/v1/dataset/` (handled by `DatasetRestApi` in `superset/datasets/api.py`, which uses
   `SQLAInterface(SqlaTable)` and the global ORM session). Because `_add_soft_delete_filter`
   only filters classes present in `SoftDeleteMixin._registered_subclasses`, a missing
   `SqlaTable` entry means no `deleted_at IS NULL` criterion is attached for this model, and
   soft-deleted dataset rows (with `deleted_at` set by `soft_delete()`) continue to appear in
   normal queries and list results despite having been “deleted”. This reproduction path
   depends on the non-cooperative `__init_subclass__` implementation in `CoreDataset`, which
   is defined in the external `superset_core.common.models` module and therefore not visible
   in this repo, but the infrastructure code here shows that such an implementation would
   bypass registration for any `SoftDeleteMixin` placed after it in the base list.
   ```
   </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=3aa4c1ad7e274410814ebf666ebd5b05&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=3aa4c1ad7e274410814ebf666ebd5b05&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/connectors/sqla/models.py
   **Line:** 1305:1310
   **Comment:**
   	*Logic Error: `SoftDeleteMixin` is placed after `CoreDataset` in the base-class list, which can prevent `SoftDeleteMixin.__init_subclass__()` from running in Python's MRO unless earlier bases cooperatively call `super()`. If registration is skipped, `SqlaTable` won’t be added to the soft-delete subclass registry, so the global visibility listener won’t auto-filter `deleted_at` rows and soft-deleted datasets can still appear in normal queries. Make `SoftDeleteMixin` the first base (or otherwise guarantee its `__init_subclass__` runs) so dataset soft-delete filtering is actually enforced.
   
   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%2F40130&comment_hash=597a234fa2b3ea0b6a99483ae543aa2221ef831452f86003716b39f6e88be3a3&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=597a234fa2b3ea0b6a99483ae543aa2221ef831452f86003716b39f6e88be3a3&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3509989797


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -37,7 +37,10 @@
     MultiCatalogDisabledValidationError,

Review Comment:
   **Suggestion:** Add a concrete type annotation for this rollback snapshot variable (nullable datetime) to satisfy the typing rule for relevant new variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added variable capturing a nullable datetime value and it is left unannotated. The rule requires type hints on relevant variables that can be annotated, 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=885ed587722e43bc80fc70a78d6c2ff9&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=885ed587722e43bc80fc70a78d6c2ff9&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/dataset/importers/v1/utils.py
   **Line:** 37:37
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for this rollback snapshot variable (nullable datetime) to satisfy the typing rule for relevant new 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%2F40130&comment_hash=5d2248ceee1f6971e428aed504596c2f14fd2c22e9c11c604ef27c3852a73b02&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=5d2248ceee1f6971e428aed504596c2f14fd2c22e9c11c604ef27c3852a73b02&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(datasets): soft-delete and restore [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3365394144


##########
superset/translations/fr/LC_MESSAGES/messages.po:
##########
@@ -4688,6 +4688,9 @@ msgstr "L’ensemble de données n'a pas pu être créé."
 msgid "Dataset could not be duplicated."
 msgstr "L’ensemble de données n'a pas pu être dupliqué."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing French translation</b></div>
   <div id="fix">
   
   The `msgstr` field is empty. French users will see the untranslated English error message. Based on the established translation pattern in this file (e.g., "Dataset could not be duplicated." → "L'ensemble de données n'a pas pu être dupliqué."), the correct translation should be "L'ensemble de données n'a pas pu être restauré.".
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #dfa400</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/sl/LC_MESSAGES/messages.po:
##########
@@ -4687,6 +4687,9 @@ msgstr "Podatkovnega niza ni mogoče ustvariti."
 msgid "Dataset could not be duplicated."
 msgstr "Podatkovnega niza ni mogoče duplicirati."
 
+msgid "Dataset 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. Slovenian-speaking users will see the untranslated English error message 'Dataset could not be restored.' instead of a localized message. Provide the Slovenian translation to ensure consistent user experience.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #dfa400</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/ja/LC_MESSAGES/messages.po:
##########
@@ -4329,6 +4329,9 @@ msgstr "データセットを作成できませんでした。"
 msgid "Dataset could not be duplicated."
 msgstr "データセットを複製できませんでした。"
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Japanese translation</b></div>
   <div id="fix">
   
   The new `msgid "Dataset could not be restored."` entry has an empty `msgstr ""` in the Japanese locale. Japanese-speaking users will see the untranslated English error message instead of a localized string. All other "Dataset could not be X" messages in this file have proper Japanese translations (lines 4327, 4330, 4336).
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #dfa400</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:
##########
@@ -4664,6 +4664,9 @@ msgstr "Não foi possível gravar a sua query"
 msgid "Dataset could not be duplicated."
 msgstr "Não foi possível gravar a sua query"
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Portuguese translation</b></div>
   <div id="fix">
   
   The `msgstr` field is empty, so Portuguese users will see untranslated English text when this error occurs. Provide a Portuguese translation consistent with the pattern used for similar messages (e.g., 'Não foi possível gravar a sua query').
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #dfa400</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:
##########
@@ -4720,6 +4720,9 @@ msgstr "Dataset kon niet worden aangemaakt."
 msgid "Dataset could not be duplicated."
 msgstr "Dataset kon niet worden gedupliceerd."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Dutch translation</b></div>
   <div id="fix">
   
   The `msgstr` field is empty, so Dutch-speaking users will see untranslated English text. Following the established pattern for similar messages (e.g., "Dataset could not be duplicated." → "Dataset kon niet worden gedupliceerd."), the translation should be "Dataset kon niet worden hersteld.".
   </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
    +++ superset/translations/nl/LC_MESSAGES/messages.po
    @@ -4721,7 +4721,7 @@ msgstr "Dataset kon niet worden gedupliceerd."
    
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "Dataset kon niet worden hersteld."
    
     msgid "Dataset could not be updated."
     msgstr "Dataset kon niet worden bijgewerkt."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #dfa400</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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3397364969


##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,454 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+

Review Comment:
   **Suggestion:** This test creates a database and dataset but does not wrap cleanup in a `finally` block. If any assertion fails before the last line, the created rows remain in the shared test DB and can make later tests fail unpredictably. Move `_hard_delete_created(...)` into a `finally` block so teardown always runs. [missing cleanup]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Failed test leaves extra database and dataset in fixtures.
   - ⚠️ Later integration tests run against polluted dataset state.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Run `TestDatasetSoftDelete.test_deleted_state_list_shows_owner_their_own_deleted` in
   `tests/integration_tests/datasets/soft_delete_tests.py:164-193`.
   
   2. The test creates a `Database` named `"sd_owner_db"` and a `SqlaTable` `"sd_owner_tbl"`
   owned by Alpha, then marks it soft-deleted by setting `dataset.deleted_at` and committing
   (lines 20-31 in the same file).
   
   3. The test logs in as `ALPHA_USERNAME` and calls `GET
   /api/v1/dataset/?q=...dataset_deleted_state=value:only` (lines 33-37), then asserts a 200
   status and that `dataset_id` appears in the result (lines 38-40). If the deleted-state
   filter logic regresses so the dataset is missing or the status is not 200, one of these
   assertions raises, aborting the test before line 42.
   
   4. Because `_hard_delete_created(dataset_id, database)` (line 42) is not in a
   `try/finally`, the failure path leaves both the `sd_owner_db` `Database` row and its
   soft-deleted `SqlaTable` row in the shared SQLAlchemy session for the remainder of the
   test run, instead of reliably cleaning them up as `_hard_delete_created` is designed to do
   (lines 2-13).
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0ac16df63fb5469f9c5d9332e8c6da5e&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=0ac16df63fb5469f9c5d9332e8c6da5e&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/datasets/soft_delete_tests.py
   **Line:** 183:192
   **Comment:**
   	*Missing Cleanup: This test creates a database and dataset but does not wrap cleanup in a `finally` block. If any assertion fails before the last line, the created rows remain in the shared test DB and can make later tests fail unpredictably. Move `_hard_delete_created(...)` into a `finally` block so teardown always runs.
   
   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%2F40130&comment_hash=c912078090c7cc244183d674e9937c22f934b68b29f7581b8cefc1677ec178b2&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=c912078090c7cc244183d674e9937c22f934b68b29f7581b8cefc1677ec178b2&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,454 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200

Review Comment:
   **Suggestion:** This flow soft-deletes a shared example dataset but has no `finally` cleanup; if restore/get assertions fail, the dataset stays deleted and can break subsequent integration tests that depend on example data. Add guaranteed cleanup with `_restore_dataset(dataset_id)` in a `finally` block. [missing cleanup]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Restore-happy-path test can strand example dataset soft-deleted.
   - ⚠️ Downstream tests depending on examples may unexpectedly fail.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Run `TestDatasetRestore.test_restore_soft_deleted_dataset` in
   `tests/integration_tests/datasets/soft_delete_tests.py:69-79` (around lines 299-310 in the
   PR hunk).
   
   2. The test calls `_get_example_dataset()` (lines 64-67), which does
   `db.session.query(SqlaTable).first()` and returns a shared example dataset, then logs in
   as `ADMIN_USERNAME` (lines 71-74).
   
   3. It soft-deletes that shared dataset with `DELETE /api/v1/dataset/<id>` (line 76), posts
   to `/api/v1/dataset/<uuid>/restore` and asserts a 200 status (lines 78-79), then does a
   `GET /api/v1/dataset/<id>` and asserts 200 again (lines 2-3 of the subsequent chunk). If a
   regression causes either the restore POST or the GET to return a non-200 status, one of
   these assertions fails.
   
   4. Because there is no `try/finally` around the `DELETE` and no explicit cleanup helper in
   this test (unlike `test_no_cascade_to_dependent_charts`, which restores in a `finally` at
   lines 42-58), a failing assertion leaves the shared example dataset soft-deleted in the
   database for the rest of the test session.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=45ea6954a24a4b4d901d0cc908f62577&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=45ea6954a24a4b4d901d0cc908f62577&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/datasets/soft_delete_tests.py
   **Line:** 304:310
   **Comment:**
   	*Missing Cleanup: This flow soft-deletes a shared example dataset but has no `finally` cleanup; if restore/get assertions fail, the dataset stays deleted and can break subsequent integration tests that depend on example data. Add guaranteed cleanup with `_restore_dataset(dataset_id)` in a `finally` block.
   
   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%2F40130&comment_hash=bc2871e68b9f956ea0fe0ebe1ef93ea4315e3b1469e1cc95fedd5783cb69fbbc&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=bc2871e68b9f956ea0fe0ebe1ef93ea4315e3b1469e1cc95fedd5783cb69fbbc&reaction=dislike'>👎</a>



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,454 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup: the mocked restore left the example dataset soft-deleted.

Review Comment:
   **Suggestion:** Cleanup runs only after the status assertion, so if the endpoint returns a non-422 response the example dataset remains soft-deleted and contaminates later tests. Put `_restore_dataset(dataset_id)` in a `finally` block to guarantee restoration on failure paths. [missing cleanup]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Failed restore-422 test leaves example dataset soft-deleted.
   - ⚠️ Subsequent tests may misbehave due to missing dataset.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Run `TestDatasetRestore.test_restore_failure_returns_422` in
   `tests/integration_tests/datasets/soft_delete_tests.py:5-34` (around lines 305-339 in the
   PR hunk).
   
   2. The test obtains a shared example dataset via `_get_example_dataset()` (lines 64-67),
   records its `id` and `uuid`, logs in as `ADMIN_USERNAME`, and soft-deletes it with `DELETE
   /api/v1/dataset/<id>` (line 23).
   
   3. It patches `RestoreDatasetCommand.run` to raise `DatasetRestoreFailedError` and posts
   to `/api/v1/dataset/<uuid>/restore` (lines 25-29), then asserts `rv.status_code == 422`
   (line 30). If the endpoint incorrectly maps `DatasetRestoreFailedError` (e.g., returns 500
   or 200 instead of 422), this assertion fails and raises before executing any further
   lines.
   
   4. Because the cleanup `_restore_dataset(dataset_id)` (line 33) is placed after the
   assertion and not inside a `finally` block, the failing assertion leaves the example
   dataset soft-deleted in the database, so later tests in `TestDatasetRestore` that rely on
   `_get_example_dataset()` and on example datasets being live now operate against mutated
   state.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=79bfd15fdd714a5fab0de5a512d1893a&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=79bfd15fdd714a5fab0de5a512d1893a&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/datasets/soft_delete_tests.py
   **Line:** 331:339
   **Comment:**
   	*Missing Cleanup: Cleanup runs only after the status assertion, so if the endpoint returns a non-422 response the example dataset remains soft-deleted and contaminates later tests. Put `_restore_dataset(dataset_id)` in a `finally` block to guarantee restoration on failure paths.
   
   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%2F40130&comment_hash=4fb5dd859d416a3cd9fdfd9088a31cb47454a404e42eb9f7c125c58680172ecb&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=4fb5dd859d416a3cd9fdfd9088a31cb47454a404e42eb9f7c125c58680172ecb&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(datasets): soft-delete and restore [superset]

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


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -140,21 +143,116 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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:
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, config["uuid"]):
+        is_soft_deleted = existing.deleted_at is not None
+        needs_mutation = overwrite or is_soft_deleted

Review Comment:
   Done — `import_dataset` no longer fuses the two operations: it now branches explicitly on `existing.deleted_at is not None` (RESTORE; preserves the active-logical-duplicate guard + MultipleResultsFound rollback) vs `else` (OVERWRITE), and `needs_mutation` is gone. Same split applied across all three importers. Resolving.



##########
tests/unit_tests/databases/commands/delete_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.
+
+from datetime import datetime
+
+import pytest
+from pytest_mock import MockerFixture
+from sqlalchemy.orm.session import Session
+
+
+def test_delete_database_blocked_by_soft_deleted_dataset(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:

Review Comment:
   Not needed — `app_context` is an `autouse=True` fixture in `tests/unit_tests/conftest.py:134`, so every unit test already runs inside an app context (these tests are green in CI). Declaring `app_context: None` would be cosmetic only. Resolving.



##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +37,29 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete.
+    #
+    # Match rows whose catalog is either unset (NULL) or the database
+    # default — these are "the same physical table" the way
+    # ``DatasetDAO.validate_uniqueness`` treats them (``table.catalog or
+    # default``). Example rows are seeded with ``catalog = NULL`` while a
+    # connection that reports a default catalog (e.g. Postgres) would
+    # normalize to that default, so both must qualify. This still excludes
+    # an unrelated third catalog variant of the same table_name. Within the
+    # matched set, prefer live rows over soft-deleted ones via
+    # ``ORDER BY deleted_at IS NULL DESC``.
+    catalog = database.get_default_catalog()
     return (
         db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
         .filter_by(database_id=database.id, schema=schema, table_name=table_name)
-        .one_or_none()
+        .filter(or_(SqlaTable.catalog.is_(None), SqlaTable.catalog == catalog))

Review Comment:
   Leaving as-is — this is a test helper (`dashboard_utils.get_table`) and the inline `or_(catalog IS NULL, catalog == default)` is intentionally explicit with a comment. Coupling the helper to `DatasetDAO._catalog_identity_filter` (a *private* method) would be a worse dependency than this small, well-commented duplication. Resolving.



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,456 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Restore a soft-deleted dataset (cleanup helper).
+
+        Used in ``finally`` blocks so a failed assertion can't strand a
+        soft-deleted row and leak it into later tests; re-queries with the
+        visibility-filter bypass and only restores if still soft-deleted.
+        """
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row is not None and row.deleted_at is not None:
+            row.restore()
+            db.session.commit()
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422

Review Comment:
   Fixed in 2fc212edf2 — the cleanup now calls the existing `_restore_dataset()` helper instead of duplicating the bypass-query/restore logic (also safer: the helper uses `one_or_none()`). 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(datasets): soft-delete and restore [superset]

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

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

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


##########
superset/commands/dataset/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 dataset."""
+
+import logging
+

Review Comment:
   Fixed in 0591115434 — unused `logger = logging.getLogger(__name__)` declaration and its `import logging` removed from `commands/dataset/restore.py`. The command does no logging; the cargo was carried from sibling files.



##########
superset/datasets/filters.py:
##########
@@ -51,3 +53,10 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(BaseDeletedStateFilter):  # pylint: disable=too-few-public-methods
+    """Rison filter for the GET list that exposes soft-deleted datasets."""
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable

Review Comment:
   Declining — the parent class `BaseDeletedStateFilter` (in `superset/views/filters.py`) already declares the abstract `model: ClassVar[type[SoftDeleteMixin]]`. The subclass assignment `model = SqlaTable` is type-checked against that annotation by mypy without needing a redundant re-declaration. The sibling `ChartDeletedStateFilter` and `DashboardDeletedStateFilter` follow the same bare-assignment pattern, and mypy passes on all three.



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

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


##########
tests/unit_tests/commands/dataset/restore_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.
+"""Unit tests for RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1)
+    dataset.id = 1
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id", return_value=dataset
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreDatasetCommand("1")
+        cmd.run()

Review Comment:
   **NIT — Use a UUID string, not an integer-like string**
   
   `RestoreDatasetCommand("1")` — `BaseRestoreCommand.__init__` accepts `model_uuid: str` for a UUID-column lookup. Passing `"1"` would fail at the DAO layer in production (UUID validation). This test passes only because `DatasetDAO.find_by_id` is mocked. Use a realistic UUID to document the expected argument type:
   
   ```python
   import uuid
   FAKE_UUID = str(uuid.uuid4())
   cmd = RestoreDatasetCommand(FAKE_UUID)
   ```
   
   Same applies at lines 57 (`"999"`), 71, and 94.



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -152,8 +151,11 @@ def insert_database(self, name: str, allow_multi_catalog: bool = False) -> Datab
         return db_connection
 
     def get_fixture_datasets(self) -> list[SqlaTable]:
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES

Review Comment:
   **NIT — Move `SKIP_VISIBILITY_FILTER_CLASSES` to module-level imports**
   
   This import is inside the `get_fixture_datasets()` method body. The same symbol is imported inline again in the `create_datasets` fixture teardown (around line 229) and in `test_delete_dataset_item` (around line 1983). Move all three to the module-level import block for clarity and to avoid repeated import overhead in the test hot path.



-- 
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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3391219011


##########
superset/translations/th/LC_MESSAGES/messages.po:
##########
@@ -8079,6 +8079,9 @@ msgstr "ไม่สามารถทำสำเนาชุดข้อมู
 # de, es, fa, fr, it, ja, lv, mi, nl, pl, pt, pt_BR, ru, sk, sl, tr, uk, zh,
 # zh_TW]
 #, fuzzy
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>CWE-20: Empty Translation String</b></div>
   <div id="fix">
   
   The `msgstr` is empty. Thai users will see the untranslated English message. Following the existing pattern for similar messages ('Dataset could not be created.' → 'ไม่สามารถสร้างชุดข้อมูลได้', 'Dataset could not be updated.' → 'ไม่สามารถอัปเดตชุดข้อมูลได้'), the translation should be 'ไม่สามารถกู้คืนชุดข้อมูลได้'. This is a machine-backfill-generated entry requiring human verification per the comment header. (See also: [CWE-20](https://cwe.mitre.org/data/definitions/20.html))
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/translations/th/LC_MESSAGES/messages.po
    +++ b/superset/translations/th/LC_MESSAGES/messages.po
    @@ -8079,7 +8079,7 @@
     # de, es, fa, fr, it, ja, lv, mi, nl, pl, pt, pt_BR, ru, sk, sl, tr, uk, zh,
     # zh_TW]
     #, fuzzy
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "ไม่สามารถกู้คืนชุดข้อมูลได้"
    
      msgid "Dataset could not be updated."
      msgstr "ไม่สามารถอัปเดตชุดข้อมูลได้"
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #eb8429</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:
##########
@@ -4754,6 +4754,9 @@ msgstr "Datensatz konnte nicht erstellt werden."
 msgid "Dataset could not be duplicated."
 msgstr "Der Datensatz konnte nicht dupliziert werden."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing German translation</b></div>
   <div id="fix">
   
   The `msgstr` for "Dataset could not be restored." is empty. Following the established pattern from lines 4754-4755 ("Der Datensatz konnte nicht dupliziert werden."), the German translation should be "Der Datensatz konnte nicht wiederhergestellt werden." Users with German locale will see untranslated English text without this fix.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/de/LC_MESSAGES/messages.po
    +++ superset/translations/de/LC_MESSAGES/messages.po
    @@ -4755,7 +4755,7 @@
     msgstr "Der Datensatz konnte nicht dupliziert werden."
    
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "Der Datensatz konnte nicht wiederhergestellt werden."
    
     msgid "Dataset could not be updated."
     msgstr "Datensatz konnte nicht aktualisiert werden."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #eb8429</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:
##########
@@ -4849,6 +4849,9 @@ msgstr "No se ha podido crear el conjunto de datos."
 msgid "Dataset could not be duplicated."
 msgstr "No se ha podido duplicar el conjunto de datos."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Spanish translation</b></div>
   <div id="fix">
   
   The `msgstr` is empty, so Spanish-speaking users will see the untranslated English text "Dataset could not be restored." instead of Spanish. This follows the pattern of other error messages in this file (lines 4849-4850, 4855-4856) which use "No se ha podido [verb] el conjunto de datos."
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #eb8429</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:
##########
@@ -4638,6 +4638,9 @@ msgstr "无法创建数据集。"
 msgid "Dataset could not be duplicated."
 msgstr "数据集无法复制。"
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing translation for new string</b></div>
   <div id="fix">
   
   The new error message `msgid "Dataset could not be restored."` has an empty `msgstr`, meaning Chinese-speaking users will see untranslated English text. Other similar dataset error messages in this file (e.g., lines 4634-4635, 4644-4645) have proper Chinese translations following a '无法[verb]数据集' pattern.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #eb8429</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:
##########
@@ -4392,6 +4392,9 @@ msgstr "Veriseti oluşturulamadı."
 msgid "Dataset could not be duplicated."
 msgstr "Veriseti çoğaltılamadı."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Turkish translation</b></div>
   <div id="fix">
   
   The new translation entry for "Dataset could not be restored." has an empty `msgstr`. Turkish locale users will see the untranslated English message instead of a localized one. Add the translation following the established pattern.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- a/superset/translations/tr/LC_MESSAGES/messages.po
    +++ b/superset/translations/tr/LC_MESSAGES/messages.po
    @@ -4393,7 +4393,7 @@ msgstr "Veriseti çoğaltılamadı."
    
     msgid "Dataset could not be restored."
    -msgstr ""
    +msgstr "Veriseti geri yüklenemedi."
    
     msgid "Dataset could not be updated."
     msgstr "Veriseti güncellenemedi."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #eb8429</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/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,456 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Restore a soft-deleted dataset (cleanup helper).
+
+        Used in ``finally`` blocks so a failed assertion can't strand a
+        soft-deleted row and leak it into later tests; re-queries with the
+        visibility-filter bypass and only restores if still soft-deleted.
+        """
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row is not None and row.deleted_at is not None:
+            row.restore()
+            db.session.commit()
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Duplicated cleanup logic</b></div>
   <div id="fix">
   
   The test `test_restore_failure_returns_422` at lines 306-331 duplicates the restoration logic from `_restore_dataset()` (lines 45-60) in its cleanup block (lines 333-342). This violates the DRY principle and creates divergence risk if the restoration logic ever changes.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #eb8429</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(datasets): soft-delete and restore [superset]

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

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

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3454235108


##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,26 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(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 = _("Dataset could not be restored.")

Review Comment:
   **Suggestion:** Add a class docstring describing the restore failure case instead of relying only on inline comments. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python class and it has no class docstring. The rule explicitly requires new classes to be documented inline, 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=c9c7199fa233465aba886a1cd61cfa49&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=c9c7199fa233465aba886a1cd61cfa49&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/dataset/exceptions.py
   **Line:** 173:180
   **Comment:**
   	*Custom Rule: Add a class docstring describing the restore failure case instead of relying only on inline comments.
   
   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%2F40130&comment_hash=71be2e155862e7a2ba2a79740ecc9c4a5a944b975ee2e9b3bc83ba81e1974866&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=71be2e155862e7a2ba2a79740ecc9c4a5a944b975ee2e9b3bc83ba81e1974866&reaction=dislike'>👎</a>



##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,26 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(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 = _("Dataset could not be restored.")
+
+
+class DatasetLogicalDuplicateError(CommandException):
+    status = 422
+    message = _(
+        "Dataset cannot be restored because another active dataset already "
+        "references the same physical table (same database, catalog, schema, "
+        "and table name). Delete the duplicate or rename the table before "
+        "restoring."
+    )

Review Comment:
   **Suggestion:** Add a class docstring that explains when this logical-duplicate exception is raised. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is also a newly added Python class and it lacks a docstring. Inline comments or a class message do not satisfy the stated docstring requirement, so the suggestion is valid.
   </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=e54d54acd8e44e968a6addc692135450&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=e54d54acd8e44e968a6addc692135450&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/dataset/exceptions.py
   **Line:** 183:190
   **Comment:**
   	*Custom Rule: Add a class docstring that explains when this logical-duplicate exception is raised.
   
   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%2F40130&comment_hash=bdb10e80c7dc442d60e4ce54a2d5b5ac4ea56debb1d3f8927fcec27d79515ae6&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=bdb10e80c7dc442d60e4ce54a2d5b5ac4ea56debb1d3f8927fcec27d79515ae6&reaction=dislike'>👎</a>



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError
+
+    def validate(self) -> SqlaTable:  # type: ignore[override]

Review Comment:
   **Suggestion:** Add an inline docstring to this newly added method to describe its validation behavior and failure condition before executing the method body. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly added Python method and it does not include a docstring. The custom rule requires newly introduced functions and classes to be documented inline, 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=81ed2e4a9eac4bf99147ca967d702fae&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=81ed2e4a9eac4bf99147ca967d702fae&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/dataset/restore.py
   **Line:** 51:51
   **Comment:**
   	*Custom Rule: Add an inline docstring to this newly added method to describe its validation behavior and failure condition before executing the method body.
   
   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%2F40130&comment_hash=d558048b71d8fe892a5e9546f2b9c3212c12a15dff936f1e02c56c7e90544f79&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=d558048b71d8fe892a5e9546f2b9c3212c12a15dff936f1e02c56c7e90544f79&reaction=dislike'>👎</a>



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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

Review Comment:
   **Suggestion:** Add an inline docstring to the newly introduced helper function so every new function in this file is documented. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The helper function `raise_security` is newly introduced in this file and does not have a docstring. This matches the custom rule requiring newly added Python functions and classes to include docstrings.
   </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=f4e69947faca47d6bbd2efeaa4d03f28&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=f4e69947faca47d6bbd2efeaa4d03f28&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/dataset/restore_test.py
   **Line:** 8:9
   **Comment:**
   	*Custom Rule: Add an inline docstring to the newly introduced helper function so every new function in this file is 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%2F40130&comment_hash=26b3110364e49168062a169014ec5ee31e32d4a131c28951f18ab34729ada59b&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=26b3110364e49168062a169014ec5ee31e32d4a131c28951f18ab34729ada59b&reaction=dislike'>👎</a>



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    def apply(self, query: Query, value: Any) -> Query:

Review Comment:
   **Suggestion:** Add an inline docstring to the newly added `apply` method so the method behavior and intent are documented per the rule for new functions. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The newly added `DatasetDeletedStateFilter.apply` method has no docstring, and the custom rule requires newly added Python functions and classes to be documented inline. This is 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=8c15c488ba5a4c1ebfe90ab6cc7b2861&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=8c15c488ba5a4c1ebfe90ab6cc7b2861&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/datasets/filters.py
   **Line:** 81:81
   **Comment:**
   	*Custom Rule: Add an inline docstring to the newly added `apply` method so the method behavior and intent are documented per the rule for new functions.
   
   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%2F40130&comment_hash=dd8ea86ef60ecfb1f839a5d1246bfe42d7b6abb16b1c3e65b2b949737636a9e5&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=dd8ea86ef60ecfb1f839a5d1246bfe42d7b6abb16b1c3e65b2b949737636a9e5&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(datasets): soft-delete and restore [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3509725825


##########
superset/translations/ar/LC_MESSAGES/messages.po:
##########
@@ -4697,6 +4697,9 @@ msgstr "تعذر إنشاء مجموعة بيانات."
 msgid "Dataset could not be duplicated."
 msgstr "تعذر تكرار مجموعة البيانات."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Untranslated message string</b></div>
   <div id="fix">
   
   The `msgstr` for 'Dataset could not be restored.' is empty. Arabic-speaking users will see untranslated English text for this error message. Compare with other messages in this file (e.g., line 4698: 'تعرضت عملية تكرار مجموعة البيانات.') which have complete Arabic translations. An appropriate Arabic translation would be: 'تعذر استعادة مجموعة البيانات.'
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #5e9c47</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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3462168531


##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Naive datetime without timezone info</b></div>
   <div id="fix">
   
   Use timezone-aware datetime instead of naive datetime for `deleted_at` timestamp.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c38ddc</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:
##########
@@ -8222,6 +8222,9 @@ msgstr "Tietojoukkoa ei voitu monistaa."
 # de, es, fa, fr, it, ja, lv, mi, nl, pl, pt, pt_BR, ru, sk, sl, tr, uk, zh,
 # zh_TW]
 #, fuzzy
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing Finnish translation</b></div>
   <div id="fix">
   
   The `msgstr` field is empty for this translation entry. While neighboring entries like "Dataset could not be duplicated" (line 8219) have Finnish translations (`Tietojoukkoa ei voitu monistaa.`), this entry has no translation. Finnish users triggering a dataset restore failure will see the raw English text instead of a localized message. This follows the pattern `Tietojoukkoa ei voitu [palauttaa/päivittää/luoda]` used in this file's other Dataset error messages.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/translations/fi/LC_MESSAGES/messages.po (line 8226) ---
    8226: -msgstr ""
    8226:+msgstr "Tietojoukkoa ei voitu palauttaa."
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c38ddc</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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510302469


##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog
+
+        # Same rationale as ``validate_uniqueness`` above: a soft-deleted
+        # twin must block the update rather than being silently ignored.
+        # The bypass is session-scoped, not per-query, because the EXISTS
+        # subquery pattern below leaves the inner Query's execution_options
+        # invisible to the outer execute (where the listener fires).
+        #
+        # avoid app-init regression: see ``validate_uniqueness`` above — a
+        # module-top import from ``superset.models.helpers`` raises
+        # "App not initialized yet" outside an app context (see PR #40573).
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
         )
-        return not db.session.query(dataset_query.exists()).scalar()
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            dataset_query = db.session.query(SqlaTable).filter(
+                SqlaTable.table_name == table.table,
+                SqlaTable.database_id == database.id,
+                SqlaTable.schema == table.schema,
+                DatasetDAO._catalog_identity_filter(catalog, default_catalog),
+                SqlaTable.id != dataset_id,
+            )
+            return not db.session.query(dataset_query.exists()).scalar()
+
+    @staticmethod
+    def has_active_logical_duplicate(model: SqlaTable) -> bool:
+        """Return True iff another *active* dataset shares model's physical table.
+
+        Physical identity is ``(database_id, catalog, schema, table_name)``.
+        ``model``'s catalog is normalized to the database default when unset —
+        the same rule ``validate_uniqueness``/``validate_update_uniqueness``
+        apply — so create, update, restore, and re-import agree on what counts
+        as the same physical table. Catalog matching is null-aware via
+        ``_catalog_identity_filter``: when the normalized catalog is the database
+        default, both ``catalog = default`` and ``catalog IS NULL`` rows match,
+        so a default-catalog twin is caught whichever way either row stored its
+        catalog.
+
+        Unlike ``validate_uniqueness``, this does NOT use
+        ``skip_visibility_filter``: it relies on the ``SoftDeleteMixin`` listener
+        to auto-append ``deleted_at IS NULL`` so only *active* rows match. Do not
+        add the bypass here — it would broaden the check to soft-deleted rows and
+        silently refuse legitimate restores. ``id != model.id`` excludes the row
+        itself.
+
+        Assumes an active app context and a session-attached ``model`` so
+        ``db.session`` and the lazy ``model.database`` relationship resolve.
+        """
+        # The catalog might not be set even if the database supports catalogs,
+        # in case multi-catalog is disabled.
+        default_catalog = model.database.get_default_catalog()
+        catalog = model.catalog or default_catalog

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag test-scaffolding duplication or local setup blocks in test files when they are intentionally kept local for readability and follow the suite's testing conventions.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
superset/daos/dataset.py:
##########
@@ -186,16 +236,111 @@ def validate_update_uniqueness(
     ) -> bool:
         # The catalog might not be set even if the database supports catalogs, in case
         # multi-catalog is disabled.
-        catalog = table.catalog or database.get_default_catalog()
-
-        dataset_query = db.session.query(SqlaTable).filter(
-            SqlaTable.table_name == table.table,
-            SqlaTable.database_id == database.id,
-            SqlaTable.schema == table.schema,
-            SqlaTable.catalog == catalog,
-            SqlaTable.id != dataset_id,
+        default_catalog = database.get_default_catalog()
+        catalog = table.catalog or default_catalog
+
+        # Same rationale as ``validate_uniqueness`` above: a soft-deleted
+        # twin must block the update rather than being silently ignored.
+        # The bypass is session-scoped, not per-query, because the EXISTS
+        # subquery pattern below leaves the inner Query's execution_options
+        # invisible to the outer execute (where the listener fires).
+        #
+        # avoid app-init regression: see ``validate_uniqueness`` above — a
+        # module-top import from ``superset.models.helpers`` raises
+        # "App not initialized yet" outside an app context (see PR #40573).
+        from superset.models.helpers import (  # pylint: disable=import-outside-toplevel
+            skip_visibility_filter,
         )
-        return not db.session.query(dataset_query.exists()).scalar()
+
+        with skip_visibility_filter(db.session, SqlaTable):
+            dataset_query = db.session.query(SqlaTable).filter(
+                SqlaTable.table_name == table.table,
+                SqlaTable.database_id == database.id,
+                SqlaTable.schema == table.schema,
+                DatasetDAO._catalog_identity_filter(catalog, default_catalog),
+                SqlaTable.id != dataset_id,
+            )
+            return not db.session.query(dataset_query.exists()).scalar()
+
+    @staticmethod
+    def has_active_logical_duplicate(model: SqlaTable) -> bool:
+        """Return True iff another *active* dataset shares model's physical table.
+
+        Physical identity is ``(database_id, catalog, schema, table_name)``.
+        ``model``'s catalog is normalized to the database default when unset —
+        the same rule ``validate_uniqueness``/``validate_update_uniqueness``
+        apply — so create, update, restore, and re-import agree on what counts
+        as the same physical table. Catalog matching is null-aware via
+        ``_catalog_identity_filter``: when the normalized catalog is the database
+        default, both ``catalog = default`` and ``catalog IS NULL`` rows match,
+        so a default-catalog twin is caught whichever way either row stored its
+        catalog.
+
+        Unlike ``validate_uniqueness``, this does NOT use
+        ``skip_visibility_filter``: it relies on the ``SoftDeleteMixin`` listener
+        to auto-append ``deleted_at IS NULL`` so only *active* rows match. Do not
+        add the bypass here — it would broaden the check to soft-deleted rows and
+        silently refuse legitimate restores. ``id != model.id`` excludes the row
+        itself.
+
+        Assumes an active app context and a session-attached ``model`` so
+        ``db.session`` and the lazy ``model.database`` relationship resolve.
+        """
+        # The catalog might not be set even if the database supports catalogs,
+        # in case multi-catalog is disabled.
+        default_catalog = model.database.get_default_catalog()
+        catalog = model.catalog or default_catalog

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag test-scaffolding duplication or local setup blocks in test files when they are intentionally kept local for readability and follow the suite's testing conventions.
   
   **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/dashboard_utils.py:
##########
@@ -35,10 +37,29 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete.
+    #
+    # Match rows whose catalog is either unset (NULL) or the database
+    # default — these are "the same physical table" the way
+    # ``DatasetDAO.validate_uniqueness`` treats them (``table.catalog or
+    # default``). Example rows are seeded with ``catalog = NULL`` while a
+    # connection that reports a default catalog (e.g. Postgres) would
+    # normalize to that default, so both must qualify. This still excludes
+    # an unrelated third catalog variant of the same table_name. Within the
+    # matched set, prefer live rows over soft-deleted ones via
+    # ``ORDER BY deleted_at IS NULL DESC``.
+    catalog = database.get_default_catalog()

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



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require type annotations for local test-scaffolding variables in test files when their types are already obvious from context; keep this style guidance scoped to tests.
   
   **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/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag missing concrete type annotations for local test-scaffolding variables when their types are already unambiguous from context; in test files, keep this style noise low unless the annotation affects correctness.
   
   **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/dataset/test_duplicate.py:
##########
@@ -101,3 +102,66 @@ def test_duplicate_dataset_access_check_passes_through() -> None:
                     command.validate()  # should not raise
                     # Confirm access check was called with the base dataset
                     mock_access.assert_called_once_with(datasource=mock_dataset)
+
+
+def test_duplicate_dataset_blocked_by_soft_deleted_twin(session: Session) -> None:
+    """validate() rejects a duplicate whose name matches a soft-deleted
+    dataset at the same (database, schema).
+
+    The previous name-only ``find_one_or_none`` lookup ran through the
+    soft-delete visibility filter, so a soft-deleted twin was invisible and
+    the duplicate proceeded — hitting whichever DB constraint applies as an
+    opaque IntegrityError, or creating an active twin that permanently
+    blocks restore where none does. The shared ``validate_uniqueness``
+    check bypasses the filter and refuses with a clean validation error.
+    """
+    from datetime import datetime, timezone
+
+    from superset import db
+    from superset.commands.dataset.duplicate import DuplicateDatasetCommand
+    from superset.commands.dataset.exceptions import DatasetInvalidError
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.models.core import Database
+
+    SqlaTable.metadata.create_all(session.get_bind())
+
+    database = Database(database_name="dup_db", sqlalchemy_uri="sqlite://")
+    base = SqlaTable(
+        table_name="base_view",
+        schema="main",
+        database=database,
+        sql="select 1",
+    )
+    hidden_twin = SqlaTable(
+        table_name="dup_name",
+        schema="main",
+        database=database,
+        deleted_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+    )
+    db.session.add_all([database, base, hidden_twin])
+    db.session.flush()
+
+    with (
+        # find_by_id applies the security base filter, which needs a request
+        # user; return the seeded row directly. validate_uniqueness — the
+        # behaviour under test — runs for real against the session.
+        patch(
+            "superset.commands.dataset.duplicate.DatasetDAO.find_by_id",
+            return_value=base,
+        ),
+        patch("superset.commands.dataset.duplicate.security_manager.raise_for_access"),
+        patch(
+            "superset.commands.dataset.duplicate."
+            "DuplicateDatasetCommand.populate_owners",
+            return_value=[],
+        ),
+    ):
+        command = DuplicateDatasetCommand(
+            {
+                "base_model_id": base.id,
+                "table_name": "dup_name",
+                "is_managed_externally": False,
+            }
+        )

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



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Avoid flagging missing type annotations for local/test-scaffolding variables whose types are obvious from context and do not change mypy behavior; prefer keeping these cases unannotated to reduce noise.
   
   **Applied to:**
     - `**/*.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(datasets): soft-delete and restore [superset]

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


##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]
+
             yield datasets
 
-            # rollback changes
-            for dataset in datasets:
-                state = inspect(dataset)
-                if not state.was_deleted:
-                    db.session.delete(dataset)
+            # rollback changes (including soft-deleted rows)
+            for dataset_id in dataset_ids:
+                row = (
+                    db.session.query(SqlaTable)
+                    .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                    .filter(SqlaTable.id == dataset_id)
+                    .one_or_none()
+                )

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/unit_tests/commands/databases/sync_permissions_test.py:
##########
@@ -409,3 +409,49 @@ def test_sync_permissions_command_rename_db_in_perms(
     assert (
         mock_chart.schema_perm == f"[{database_with_catalog.name}].[catalog1].[schema1]"
     )
+
+
+def test_sync_permissions_command_rename_bypasses_visibility_filter(
+    mocker: MockerFixture, database_with_catalog: MagicMock
+):

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/unit_tests/commands/databases/sync_permissions_test.py:
##########
@@ -409,3 +409,49 @@ def test_sync_permissions_command_rename_db_in_perms(
     assert (
         mock_chart.schema_perm == f"[{database_with_catalog.name}].[catalog1].[schema1]"
     )
+
+
+def test_sync_permissions_command_rename_bypasses_visibility_filter(
+    mocker: MockerFixture, database_with_catalog: MagicMock
+):
+    """The dataset/chart perm rewrite must run with the soft-delete
+    visibility filter bypassed for ``SqlaTable`` and ``Slice``.
+
+    A soft-deleted dataset's ``schema_perm``/``catalog_perm`` (and its
+    charts') must still be rewritten on a database rename; without the
+    bypass, the listener hides those rows from ``get_datasets`` and a
+    later restore resurrects stale perm strings referencing the old
+    database name — matchable by a ``schema_access`` grant on a new
+    database reusing that name.
+    """
+    from superset.connectors.sqla.models import SqlaTable
+    from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES
+    from superset.models.slice import Slice
+
+    mocker.patch(
+        "superset.commands.database.sync_permissions."
+        "security_manager.find_permission_view_menu",
+        return_value=None,
+    )
+    observed_bypass: list[set[type]] = []
+
+    def capture_bypass(*args, **kwargs):
+        observed_bypass.append(
+            set(db.session.info.get(SKIP_VISIBILITY_FILTER_CLASSES, set()))
+        )
+        return []
+

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510303122


##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -1957,17 +1974,32 @@ def test_delete_dataset_item(self):
         """
 
         dataset = self.insert_default_dataset()
+        dataset_id = dataset.id

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit scalar type annotations for local test-scaffolding variables when their types are already unambiguous from context and the annotation would add noise without improving mypy coverage.
   
   **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/datasets/api_tests.py:
##########
@@ -1957,17 +1974,32 @@ def test_delete_dataset_item(self):
         """
 
         dataset = self.insert_default_dataset()
+        dataset_id = dataset.id
         view_menu = security_manager.find_view_menu(dataset.get_perm())
         assert view_menu is not None
         view_menu_id = view_menu.id
         self.login(ADMIN_USERNAME)
         uri = f"api/v1/dataset/{dataset.id}"
         rv = self.client.delete(uri)
         assert rv.status_code == 200
+        # With soft delete, the row still exists (with deleted_at set) so
+        # FAB permissions are preserved for potential restore.
         non_view_menu = db.session.query(security_manager.viewmenu_model).get(
             view_menu_id
         )
-        assert non_view_menu is None
+        assert non_view_menu is not None
+
+        # Hard-delete the soft-deleted row to avoid unique constraint
+        # collisions in subsequent tests
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )

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 obvious from context; these annotations add noise without improving mypy coverage.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



##########
tests/unit_tests/commands/databases/sync_permissions_test.py:
##########
@@ -409,3 +409,49 @@ def test_sync_permissions_command_rename_db_in_perms(
     assert (
         mock_chart.schema_perm == f"[{database_with_catalog.name}].[catalog1].[schema1]"
     )
+
+
+def test_sync_permissions_command_rename_bypasses_visibility_filter(
+    mocker: MockerFixture, database_with_catalog: MagicMock
+):

Review Comment:
   ✅ **Customized review instruction saved!**
   
   **Instruction:**
   > Do not require explicit return type annotations on new or modified test functions in test files when the return type is obvious from context and the annotation would add noise.
   
   **Applied to:**
     - `**/test/**`
     - `**/tests/**`
     - `**/*test*.<ext>`
   
   ---
   💡 *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(datasets): soft-delete and restore [superset]

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


##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,26 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(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 = _("Dataset could not be restored.")

Review Comment:
   Considered — keeping as-is: these are internal helpers/test scaffolding following the surrounding file's documentation and style conventions. Declining as style-tier; happy to revisit if a maintainer feels differently.



##########
superset/commands/dataset/exceptions.py:
##########
@@ -170,6 +170,26 @@ class DatasetUpdateFailedError(UpdateFailedError):
     message = _("Dataset could not be updated.")
 
 
+class DatasetRestoreFailedError(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 = _("Dataset could not be restored.")
+
+
+class DatasetLogicalDuplicateError(CommandException):
+    status = 422
+    message = _(
+        "Dataset cannot be restored because another active dataset already "
+        "references the same physical table (same database, catalog, schema, "
+        "and table name). Delete the duplicate or rename the table before "
+        "restoring."
+    )

Review Comment:
   Test-scaffolding duplication noted; the setup blocks intentionally stay local to each test for readability (per the avoid-nesting-when-testing convention this suite follows). Declining as style.



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,60 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: DB-level enforcement of
+    ``SqlaTable`` logical uniqueness is inconsistent (the model-level
+    4-column ``UniqueConstraint`` is metadata-only — no migration creates
+    it — and the legacy 3-column ``_customer_location_uc`` has no catalog
+    leg and is NULL-leaky), so another active dataset may have claimed the
+    same physical identity while this one was soft-deleted. The
+    application-level check refuses the restore with a clean 422 rather
+    than relying on the DB, which would either reject with an opaque
+    IntegrityError or — where no constraint applies — silently allow two
+    active datasets pointing at the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError
+
+    def validate(self) -> SqlaTable:  # type: ignore[override]

Review Comment:
   Considered — keeping as-is: these are internal helpers/test scaffolding following the surrounding file's documentation and style conventions. Declining as style-tier; happy to revisit if a maintainer feels differently.



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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

Review Comment:
   Considered — keeping as-is: these are internal helpers/test scaffolding following the surrounding file's documentation and style conventions. Declining as style-tier; happy to revisit if a maintainer feels differently.



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable
+
+    def apply(self, query: Query, value: Any) -> Query:

Review Comment:
   Considered — keeping as-is: these are internal helpers/test scaffolding following the surrounding file's documentation and style conventions. Declining as style-tier; happy to revisit if a maintainer feels differently.



##########
superset/translations/mi/LC_MESSAGES/messages.po:
##########
@@ -4618,6 +4618,9 @@ msgstr "Kāore i taea te hanga i te rārangi raraunga."
 msgid "Dataset could not be duplicated."
 msgstr "Kāore i taea te tārua i te rārangi raraunga."
 
+msgid "Dataset could not be restored."
+msgstr ""

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



##########
superset/translations/ko/LC_MESSAGES/messages.po:
##########
@@ -4578,6 +4578,9 @@ msgstr ""
 msgid "Dataset could not be duplicated."
 msgstr "데이터베이스를 업데이트할 수 없습니다."
 
+msgid "Dataset could not be restored."
+msgstr ""

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



-- 
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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3530161837


##########
superset/commands/database/sync_permissions.py:
##########
@@ -283,17 +286,29 @@ def _rename_database_in_permissions(
             if existing_pvm:
                 existing_pvm.view_menu.name = new_schema_perm_name
 
-            # rename permissions on datasets and charts
-            for dataset in DatabaseDAO.get_datasets(
-                self.db_connection_id,
-                catalog=catalog,
-                schema=schema,
-            ):
-                dataset.catalog_perm = new_catalog_perm_name
-                dataset.schema_perm = new_schema_perm_name
-                for chart in DatasetDAO.get_related_objects(dataset.id)["charts"]:
-                    chart.catalog_perm = new_catalog_perm_name
-                    chart.schema_perm = new_schema_perm_name
+            # Rename permissions on datasets and charts. Bypass the
+            # soft-delete visibility filter: a soft-deleted dataset's
+            # ``schema_perm``/``catalog_perm`` (and its charts') must still be
+            # rewritten on a database rename — otherwise restoring the dataset
+            # later brings back stale perm strings referencing the old
+            # database name (fail-closed for legitimate users, and matchable
+            # by a schema_access grant on a new database reusing the old
+            # name). Mirrors the same bypass in
+            # ``security_manager._update_vm_datasources_access``, which
+            # maintains the dataset-level ``perm`` string. ``Slice`` is
+            # included so chart perm rewrites keep working once charts gain
+            # soft delete (a no-op until then).
+            with skip_visibility_filter(db.session, SqlaTable, Slice):
+                for dataset in DatabaseDAO.get_datasets(
+                    self.db_connection_id,
+                    catalog=catalog,
+                    schema=schema,
+                ):
+                    dataset.catalog_perm = new_catalog_perm_name
+                    dataset.schema_perm = new_schema_perm_name
+                    for chart in DatasetDAO.get_related_objects(dataset.id)["charts"]:
+                        chart.catalog_perm = new_catalog_perm_name
+                        chart.schema_perm = new_schema_perm_name

Review Comment:
   **Suggestion:** This introduces an N+1 query pattern during database rename: for every dataset in a schema you call `get_related_objects`, which runs multiple SQL queries (including an unnecessary dashboards query) even though only charts are used. On databases with many datasets this can make permission sync very slow and timeout-prone. Fetch charts in bulk once per schema (or add a charts-only DAO helper) instead of querying per dataset. [performance]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Database rename sync issues two queries per dataset.
   - ⚠️ Large schemas may cause slow or timing-out sync.
   - ⚠️ Unnecessary dashboards queries increase database load.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Trigger a database rename so permissions are synced:
   
      - Call `PUT /api/v1/database/<id>` to change `database_name`, which invokes
      `UpdateDatabaseCommand.run` in `superset/commands/database/update.py:54-118`.
   
      - That method computes `original_database_name` and then calls
      `SyncPermissionsCommand(...).run()` at `update.py:105-115`.
   
   
   
   2. Follow the execution into `SyncPermissionsCommand`:
   
      - `SyncPermissionsCommand.run` in
      `superset/commands/database/sync_permissions.py:122-133` calls
      `self.sync_database_permissions()` when `SYNC_DB_PERMISSIONS_IN_ASYNC_MODE` is False
      (or enqueues the Celery task which calls the same method).
   
      - `sync_database_permissions` iterates catalogs and schemas and, when the database name
      changed, calls `_rename_database_in_permissions(catalog, schemas)` at
      `sync_permissions.py:185-187`.
   
   
   
   3. Observe dataset enumeration per schema:
   
      - Inside `_rename_database_in_permissions` (`sync_permissions.py:248-312`), for each
      `schema` it enters the new block at `sync_permissions.py:289-301`.
   
      - Within the `skip_visibility_filter` context, it calls
      `DatabaseDAO.get_datasets(self.db_connection_id, catalog=catalog, schema=schema)` and
      iterates `for dataset in ...` at `sync_permissions.py:302-306`.
   
   
   
   4. See the per-dataset relationship queries and redundant dashboards query:
   
      - For each `dataset` returned, the code runs `for chart in
      DatasetDAO.get_related_objects(dataset.id)["charts"]:` at
      `sync_permissions.py:309-311`.
   
      - `DatasetDAO.get_related_objects` in `superset/daos/dataset.py:124-144` issues two
      separate SQL queries per call: one to load charts (`db.session.query(Slice)...all()`)
      and another to load dashboards via a `Dashboard` join and `Slice.id.in_(chart_ids)`.
   
      - Because this call is made once per dataset, the permission sync performs an N+1
      pattern (2 queries per dataset) plus one query for the dataset list, and it loads
      dashboards even though `_rename_database_in_permissions` only uses the `charts` list.
      On databases with many datasets in a schema, this can significantly slow or even time
      out the `/<pk>/sync_permissions/` endpoint and the implicit sync invoked from database
      updates.
   ```
   </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=16f8bbdeb5e445508f870ff558c33571&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=16f8bbdeb5e445508f870ff558c33571&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/database/sync_permissions.py
   **Line:** 309:311
   **Comment:**
   	*Performance: This introduces an N+1 query pattern during database rename: for every dataset in a schema you call `get_related_objects`, which runs multiple SQL queries (including an unnecessary dashboards query) even though only charts are used. On databases with many datasets this can make permission sync very slow and timeout-prone. Fetch charts in bulk once per schema (or add a charts-only DAO helper) instead of querying per dataset.
   
   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%2F40130&comment_hash=a7ed2082234c00e5336b69d92fa1f4e477d79fb1d5b18047b8652b8f59a05a6f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=a7ed2082234c00e5336b69d92fa1f4e477d79fb1d5b18047b8652b8f59a05a6f&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(datasets): soft-delete and restore [superset]

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

   Thanks all for the earlier reviews — this PR's head was refreshed and is green and ready for a final look:
   
   - **Rebased onto current master** after charts soft-delete (#40129) merged, and re-pointed the `add_deleted_at_to_tables` migration onto the new head so the branch presents a **single alembic head** (no dangling migration head).
   - **Addressed the outstanding automated-review comments**: the MCP `create_dataset` / `create_virtual_dataset` tools now handle the soft-deleted-twin case explicitly (actionable restore-or-rename message rather than a generic error); tightened the database-delete tests to assert the specific `DatabaseDeleteSoftDeletedDatasetsExistFailedError` (+ a live-dataset branch test); and documented that the DB `UniqueConstraint` is the real guard on the duplicate-check path. All review threads are resolved.
   - **Fixed a test-cleanup bug** (`_restore_dataset` was called on the wrong class in one `finally`) that had been failing the DB suites; `test-postgres` / `test-mysql` / `test-sqlite` are now green.
   
   No behavior/scope change — same soft-delete + restore, gated behind `SOFT_DELETE`. @eschutho (or any migrations code owner) — would appreciate a re-approve on the current head when you have a moment. 🙏
   
   _This comment was generated by Claude (AI) 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(datasets): soft-delete and restore [superset]

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

   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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3492947026


##########
superset/datasets/api.py:
##########
@@ -87,25 +94,40 @@
     statsd_metrics,
 )
 from superset.views.error_handling import handle_api_exception
-from superset.views.filters import BaseFilterRelatedUsers, FilterRelatedOwners
+from superset.views.filters import (
+    BaseFilterRelatedUsers,
+    FilterRelatedOwners,
+    SoftDeleteApiMixin,
+)
 
 logger = logging.getLogger(__name__)
 
 
-class DatasetRestApi(BaseSupersetModelRestApi):
+class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
     datamodel = SQLAInterface(SqlaTable)
     base_filters = [["id", DatasourceFilter, lambda: []]]
 
     resource_name = "dataset"
     allow_browser_login = True
     class_permission_name = "Dataset"
-    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_Dataset``) 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 for `method_permission_name` (for example a dictionary mapping method names to permission strings) to satisfy the type-hint requirement for newly introduced variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly introduced class attribute in Python code and it is not type-annotated. Under the type-hint rule, such annotatable variables should include an explicit type hint, so the suggestion 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=dad5e123ac5a44f98c4c27317a02910b&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=dad5e123ac5a44f98c4c27317a02910b&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/datasets/api.py
   **Line:** 120:123
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for `method_permission_name` (for example a dictionary mapping method names to permission strings) to satisfy the type-hint requirement for 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%2F40130&comment_hash=e286766d87342f7f46a023603550c621339fe52a340d6cfe9ac31a60a0cbd05e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=e286766d87342f7f46a023603550c621339fe52a340d6cfe9ac31a60a0cbd05e&reaction=dislike'>👎</a>



##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,54 @@
+# 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 tables for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``tables`` table to support soft deletion of datasets. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 3a8e6f2c1b95
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:10: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 = "3a8e6f2c1b95"
+down_revision = "78a40c08b4be"

Review Comment:
   **Suggestion:** Add explicit type annotations to the Alembic revision identifier variables to comply with the required Python typing rule. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The file introduces module-level Alembic metadata variables without type annotations. Under the Python type-hint rule, these annotatable variables should be explicitly typed, so the suggestion 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=6216bc4393264c84a1e7c4068a2979bd&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=6216bc4393264c84a1e7c4068a2979bd&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-10_3a8e6f2c1b95_add_deleted_at_to_tables.py
   **Line:** 38:39
   **Comment:**
   	*Custom Rule: Add explicit type annotations to the Alembic revision identifier variables to 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%2F40130&comment_hash=6542ccd5e457174d5007745f6ca4896b8cf4033e127f3e552268eaf4144d4128&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=6542ccd5e457174d5007745f6ca4896b8cf4033e127f3e552268eaf4144d4128&reaction=dislike'>👎</a>



##########
superset/migrations/versions/2026-05-08_12-10_3a8e6f2c1b95_add_deleted_at_to_tables.py:
##########
@@ -0,0 +1,54 @@
+# 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 tables for soft-delete.
+
+Adds a nullable ``deleted_at`` column and an index on it to the
+``tables`` table to support soft deletion of datasets. Companion to
+the ``SoftDeleteMixin`` infrastructure shipped in PR #39977.
+
+Revision ID: 3a8e6f2c1b95
+Revises: 78a40c08b4be
+Create Date: 2026-05-08 12:10: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 = "3a8e6f2c1b95"
+down_revision = "78a40c08b4be"
+
+TABLE_NAME = "tables"
+INDEX_NAME = f"ix_{TABLE_NAME}_deleted_at"

Review Comment:
   **Suggestion:** Add explicit type annotations to the module-level table/index name constants since they are relevant annotatable variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   These new module-level constants are plain strings and can be annotated, but the file omits type hints for them. That matches the Python typing rule's requirement 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=a75679d1557842f6aebf7e6a2a7f8711&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=a75679d1557842f6aebf7e6a2a7f8711&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-10_3a8e6f2c1b95_add_deleted_at_to_tables.py
   **Line:** 41:42
   **Comment:**
   	*Custom Rule: Add explicit type annotations to the module-level table/index name constants since they are 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%2F40130&comment_hash=6c07de0109e1638f2199880e876f00f0baea3c1f1bce959183ae56f41a6ce567&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=6c07de0109e1638f2199880e876f00f0baea3c1f1bce959183ae56f41a6ce567&reaction=dislike'>👎</a>



##########
superset/security/manager.py:
##########
@@ -2344,11 +2347,16 @@ def _update_vm_datasources_access(  # pylint: disable=too-many-locals
         sqlatable_table = SqlaTable.__table__  # pylint: disable=no-member
         chart_table = Slice.__table__  # pylint: disable=no-member
         new_database_name = target.database_name
-        datasets = (
-            self.session.query(SqlaTable)
-            .filter(SqlaTable.database_id == target.id)
-            .all()
-        )
+        # Bypass the soft-delete visibility filter: a soft-deleted dataset's perm
+        # strings (and its charts') must still be rewritten on a database rename,
+        # otherwise restoring that dataset later brings back stale dataset/schema/
+        # catalog permission strings referencing the old database name.
+        with skip_visibility_filter(self.session, SqlaTable):
+            datasets = (
+                self.session.query(SqlaTable)
+                .filter(SqlaTable.database_id == target.id)
+                .all()
+            )

Review Comment:
   **Suggestion:** Add an explicit type annotation for the new local variable so the added query result is typed. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The added local variable `datasets` is assigned a query result in new Python code and can be annotated with a concrete type, so this 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=002c43a5e37245d1b37a79589c699f0c&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=002c43a5e37245d1b37a79589c699f0c&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/security/manager.py
   **Line:** 2355:2359
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for the new local variable so the added query result is 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%2F40130&comment_hash=3c6038a921d024efa14634e7df51548379b16567d615d52059feaeb6def64a9f&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=3c6038a921d024efa14634e7df51548379b16567d615d52059feaeb6def64a9f&reaction=dislike'>👎</a>



##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +37,29 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete.
+    #
+    # Match rows whose catalog is either unset (NULL) or the database
+    # default — these are "the same physical table" the way
+    # ``DatasetDAO.validate_uniqueness`` treats them (``table.catalog or
+    # default``). Example rows are seeded with ``catalog = NULL`` while a
+    # connection that reports a default catalog (e.g. Postgres) would
+    # normalize to that default, so both must qualify. This still excludes
+    # an unrelated third catalog variant of the same table_name. Within the
+    # matched set, prefer live rows over soft-deleted ones via
+    # ``ORDER BY deleted_at IS NULL DESC``.
+    catalog = database.get_default_catalog()

Review Comment:
   **Suggestion:** Add an explicit type annotation to `catalog` (for example an optional string) to satisfy the rule requiring type hints for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new local variable `catalog` is introduced without an explicit type hint, and it is a value that can be annotated (likely an optional string returned from `get_default_catalog`). This matches the rule requiring type hints for 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=988f249d7f894ec3b4c81461f7bf7bcd&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=988f249d7f894ec3b4c81461f7bf7bcd&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/dashboard_utils.py
   **Line:** 55:55
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to `catalog` (for example an optional string) to satisfy the rule requiring type hints 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%2F40130&comment_hash=9c187555911a539252c5bf7de880fb92b3978cc37c9c002e590eea0317e911f8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=9c187555911a539252c5bf7de880fb92b3978cc37c9c002e590eea0317e911f8&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(datasets): soft-delete and restore [superset]

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

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

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

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

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


##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
superset/datasets/filters.py:
##########
@@ -51,3 +57,40 @@ def apply(self, query: Query, value: bool) -> Query:
                 )
             )
         return query
+
+
+class DatasetDeletedStateFilter(  # pylint: disable=too-few-public-methods
+    BaseDeletedStateFilter
+):
+    """Rison filter for the GET list that exposes soft-deleted datasets.
+
+    Soft-deleted rows are additionally scoped to the **restore audience**: only
+    the dataset's owners (or admins) may enumerate them. This mirrors
+    ``RestoreDatasetCommand``'s ``raise_for_ownership`` check, so a read-access
+    non-owner (who can see the dataset via ``datasource_access``) cannot list
+    soft-deleted datasets they could never restore. Live rows are unaffected —
+    they keep their normal ``DatasourceFilter`` 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 chart soft-delete rollouts).
+    """
+
+    arg_name = "dataset_deleted_state"
+    model = SqlaTable

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. Declining as style.



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()

Review Comment:
   Good catch — fixed in `b463c484b4`. The purge is now restricted to rows with `deleted_at` set (matching its comment's stated intent), so it can no longer hard-delete live datasets other suites created over the same AB tables.



##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)

Review Comment:
   Fixed in `b463c484b4` — wrapped in `try/finally` to match the sibling tests, so a failed assertion can no longer strand the soft-deleted dataset/database in the shared test DB.



##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,172 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())

Review Comment:
   Considered — keeping as-is: these are internal helpers/test scaffolding following the surrounding file's documentation and style conventions. Declining as style-tier; happy to revisit if a maintainer feels differently.



##########
superset/daos/base.py:
##########
@@ -81,9 +81,15 @@ def apply(self, column: Any, value: Any) -> Any:
         return op_func(column, value)
 
 
-def _escape_like(value: str) -> str:
-    """Escape LIKE/ILIKE wildcards to prevent wildcard injection."""
-    return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+def _escape_like(value: Any) -> str:
+    """Escape LIKE/ILIKE wildcards to prevent wildcard injection.
+
+    ``ColumnOperator.value`` is typed ``Any``, so a non-string payload (e.g. a
+    numeric JSON value) can reach a LIKE-family operator. Coerce to ``str`` so
+    such input degrades to a literal match instead of raising ``AttributeError``.
+    """
+    text = "" if value is None else str(value)
+    return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")

Review Comment:
   Resolved by extraction: the `_escape_like` change was removed from this PR (review feedback — unrelated to soft delete) and lives in #41653, which also fixes the issue this thread describes properly — `None` now matches **no** rows (SQL three-valued logic, `x LIKE NULL`) instead of coercing to `""` and matching everything, with tests reproducing the original failure.



##########
superset/translations/ar/LC_MESSAGES/messages.po:
##########
@@ -4697,6 +4697,9 @@ msgstr "تعذر إنشاء مجموعة بيانات."
 msgid "Dataset could not be duplicated."
 msgstr "تعذر تكرار مجموعة البيانات."
 
+msgid "Dataset could not be restored."
+msgstr ""

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



##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -191,19 +193,34 @@ def create_virtual_datasets(self):
     @pytest.fixture
     def create_datasets(self):
         with self.create_app().app_context():
+            # Purge any soft-deleted rows that occupy the unique constraint
+            stale = self.get_fixture_datasets()
+            for ds in stale:
+                db.session.delete(ds)
+            if stale:
+                db.session.commit()
+
             datasets = []
             admin = self.get_user("admin")
             main_db = get_main_database()
             for tables_name in self.fixture_tables_names:
                 datasets.append(self.insert_dataset(tables_name, [admin.id], main_db))
 
+            # Capture IDs eagerly — dataset objects may be detached after yield
+            dataset_ids = [ds.id for ds in datasets]
+
             yield datasets
 
-            # rollback changes
-            for dataset in datasets:
-                state = inspect(dataset)
-                if not state.was_deleted:
-                    db.session.delete(dataset)
+            # rollback changes (including soft-deleted rows)
+            for dataset_id in dataset_ids:

Review Comment:
   Following the surrounding file's conventions — these are local/test-scaffolding variables whose types are unambiguous from context; annotating each would add noise without changing what mypy checks. 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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3510301805


##########
superset/translations/it/LC_MESSAGES/messages.po:
##########
@@ -4602,6 +4602,9 @@ msgstr "La tua query non può essere salvata"
 msgid "Dataset could not be duplicated."
 msgstr "La tua query non può essere salvata"
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion to provide an Italian translation for the new error message is appropriate. While it is common for untranslated strings to fall back to English, providing a localized translation ensures a consistent user experience for Italian-speaking users, matching the established pattern in the file.
   
   **superset/translations/it/LC_MESSAGES/messages.po**
   ```
   msgid "Dataset could not be restored."
   msgstr "Il dataset non può essere ripristinato."
   ```



##########
superset/translations/fa/LC_MESSAGES/messages.po:
##########
@@ -4634,6 +4634,9 @@ msgstr "گزارش نمی‌تواند ایجاد شود."
 msgid "Dataset could not be duplicated."
 msgstr "مجموعه داده نمی‌تواند تکرار شود."
 
+msgid "Dataset could not be restored."
+msgstr ""

Review Comment:
   <!-- Bito Reply -->
   The suggestion to provide a Persian translation for the newly added message is appropriate. While it is true that catalogs may carry new message IDs untranslated until a translator fills them in, providing a translation for consistency with similar existing error messages in the same file improves the user experience for Persian-speaking users. Applying this suggestion ensures that the new error message is localized rather than falling back to English.
   
   **superset/translations/fa/LC_MESSAGES/messages.po**
   ```
   +msgid "Dataset 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(datasets): soft-delete and restore [superset]

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


##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -140,21 +143,116 @@ def import_dataset(  # noqa: C901
     force_data: bool = False,
     ignore_permissions: bool = False,
 ) -> SqlaTable:
+    """Import a dataset 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 dataset 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 charts/dashboards to a deleted dataset).
+    """
     can_write = ignore_permissions or security_manager.can_access(
         "can_write",
         "Dataset",
     )
-    existing = db.session.query(SqlaTable).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:
+    # Tracks whether we entered the soft-deleted mutation path so the
+    # downstream `sync` decision (below) can reflect that an
+    # implicit-restore re-import is a clean replacement, not a merge.
+    is_soft_deleted_match = False
+
+    if existing := find_existing_for_import(SqlaTable, 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 dataset* 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 (dup-check, `deleted_at` snapshot/flush, `MultipleResultsFound` rollback) 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 (`"Dataset was deleted and re-import requires can_write…"`).
   
   The same collapse exists in the charts (#40129) 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(datasets): soft-delete and restore [superset]

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


##########
tests/integration_tests/dashboard_utils.py:
##########
@@ -35,10 +36,23 @@ def get_table(
     schema: Optional[str] = None,
 ):
     schema = schema or get_example_default_schema()
+    # Bypass the soft-delete listener so the helper finds rows previously
+    # soft-deleted by other tests in the same session. Without the
+    # bypass, the listener hides them and a subsequent INSERT collides
+    # with the underlying ``(database_id, catalog, schema, table_name)``
+    # unique constraint that survives soft-delete. Prefer live rows over
+    # soft-deleted ones via ``ORDER BY deleted_at IS NULL DESC, id`` —
+    # the filter doesn't include ``catalog``, so it can match more than
+    # one row when a soft-deleted row coexists with a live row that
+    # differs only by catalog (e.g. NULL vs ``"public"``). ``.first()``
+    # plus the live-first ordering keeps the behaviour predictable
+    # without surfacing a ``MultipleResultsFound`` for that case.
     return (
         db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
         .filter_by(database_id=database.id, schema=schema, table_name=table_name)
-        .one_or_none()
+        .order_by(SqlaTable.deleted_at.is_(None).desc(), SqlaTable.id)
+        .first()

Review Comment:
   Correction: the first attempt (d66d661b36) filtered on only the database default catalog, which regressed find-or-create for the NULL-catalog example rows under the Postgres examples DB. Fixed properly in 891486b615 — now matches `catalog IS NULL OR catalog == default` (the way `validate_uniqueness`'s `table.catalog or default` treats them), keeping the seeded rows findable on every dialect while still excluding an unrelated third catalog.



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

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

   Re: the test-cleanup note — fixed in d66d661b36. The `TestDatasetSoftDelete` methods that soft-delete-then-restore are now wrapped in `try/finally` via a `_restore_dataset` helper, so a failed assertion can't strand a soft-deleted row into later tests.


-- 
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(datasets): soft-delete and restore (sc-106191) [superset]

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

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/40130?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 ([`fefb486`](https://app.codecov.io/gh/apache/superset/commit/fefb486d51495e2fc1ed6f0a3f7a9e517c52dc46?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/datasets/api.py](https://app.codecov.io/gh/apache/superset/pull/40130?src=pr&el=tree&filepath=superset%2Fdatasets%2Fapi.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGF0YXNldHMvYXBpLnB5) | 50.00% | [10 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40130?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/dataset/importers/v1/utils.py](https://app.codecov.io/gh/apache/superset/pull/40130?src=pr&el=tree&filepath=superset%2Fcommands%2Fdataset%2Fimporters%2Fv1%2Futils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvZGF0YXNldC9pbXBvcnRlcnMvdjEvdXRpbHMucHk=) | 0.00% | [6 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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/40130?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 (fefb486). Click for more details.
   > 
   > <details><summary>HEAD has 39 uploads less than BASE</summary>
   >
   >| Flag | BASE (823eb90) | HEAD (fefb486) |
   >|------|------|------|
   >|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   #40130      +/-   ##
   ==========================================
   - 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/40130/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/40130/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/40130/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/40130/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/40130/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/40130/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/40130/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/40130/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/40130?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(datasets): soft-delete and restore [superset]

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


##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,331 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+

Review Comment:
   **MEDIUM — Missing post-exception state assertion**
   
   After `pytest.raises(ImportFailedError)` exits, there is no assertion that `existing.deleted_at is not None`. A bug that clears `deleted_at` **before** raising the exception would pass this test undetected (Rule 26 — test that removes the change still passes).
   
   Add:
   ```python
   # Verify the permission check prevented the mutation
   assert existing.deleted_at is not None, (
       "deleted_at was cleared before the exception — mutation happened before raise"
   )
   ```



##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -1014,6 +1015,331 @@ def test_import_dataset_access_check(
         import_dataset(config)
 
 
+def test_import_soft_deleted_dataset_overwrite_restores_in_place(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Overwrite-importing a soft-deleted dataset must restore the row in
+    place rather than hard-delete-and-replace. A hard delete would
+    cascade through the chart back-reference and table_columns /
+    sql_metrics rows; in-place restore preserves them.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=True)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_restores_for_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import of a soft-deleted UUID is implicitly a
+    restore-and-update: the user is bringing the dataset back by
+    uploading it again. The same ownership rule as the overwrite path
+    applies, so an owner (or admin) succeeds without setting
+    overwrite=True.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    initial = import_dataset(config)
+    original_id = initial.id
+
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    admin = User(
+        first_name="Alice",
+        last_name="Doe",
+        email="adoe@example.org",
+        username="admin",
+        roles=[Role(name="Admin")],
+    )
+
+    with override_user(admin):
+        restored = import_dataset(config, overwrite=False)
+
+    assert restored.id == original_id
+    assert restored.deleted_at is None
+
+
+def test_import_soft_deleted_dataset_non_overwrite_raises_for_non_owner(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Non-overwrite re-import that would resurrect a soft-deleted dataset
+    must respect ownership: a non-owner without admin role cannot
+    restore-via-import. Mirrors the explicit /restore endpoint's check.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=True)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    import_dataset(config)
+    existing = db.session.query(SqlaTable).filter_by(uuid=config["uuid"]).one()
+    existing.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+    db.session.flush()
+
+    non_owner = User(
+        first_name="Bob",
+        last_name="Roe",
+        email="bob@example.org",
+        username="bob",
+        roles=[Role(name="Gamma")],
+    )
+
+    with override_user(non_owner):
+        with pytest.raises(ImportFailedError) as excinfo:
+            import_dataset(config, overwrite=False)
+    assert "permissions to restore" in str(excinfo.value)
+
+
+def test_import_soft_deleted_dataset_raises_when_caller_lacks_can_write(
+    mocker: MockerFixture,
+    session: Session,
+) -> None:
+    """
+    Case B: re-import of a soft-deleted UUID by a caller without
+    can_write must raise, not silently return the soft-deleted row.
+
+    Real-world scenario: a user has can_write Dashboard but not
+    can_write Dataset, and they import a dashboard zip that references
+    a soft-deleted dataset. Silently returning the row would let the
+    dashboard importer wire the dashboard's charts to a deleted dataset
+    and produce broken chart loads.
+    """
+    mocker.patch.object(security_manager, "can_access", return_value=False)
+
+    engine = db.session.get_bind()
+    SqlaTable.metadata.create_all(engine)  # pylint: disable=no-member
+
+    database = Database(database_name="my_database", sqlalchemy_uri="sqlite://")
+    db.session.add(database)
+    db.session.flush()
+
+    config = copy.deepcopy(dataset_fixture)
+    config["database_id"] = database.id
+
+    # Seed a soft-deleted dataset with the matching UUID directly, so the
+    # test doesn't need to flip permissions mid-test.
+    existing = SqlaTable(
+        table_name="soft_deleted_dataset",
+        database_id=database.id,
+        uuid=config["uuid"],
+        deleted_at=datetime(2026, 1, 1, 12, 0, 0),
+    )
+    db.session.add(existing)
+    db.session.flush()
+
+    with pytest.raises(ImportFailedError) as excinfo:
+        import_dataset(config, overwrite=False)
+    assert "can_write" in str(excinfo.value)
+

Review Comment:
   **MEDIUM — Missing post-exception state assertion (Case B path)**
   
   Same gap as the non-owner test: only the error message is asserted, not that `existing.deleted_at` is still set after the failed call. A regression that clears `deleted_at` before raising would pass this test.
   
   Add:
   ```python
   assert existing.deleted_at is not None, (
       "Case B: deleted_at was cleared before raising — mutation happened before raise"
   )
   ```



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

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

   Thanks @richardfogaca — addressed in 7096621f4b (and a small mypy follow-up in b65c253078).
   
   **\`utils.py:255\` — restore-via-import + \`MultipleResultsFound\` fallback**: you're right, the prior flow cleared \`deleted_at\` and flushed before \`SqlaTable.import_from_dict\` had a chance to apply the upload. If \`import_from_dict\` then raised \`MultipleResultsFound\` (legacy NULL-schema ambiguity at line 303), the fallback returned the row unmodified — meaning the operator got a "restore" they didn't ask for, with the upload contents silently dropped.
   
   Fix: snapshot \`existing.deleted_at\` before the clear, then check \`is_soft_deleted_match\` in the \`except MultipleResultsFound\` handler. If both conditions hold, restore the snapshotted \`deleted_at\` value, flush, and raise \`ImportFailedError\` with a message explaining the legacy-ambiguity cause:
   
   \`\`\`python
   if is_soft_deleted_match:
       existing.deleted_at = original_deleted_at
       db.session.flush()
       raise ImportFailedError(
           "Soft-deleted dataset has an ambiguous legacy duplicate "
           "(likely from the NULL-schema migration). Cannot restore-"
           "and-update via re-import; resolve the duplicate manually "
           "before retrying."
       ) from None
   \`\`\`
   
   The non-soft-deleted overwrite path keeps the legacy "return unmodified" contract from the original 2018 fix — that semantic still applies when the operator is doing an explicit overwrite, just not when soft-delete-restore is in play.
   
   Same commit also addresses a bito follow-up: the docstring on \`test_create_blocked_by_soft_deleted_logical_duplicate\` referenced the deleted \`test_restore_blocked_by_active_logical_duplicate\` (removed in c4560c1b39 as unreachable due to the DB-level unique constraint). Rewrote the docstring to describe what the test actually pins: \`validate_uniqueness\` bypasses the visibility filter so a soft-deleted twin blocks creates at the application layer with a clean 422.
   
   Thanks for the precise file:line trace through the flush ordering — the \`utils.py:228\` snapshot anchor made the fix shape obvious.


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

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

   Thanks @bito-code-review. Mixed response on the four items:
   
   **Addressed (13b9009fcb):**
   - ✅ One-line docstrings added to `upgrade()` and `downgrade()` in the migration.
   
   **Declining the filters.py:58-62 type annotation** (`Missing type annotation on model`):
   
   The parent class `BaseDeletedStateFilter` (in `superset/views/filters.py`) already declares the abstract attribute:
   
   ```python
   model: ClassVar[type[SoftDeleteMixin]]
   ```
   
   A subclass assignment `model = SqlaTable` is type-checked against the parent's annotation by mypy. Declaring `model: ClassVar[type[SoftDeleteMixin]] = SqlaTable` on the subclass would be redundant. The sibling classes `ChartDeletedStateFilter` and `DashboardDeletedStateFilter` follow the same pattern (bare assignment), and mypy passes on all three. Adding the annotation here would diverge from the established pattern without a correctness benefit.
   
   **Test-coverage suggestions — gated by integration vs unit:**
   
   - *Missing test for conflict guard in `importers/v1/utils.py:239-249`*: the conflict guard is covered end-to-end by `test_restore_blocked_by_active_logical_duplicate` and `test_create_blocked_by_soft_deleted_logical_duplicate` in `tests/integration_tests/datasets/soft_delete_tests.py` (lines 200–289). Those tests seed an active dataset with a matching `(database, catalog, schema, table_name)`, exercise the restore + create paths, and assert 422 + the post-state. A unit test would add isolation but no new behavioural coverage. Defer to integration coverage here.
   
   - *Missing `DatasetRestoreFailedError` test path*: similarly, the integration suite covers the restore endpoint's failure mode end-to-end. A unit-level analogue to `test_restore_dataset_forbidden_raises` that patches the DAO to raise an unexpected exception would be defensible but doesn't pin any contract that the integration tests don't already cover.
   
   Both items are reasonable as additions in a follow-up PR if the maintainers prefer unit-level coverage of every command-level error path, but I don't see them as blockers for 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(datasets): soft-delete and restore [superset]

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

   Thanks @richardfogaca (and the PR review agent) — all three of your functional concerns are addressed:
   
   **`superset/datasets/api.py:963` — restore can produce two live datasets at one physical table** (the headline concern): fixed in `0591115434` with two-layer defense:
   
   1. `RestoreDatasetCommand.validate()` overrides the base with an `_has_active_logical_duplicate(model)` check that raises a new `DatasetLogicalDuplicateError` (HTTP 422) when another active dataset references the same `(database_id, catalog, schema, table_name)`.
   2. `DatasetDAO.validate_uniqueness` and `validate_update_uniqueness` now run with `execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})`, so a soft-deleted row also blocks new creates at the same logical identity. Closes the gap from the create side.
   
   Mirrors the slug-conflict pattern on dashboards. Integration tests at `tests/integration_tests/datasets/soft_delete_tests.py:200-289` cover both the restore-blocked and create-blocked flows.
   
   **`superset/commands/dataset/importers/v1/utils.py:228` — restore-via-import path**: same commit adds the duplicate check before `existing.deleted_at = None`, raising `ImportFailedError` with a descriptive message if a live duplicate exists. Aligns the importer behaviour with the explicit restore endpoint.
   
   **`superset/daos/datasource.py:101` — Core-select bypass in `build_dataset_query`**: same commit adds an explicit `ds_q = ds_q.where(ds_table.c.deleted_at.is_(None))` predicate. Soft-deleted datasets no longer count toward `GET /api/v1/datasource/` totals or pagination slots.
   
   Test coverage at integration level + unit level for the restore-side guard. Thanks for the precise, mechanism-naming write-up — the "logical-vs-physical uniqueness" framing was exactly what made the three concerns hang together.


-- 
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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3397305342


##########
tests/unit_tests/commands/dataset/restore_test.py:
##########
@@ -0,0 +1,169 @@
+# 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 RestoreDatasetCommand."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Stable UUIDs make the test boundary realistic: the production command
+# loads by UUID, not integer ID. The test only mocks the DAO lookup, but
+# the argument shape should still match.
+_DATASET_UUID = str(uuid.uuid4())
+_MISSING_UUID = str(uuid.uuid4())
+
+
+def test_restore_dataset_clears_deleted_at(app_context: None) -> None:
+    """RestoreDatasetCommand.run() restores a soft-deleted dataset."""
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    dataset.id = 1
+
+    with (
+        patch(
+            "superset.daos.dataset.DatasetDAO.find_by_id", return_value=dataset
+        ) as mock_find,
+        patch("superset.commands.restore.security_manager") as mock_sec,
+        patch(
+            "superset.daos.dataset.DatasetDAO.has_active_logical_duplicate",
+            return_value=False,
+        ),
+    ):
+        mock_sec.raise_for_ownership.return_value = None
+
+        cmd = RestoreDatasetCommand(_DATASET_UUID)
+        cmd.run()
+
+    mock_find.assert_called_once()
+    dataset.restore.assert_called_once()
+
+
+def test_restore_dataset_not_found_raises(app_context: None) -> None:
+    """RestoreDatasetCommand raises DatasetNotFoundError for missing dataset."""
+    from superset.commands.dataset.exceptions import DatasetNotFoundError
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    with patch("superset.daos.dataset.DatasetDAO.find_by_id", return_value=None):
+        cmd = RestoreDatasetCommand(_MISSING_UUID)
+        with pytest.raises(DatasetNotFoundError):
+            cmd.run()
+
+
+def test_restore_active_dataset_raises_not_found(app_context: None) -> None:
+    """RestoreDatasetCommand raises DatasetNotFoundError for non-deleted dataset."""
+    from superset.commands.dataset.exceptions import DatasetNotFoundError
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+
+    dataset = MagicMock()
+    dataset.deleted_at = None  # not soft-deleted
+
+    with patch("superset.daos.dataset.DatasetDAO.find_by_id", return_value=dataset):
+        cmd = RestoreDatasetCommand(_DATASET_UUID)
+        with pytest.raises(DatasetNotFoundError):
+            cmd.run()
+
+
+def test_restore_dataset_forbidden_raises(app_context: None) -> None:
+    """RestoreDatasetCommand raises DatasetForbiddenError on permission check."""
+    from superset.commands.dataset.exceptions import DatasetForbiddenError
+    from superset.commands.dataset.restore import RestoreDatasetCommand
+    from superset.exceptions import SupersetSecurityException
+
+    dataset = MagicMock()
+    dataset.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 it complies with the rule that all new functions must be documented. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The helper function `raise_security` is newly introduced 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=27476dfd21f8477ab33f58c077329297&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=27476dfd21f8477ab33f58c077329297&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/dataset/restore_test.py
   **Line:** 95:96
   **Comment:**
   	*Custom Rule: Add an inline docstring to the newly introduced helper function so it complies with the rule that all new functions must be 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%2F40130&comment_hash=deaf6187e54690890410d3c95fa3c67190d0410f2a3c4c9a21f385425fd4ce5c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=deaf6187e54690890410d3c95fa3c67190d0410f2a3c4c9a21f385425fd4ce5c&reaction=dislike'>👎</a>



##########
tests/unit_tests/dao/base_dao_test.py:
##########
@@ -52,6 +52,40 @@ class TestDAOWithNoneModel(BaseDAO[MockModel]):
 # =============================================================================
 
 
+def test_escape_like_coerces_non_string_values() -> None:
+    """``_escape_like`` coerces non-str input rather than raising.
+
+    ``ColumnOperator.value`` is typed ``Any``, so a numeric or ``None`` value can
+    reach a LIKE-family operator; it must degrade to a literal match instead of
+    raising ``AttributeError`` on ``str.replace``.
+    """
+    # Wildcards in string input are still escaped, backslash first.
+    assert _escape_like("50%_off") == "50\\%\\_off"
+    assert _escape_like("a\\b") == "a\\\\b"
+    # Non-string input is coerced, not crashed.
+    assert _escape_like(5) == "5"
+    assert _escape_like(3.5) == "3.5"
+    assert _escape_like(None) == ""
+
+
+def test_like_operator_accepts_non_string_value() -> None:
+    """A non-string value flows through a LIKE operator without raising.
+
+    Guards the ``_escape_like`` coercion end-to-end: before it, ``ct``/``like``
+    with a numeric value raised ``AttributeError`` deep in operator application.
+    """
+    Base_test = declarative_base()  # noqa: N806
+
+    class TestModel(Base_test):  # type: ignore
+        __tablename__ = "test_model_like"
+        id = Column(Integer, primary_key=True)
+        name = Column(String(50))

Review Comment:
   **Suggestion:** Add a short class docstring to this newly introduced inner model class so new classes are documented inline. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   This is a newly introduced class in a new hunk, and it does not include a docstring. The custom rule requires new Python classes to be documented inline, so the suggestion matches a real violation.
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c12851abab824d95806b975386bfd8a8&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=c12851abab824d95806b975386bfd8a8&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/base_dao_test.py
   **Line:** 79:82
   **Comment:**
   	*Custom Rule: Add a short class docstring to this newly introduced inner model class so new 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%2F40130&comment_hash=5f63bfd120e16a9d9fd29954037ea0b254b2dfb3c7ab755df397075d9654ac85&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=5f63bfd120e16a9d9fd29954037ea0b254b2dfb3c7ab755df397075d9654ac85&reaction=dislike'>👎</a>



##########
superset/commands/dataset/restore.py:
##########
@@ -0,0 +1,54 @@
+# 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 dataset."""
+
+from superset.commands.dataset.exceptions import (
+    DatasetForbiddenError,
+    DatasetLogicalDuplicateError,
+    DatasetNotFoundError,
+    DatasetRestoreFailedError,
+)
+from superset.commands.restore import BaseRestoreCommand
+from superset.connectors.sqla.models import SqlaTable
+from superset.daos.dataset import DatasetDAO
+
+
+class RestoreDatasetCommand(BaseRestoreCommand[SqlaTable]):
+    """Restore a soft-deleted dataset by clearing its ``deleted_at`` field.
+
+    Most behaviour is inherited from ``BaseRestoreCommand``. The override
+    here adds a logical-duplicate check: ``SqlaTable`` uniqueness is
+    enforced in application code (no DB constraint), so it is possible
+    for another active dataset to have claimed the same ``(database_id,
+    catalog, schema, table_name)`` while this one was soft-deleted.
+    Restore should not silently produce two active datasets pointing at
+    the same physical table.
+    """
+
+    dao = DatasetDAO
+    not_found_exc = DatasetNotFoundError
+    forbidden_exc = DatasetForbiddenError
+    restore_failed_exc = DatasetRestoreFailedError
+
+    def validate(self) -> SqlaTable:  # type: ignore[override]
+        model = super().validate()

Review Comment:
   **Suggestion:** Add an inline docstring to the new method so the function is documented as required for newly added Python functions. [custom_rule]
   
   **Severity Level:** Minor ⚠️
   <details>
   <summary><b>Why it matters? 🤔 </b></summary>
   
   The new method `validate` is added without a docstring. The provided 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=55c0fec0aa0b469cba2ca7f5d4ea5c32&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=55c0fec0aa0b469cba2ca7f5d4ea5c32&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/dataset/restore.py
   **Line:** 47:48
   **Comment:**
   	*Custom Rule: Add an inline docstring to the new method so the function is documented as required for newly added Python functions.
   
   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%2F40130&comment_hash=ee4067891d5e6f96b0f1ab5caf0befba213388a431aac5a1b325b56ea1af88d7&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40130&comment_hash=ee4067891d5e6f96b0f1ab5caf0befba213388a431aac5a1b325b56ea1af88d7&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(datasets): 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 #40130:
URL: https://github.com/apache/superset/pull/40130#discussion_r3398716271


##########
tests/integration_tests/datasets/soft_delete_tests.py:
##########
@@ -0,0 +1,462 @@
+# 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 dataset 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.core import Database
+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,
+    GAMMA_USERNAME,
+)
+
+
+def _restore_dataset(dataset_id: int) -> None:
+    """Restore a soft-deleted dataset (cleanup helper).
+
+    Module-level so every test class in this file can use it. Used in
+    ``finally`` blocks so a failed assertion can't strand a soft-deleted
+    row and leak it into later tests; re-queries with the
+    visibility-filter bypass and only restores if still soft-deleted.
+    """
+    row = (
+        db.session.query(SqlaTable)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+        .filter(SqlaTable.id == dataset_id)
+        .one_or_none()
+    )
+    if row is not None and row.deleted_at is not None:
+        row.restore()
+        db.session.commit()
+
+
+class TestDatasetSoftDelete(SupersetTestCase):
+    """Tests for dataset soft-delete behaviour (T015, T018)."""
+
+    def _get_example_dataset_id(self) -> int:
+        """Get an existing example dataset ID for testing."""
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None, "No datasets found — load examples first"
+        return dataset.id
+
+    def _restore_dataset(self, dataset_id: int) -> None:
+        """Class-method shim over the module-level helper (existing call sites)."""
+        _restore_dataset(dataset_id)
+
+    def test_delete_dataset_soft_deletes(self) -> None:
+        """DELETE should set deleted_at instead of removing the row."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            row = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one_or_none()
+            )
+            assert row is not None
+            assert row.deleted_at is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_excluded_from_list(self) -> None:
+        """GET /api/v1/dataset/ should not include soft-deleted datasets."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rv = self.client.get("/api/v1/dataset/")
+            data = json.loads(rv.data)
+            ids = [d["id"] for d in data["result"]]
+            assert dataset_id not in ids
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_soft_deleted_dataset_included_in_list_when_requested(self) -> None:
+        """GET /api/v1/dataset/ with dataset_deleted_state=include returns deleted datasets."""  # noqa: E501
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            rison_query = (
+                "(filters:!((col:id,opr:dataset_deleted_state,value:include)))"
+            )
+            rv = self.client.get(f"/api/v1/dataset/?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"] == dataset_id),
+                None,
+            )
+            assert deleted_row is not None
+            assert deleted_row["deleted_at"] is not None
+        finally:
+            self._restore_dataset(dataset_id)
+
+    def test_only_filter_returns_only_soft_deleted_datasets(self) -> None:
+        """dataset_deleted_state=only excludes live rows and returns only deleted ones."""  # noqa: E501
+        ids = [row.id for row in db.session.query(SqlaTable).limit(2).all()]
+        assert len(ids) >= 2, "Need at least two example datasets for this test"
+        live_id, deleted_id = ids[0], ids[1]
+        self.login(ADMIN_USERNAME)
+
+        try:
+            rv = self.client.delete(f"/api/v1/dataset/{deleted_id}")
+            assert rv.status_code == 200
+
+            rison_query = "(filters:!((col:id,opr:dataset_deleted_state,value:only)))"
+            rv = self.client.get(f"/api/v1/dataset/?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
+        finally:
+            self._restore_dataset(deleted_id)
+
+    def _hard_delete_created(self, dataset_id: int, database: Database) -> None:
+        """Remove a test-created dataset + its database (visibility bypassed)."""
+        row = (
+            db.session.query(SqlaTable)
+            .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+            .filter(SqlaTable.id == dataset_id)
+            .one_or_none()
+        )
+        if row:
+            db.session.delete(row)
+        db.session.delete(database)
+        db.session.commit()
+
+    def test_deleted_state_list_shows_owner_their_own_deleted(self) -> None:
+        """A non-admin owner can still enumerate their own soft-deleted datasets.
+        Deleted-state scoping mirrors the restore audience, so it must not lock
+        owners out of their own trash."""
+        alpha = self.get_user(ALPHA_USERNAME)
+        database = Database(database_name="sd_owner_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(
+            table_name="sd_owner_tbl", database=database, owners=[alpha]
+        )
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        dataset.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+        db.session.commit()
+
+        self.login(ALPHA_USERNAME)
+        rison_query = (
+            "(filters:!((col:id,opr:dataset_deleted_state,value:only)),page_size:200)"
+        )
+        rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+        assert rv.status_code == 200
+        ids = [r["id"] for r in json.loads(rv.data)["result"]]
+        assert dataset_id in ids
+
+        self._hard_delete_created(dataset_id, database)
+
+    def test_deleted_state_list_hides_non_owned_from_read_access_user(self) -> None:
+        """A read-access non-owner must not enumerate a dataset once it is
+        soft-deleted.
+
+        Gamma is granted ``datasource_access`` to the dataset, so
+        ``DatasourceFilter`` makes it visible to gamma while 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 = self.get_user(ADMIN_USERNAME)
+        database = Database(database_name="sd_acl_db", sqlalchemy_uri="sqlite://")
+        db.session.add(database)
+        db.session.flush()
+        dataset = SqlaTable(table_name="sd_acl_tbl", database=database, owners=[admin])
+        db.session.add(dataset)
+        db.session.commit()
+        dataset_id = dataset.id
+
+        gamma_role = security_manager.find_role("Gamma")
+        pvm = security_manager.add_permission_view_menu(
+            "datasource_access", dataset.perm
+        )
+        gamma_role.permissions.append(pvm)
+        db.session.commit()
+
+        try:
+            # Precondition: gamma can see the dataset while it is live.
+            self.login(GAMMA_USERNAME)
+            rv = self.client.get("/api/v1/dataset/?q=(page_size:200)")
+            assert dataset_id in [r["id"] for r in json.loads(rv.data)["result"]], (
+                "precondition: gamma should see the live dataset via datasource access"
+            )
+
+            reloaded = (
+                db.session.query(SqlaTable)
+                .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {SqlaTable}})
+                .filter(SqlaTable.id == dataset_id)
+                .one()
+            )
+            reloaded.deleted_at = datetime(2026, 1, 1, 12, 0, 0)
+            db.session.commit()
+
+            for value in ("include", "only"):
+                rison_query = (
+                    f"(filters:!((col:id,opr:dataset_deleted_state,value:{value})),"
+                    "page_size:200)"
+                )
+                rv = self.client.get(f"/api/v1/dataset/?q={rison_query}")
+                assert rv.status_code == 200
+                ids = [r["id"] for r in json.loads(rv.data)["result"]]
+                assert dataset_id not in ids, (
+                    "read-access non-owner must not enumerate a soft-deleted "
+                    f"dataset via dataset_deleted_state={value}"
+                )
+        finally:
+            pvm = security_manager.find_permission_view_menu(
+                "datasource_access", dataset.perm
+            )
+            if pvm:
+                security_manager.del_permission_role(gamma_role, pvm)
+            db.session.commit()
+            self._hard_delete_created(dataset_id, database)
+
+    def test_no_cascade_to_dependent_charts(self) -> None:
+        """Soft-deleting a dataset should NOT cascade to its charts (FR-009, T018)."""
+        dataset_id = self._get_example_dataset_id()
+        self.login(ADMIN_USERNAME)
+
+        # Find charts that depend on this dataset
+        dependent_charts = (
+            db.session.query(Slice)
+            .filter(Slice.datasource_id == dataset_id, Slice.datasource_type == "table")
+            .all()
+        )
+        dependent_chart_ids = [c.id for c in dependent_charts]
+
+        try:
+            # Soft-delete the dataset
+            rv = self.client.delete(f"/api/v1/dataset/{dataset_id}")
+            assert rv.status_code == 200
+
+            # Dependent charts should still be active (no cascade). On this
+            # branch ``Slice`` does not yet carry ``deleted_at`` (added by the
+            # charts soft-delete PR), so we only verify the row is still
+            # loadable through the default visibility-filtered query — which
+            # would return None if the chart had been soft-deleted.
+            for chart_id in dependent_chart_ids:
+                chart = (
+                    db.session.query(Slice).filter(Slice.id == chart_id).one_or_none()
+                )
+                assert chart is not None, f"Chart {chart_id} should still be active"
+        finally:
+            self._restore_dataset(dataset_id)
+
+
+class TestDatasetRestore(SupersetTestCase):
+    """Tests for dataset restore behaviour (T027)."""
+
+    def _get_example_dataset(self) -> SqlaTable:
+        dataset = db.session.query(SqlaTable).first()
+        assert dataset is not None
+        return dataset
+
+    def test_restore_soft_deleted_dataset(self) -> None:
+        """POST /api/v1/dataset/<uuid>/restore should make it visible again."""
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 200
+
+        rv = self.client.get(f"/api/v1/dataset/{dataset_id}")
+        assert rv.status_code == 200
+
+    def test_restore_failure_returns_422(self) -> None:
+        """A failure during restore surfaces as a clean 422 via the
+        ``DatasetRestoreFailedError`` handler rather than an unhandled 500.
+
+        ``RestoreDatasetCommand.run`` wraps the restore in ``@transaction``
+        and rethrows ``DatasetRestoreFailedError`` on any underlying
+        SQLAlchemy error; this pins that the endpoint maps it to 422.
+        """
+        from unittest.mock import patch
+
+        from superset.commands.dataset.exceptions import (
+            DatasetRestoreFailedError,
+        )
+
+        dataset = self._get_example_dataset()
+        dataset_id = dataset.id
+        dataset_uuid = str(dataset.uuid)
+        self.login(ADMIN_USERNAME)
+        self.client.delete(f"/api/v1/dataset/{dataset_id}")
+
+        with patch(
+            "superset.commands.dataset.restore.RestoreDatasetCommand.run",
+            side_effect=DatasetRestoreFailedError(),
+        ):
+            rv = self.client.post(f"/api/v1/dataset/{dataset_uuid}/restore")
+        assert rv.status_code == 422
+
+        # Cleanup: the mocked restore left the example dataset soft-deleted.
+        _restore_dataset(dataset_id)

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing finally block in test cleanup</b></div>
   <div id="fix">
   
   Wrap the dataset restore call and assertion in a `try/finally` block to ensure `_restore_dataset(dataset_id)` always runs, mirroring the pattern in other tests.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a8946</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/integration_tests/security_tests.py:
##########
@@ -560,6 +560,72 @@ def test_after_update_database__perm_datasource_access(self):
         db.session.delete(tmp_db1)
         db.session.commit()
 
+    def test_after_update_database__perm_datasource_access_soft_deleted(self):
+        """A soft-deleted dataset's perm strings must still be rewritten on a
+        database rename. The maintenance query bypasses the soft-delete
+        visibility filter so hidden datasets are updated too; otherwise
+        restoring the dataset later would resurrect stale dataset/schema/catalog
+        permission strings pointing at the old database name.
+        """
+        from datetime import datetime  # noqa: PLC0415
+
+        from superset.constants import SKIP_VISIBILITY_FILTER_CLASSES  # noqa: PLC0415
+
+        security_manager.on_view_menu_after_update = Mock()

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Mock setup without verification</b></div>
   <div id="fix">
   
   The test mocks `on_view_menu_after_update` at line 574 but never verifies the hook was called. The implementation at `superset/security/manager.py:2056` invokes this hook for each updated dataset. Compare with the existing test at line 548 which includes `assert_has_calls` verification.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a8946</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