aminghadersohi commented on code in PR #40129:
URL: https://github.com/apache/superset/pull/40129#discussion_r3342330668


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

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



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

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



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

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



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

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



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

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



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to