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/08 18:58:28 UTC

[PR] feat(core): SoftDeleteMixin and restore infrastructure [superset]

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

   ### SUMMARY
   
   First of four PRs decomposing the soft-delete work for charts, dashboards, and datasets ([sc-103157](https://app.shortcut.com/preset/story/103157), [SIP-208](https://github.com/apache/superset/issues/39464) — passed 2026-05-08).
   
   This PR ships the **infrastructure** with **zero behaviour change**. No model uses the mixin yet, no migration runs, no API surface changes, no permission migrations. Everything in this PR is dormant until the entity-rollout PRs (linked below) opt their concrete entities in.
   
   Tracked at [sc-106188](https://app.shortcut.com/preset/story/106188).
   
   #### Entity rollouts (forthcoming, depend on this PR)
   - [sc-106189](https://app.shortcut.com/preset/story/106189) — Soft-delete and restore for **charts**
   - [sc-106190](https://app.shortcut.com/preset/story/106190) — Soft-delete and restore for **dashboards**
   - [sc-106191](https://app.shortcut.com/preset/story/106191) — Soft-delete and restore for **datasets**
   
   Each entity-rollout PR adds `SoftDeleteMixin` to its model, ships a one-table migration adding the `deleted_at` column + index, wires the entity-specific concrete subclasses of the abstractions in this PR, and adds entity-level integration tests.
   
   #### What this PR ships
   
   **Runtime mechanism** (`superset/models/helpers.py`, `superset/initialization/__init__.py`)
   
   - `SoftDeleteMixin` — adds a nullable `deleted_at` column, `is_deleted` hybrid property, `not_deleted()` filter clause, `soft_delete()` and `restore()` methods.
   - `_add_soft_delete_filter` — `do_orm_execute` listener using SQLAlchemy's officially-recommended pattern ([Mike Bayer / sqlalchemy#7973](https://github.com/sqlalchemy/sqlalchemy/issues/7973#issuecomment-1112561295)). Globally excludes soft-deleted rows from every ORM SELECT (including relationship lazy loads) for any class inheriting `SoftDeleteMixin`. **No-op until something inherits the mixin.**
   - Two opt-out paths:
     - **Per-query** — `execution_options(skip_visibility_filter=True)`. The narrow tool, for non-user-facing code paths (admin tooling, import re-lookups).
     - **Per-request** — `flask.g.skip_visibility_filter = True`. The broad tool, reserved for user-facing list-endpoint filters that explicitly ask to surface soft-deleted rows for the rest of the request.
   
   **BaseDAO surface** (`superset/daos/base.py`, `superset/daos/database.py`)
   
   - `BaseDAO.soft_delete(items)` — calls `item.soft_delete()` on each.
   - `BaseDAO.hard_delete(items)` — calls `db.session.delete(item)` on each (the original `BaseDAO.delete` behaviour, renamed and preserved).
   - `BaseDAO.delete(items)` — routes to soft for `SoftDeleteMixin`-inheriting models, hard otherwise. **Backwards-compatible**: until any model inherits the mixin, `delete()` continues to call `hard_delete()` exactly as before.
   - `find_by_id`, `find_by_uuid`, `find_by_ids`, `_find_by_column` gain a `skip_visibility_filter: bool = False` parameter, mirroring the existing `skip_base_filter` parameter.
   - `DatabaseDAO.find_by_id` is updated for signature compatibility.
   
   **Restore abstractions** (`superset/commands/restore.py`, `superset/views/filters.py`, `superset/commands/importers/v1/utils.py`, `superset/constants.py`)
   
   - `BaseRestoreCommand[T]` — `T` bound to `SoftDeleteMixin`. Subclasses provide `dao`, `not_found_exc`, `forbidden_exc`. Validates ownership via `security_manager.raise_for_ownership` (identical to existing delete commands; admins always pass).
   - `BaseDeletedStateFilter` — base class for per-entity rison filters (`*_deleted_state` with values `include` / `only`). Sets `g.skip_visibility_filter = True` to opt the request out of the global filter.
   - `find_existing_for_import(model_cls, uuid)` — helper for v1 importer pipelines that bypasses the visibility filter on UUID lookup and hard-deletes any soft-deleted match before returning so re-imports don't hit a unique-constraint violation on `uuid`.
   - `MODEL_API_RW_METHOD_PERMISSION_MAP["restore"] = "write"` — so future per-entity `/restore` endpoints inherit `can_write` (the same permission as `delete`). **No new permission, no role migration**.
   - `BaseSupersetModelRestApi.pre_get_list` augments list responses with `deleted_at` when the request has opted into seeing soft-deleted rows.
   
   #### Design decisions documented in code
   
   - **No feature flag** — soft-delete is always-on once a model inherits the mixin. Per [SIP-208 discussion](https://github.com/apache/superset/issues/39464) and the sc-103157 thread, a global flag risks confusing partial states.
   - **No cascade in V1** — each entity is soft-deleted independently; cascade is out of scope and tracked separately.
   - **Permission model mirrors delete exactly** — endpoint-level `can_write`, resource-level `raise_for_ownership`. No new permission plumbing.
   - **`datetime.now()` (naive)** for `deleted_at` to match `AuditMixinNullable.changed_on` precedent ([PR #33693 reverted UTC](https://github.com/apache/superset/pull/33693) on those columns; if/when audit columns move to UTC-aware, soft-delete should follow).
   - **Compatible with future SQLAlchemy-Continuum adoption** for full entity versioning (confirmed compatible with SQLAlchemy 1.4.54).
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   
   N/A — backend-only infrastructure with no runtime behaviour change.
   
   ### TESTING INSTRUCTIONS
   
   ```bash
   pytest tests/unit_tests/models/test_soft_delete_mixin.py tests/unit_tests/daos/test_base_dao_soft_delete.py -v
   ```
   
   Expected: 10 passed.
   
   The tests use synthetic in-memory models (`_SoftDeletable`) that inherit `SoftDeleteMixin` directly, exercising the listener, mixin methods, and BaseDAO routing without any real Superset entity. Real entities acquire the mixin in the entity-rollout PRs above.
   
   Optional sanity check that nothing broke in master behaviour (since `BaseDAO.delete` is now routed):
   
   ```bash
   pytest tests/unit_tests/daos/ tests/unit_tests/models/ -q
   ```
   
   Expected: all green.
   
   ### ADDITIONAL INFORMATION
   
   - [X] Has associated issue: [sc-106188](https://app.shortcut.com/preset/story/106188), [SIP-208 #39464](https://github.com/apache/superset/issues/39464)
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration — *(no, migrations land in the entity-rollout PRs)*
   - [X] Introduces new feature or API — *(adds BaseDAO methods, BaseRestoreCommand, BaseDeletedStateFilter, find_existing_for_import, and `restore` -> "write" mapping; no user-facing API surface yet)*
   - [ ] Removes existing feature or API
   
   #### Reviewer notes
   
   A reviewer may reasonably ask: *"why ship abstractions with no callers in master?"* Defenses:
   
   1. **The callers exist** — the three entity-rollout PRs (sc-106189 / sc-106190 / sc-106191) are queued behind this one and each consumes the abstractions. The original mono-PR (#39286) demonstrated all three callers in a single diff; the decomposition just spreads them across reviewable PRs while keeping the abstraction as a single, focused unit.
   2. **The unit tests prove the contract.** Synthetic `_SoftDeletable` models exercise the mixin, listener, and BaseDAO routing. The tests would fail if the abstractions were broken.
   3. **The git history of the original branch** shows the abstractions emerged from concrete duplication that was reviewed (Bob Martin–style clean-code review of the mono-PR extracted them). This PR is the *reviewed* form, not a speculative one.
   


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   > @richardfogaca I think there's a better solution to the `raise_for_ownership` issue, which is to always supply the "skip" filter there---there's no logical reason to be omitting soft-deleted items in "check owners". That eliminates a lot of the complexity of this PR
   
   I'm seeing that my "better solution" is actually more of a whack-a-mole thing because there are several more places where `execution_options` is insufficient for propagating the "include soft-deletion" flag.  The general problem is that any code path that constructs a new Query from the model class — without taking the bypass option as an explicit parameter — won't inherit the flag. The confirmed instance is `Flask-AppBuilder`'s `SQLAInterface.get_outer_query_from_inner_query`: when list_columns contains many-to-many fields, the outer fetch query is built from a fresh `session.query(self.obj)` and joined to the filtered query as a `.subquery()` Core construct — at which point the bypass option (which lived on the filtered inner Query) is gone. The listener fires on the outer query, sees no bypass, attaches its `with_loader_criteria(where_not_deleted)`, and the result query collides with the inner subquery's filter and returns zero rows. Other framework or future code paths c
 ould lose the option the same way; auditing all of them isn't realistic.
   
   Either I have to fix all these cases individually ("if flag is on original then add flag to subquery...") and _hope_ that I catch them all, or else make the flag ambient in either the request or the session.  I'm leaning towards doing it in the session.


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @richardfogaca I think there's a better solution to the `raise_for_ownership` issue, which is to always supply the "skip" filter there---there's no logical reason to be omitting soft-deleted items in the "check owners" check there.  That eliminates a lot of the complexity of 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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   After some discussion with AI about the maintainability of the official side-effecting pattern, I'd like to create a follow-up PR after this one to wrap the per-request bypass in a context manager.  
   
   The issue here is that it's easy for a dev to forget to reset the flag in try/catch:
   
     - Forgetting the `try/finally` and leaving the flag set for the rest of the request                                                                                                                 
     - Cleaning up with `setattr(g, SKIP_VISIBILITY_FILTER, False)` instead of restoring the captured previous value, which breaks composition when a caller is already inside a bypass
   
   Both cases can be eliminated by a small context manager next to the `SKIP_VISIBILITY_FILTER` constant (via claude):                                                                                                    
                                                                                                                                                                                                         
   ```python                                                                                                                                                                                           
   @contextmanager                                   
   def skip_visibility_filter() -> Iterator[None]:
         """Opt the current request out of the soft-delete listener for the
         duration of the block. Restores the previous value on exit,                                                                                                                                     
         including the exception path. Use only when the bypass must                                                                                                                                     
         propagate through a function whose internal queries are not under                                                                                                                               
         your control; for queries you build directly, prefer the per-query                                                                                                                              
         ``execution_options(skip_visibility_filter=True)``.
         """                                                                                                                                                                                             
         previous = getattr(g, SKIP_VISIBILITY_FILTER, False)
         setattr(g, SKIP_VISIBILITY_FILTER, True)                                                                                                                                                        
         try:                                                                                                                                                                                            
             yield                                
         finally:                                                                                                                                                                                        
             setattr(g, SKIP_VISIBILITY_FILTER, previous)
   ```
                                                                                                                                                                                                         
   Call site in BaseRestoreCommand.validate becomes:
   
   ```python                                                                                                                                                                                                      
   with skip_visibility_filter():                    
         try:                                     
             security_manager.raise_for_ownership(model)
         except SupersetSecurityException as ex:                                                                                                                                                         
             raise self.forbidden_exc() from ex
   ```
   


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/models/helpers.py:
##########
@@ -654,7 +655,94 @@ def created_on_humanized(self) -> str:
 
     @renders("changed_on")
     def modified(self) -> Markup:
-        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')
+        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')  # noqa: S704
+
+
+SKIP_VISIBILITY_FILTER = "skip_visibility_filter"
+
+
+class SoftDeleteMixin:
+    """Mixin that adds soft-delete support to a SQLAlchemy model.
+
+    Adds a nullable ``deleted_at`` column. When set, the row is treated as
+    deleted and excluded from standard ORM queries via a global
+    ``do_orm_execute`` listener registered at app init.
+
+    Delete commands should call ``soft_delete()`` to mark the object as
+    deleted.  Use ``BaseDAO.delete()`` (which calls ``session.delete()``)
+    for permanent hard deletion.
+
+    See also: ``_add_soft_delete_filter`` (the listener function) and
+    ``SKIP_VISIBILITY_FILTER`` (the execution-option key used to opt out
+    of the filter in restore commands and admin tooling).
+    """
+
+    deleted_at = sa.Column(sa.DateTime, nullable=True, index=True)
+
+    @hybrid_property
+    def is_deleted(self) -> bool:
+        return self.deleted_at is not None
+
+    @is_deleted.expression  # type: ignore
+    def is_deleted(cls) -> ColumnElement:  # noqa: N805
+        return cls.deleted_at.is_not(None)
+
+    @classmethod
+    def not_deleted(cls) -> ColumnElement:
+        """Filter clause for active (non-deleted) rows."""
+        return cls.deleted_at.is_(None)
+
+    def soft_delete(self) -> None:
+        """Mark this object as soft-deleted."""
+        # Naive datetime, mirroring AuditMixinNullable.changed_on. PR #33693
+        # reverted a UTC migration on the audit columns; if/when those move
+        # to UTC-aware, this assignment should follow.
+        self.deleted_at = datetime.now()

Review Comment:
   Four reasons the naive `datetime.now()` is deliberate here:
   
   1. **Project precedent.** `AuditMixinNullable.changed_on` and `.created_on` use naive `datetime.now()`. [PR #33693](https://github.com/apache/superset/pull/33693) explicitly reverted a UTC migration on those audit columns. `deleted_at` is semantically an audit column and should match the convention; diverging would produce a model with mixed-TZ columns.
   
   2. **Schema mismatch.** The `deleted_at` column ships as `DateTime`, not `DateTime(timezone=True)`. Storing a TZ-aware Python value into a TZ-naive Postgres/MySQL column silently strips the timezone on insert, so the suggestion would not actually achieve TZ-awareness end-to-end — it would just introduce a representation gap between Python and the database.
   
   3. **`pytz.utc` is the wrong import even hypothetically.** Python 3.9+ has `datetime.timezone.utc` built-in and `zoneinfo` is the modern stdlib path; `pytz` is being phased out. If Superset ever moves to TZ-aware datetimes, it won't be via `pytz`.
   
   4. **The PR already documents this.** The inline comment on the `soft_delete()` method cites PR #33693 and explicitly notes that `deleted_at` should follow if/when the audit columns move to UTC-aware. The bot didn't have visibility into that comment.
   
   Resolving as not-applicable.



-- 
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(core): SoftDeleteMixin and restore infrastructure [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 #39977:
URL: https://github.com/apache/superset/pull/39977#discussion_r3220682707


##########
superset/commands/restore.py:
##########
@@ -0,0 +1,82 @@
+# 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.
+"""Base class shared by all soft-delete restore commands."""
+
+from typing import Any, ClassVar, Generic, TypeVar
+
+from superset import security_manager
+from superset.commands.base import BaseCommand
+from superset.exceptions import SupersetSecurityException
+from superset.models.helpers import SoftDeleteMixin
+
+T = TypeVar("T", bound=SoftDeleteMixin)
+
+
+class BaseRestoreCommand(BaseCommand, Generic[T]):
+    """Base class for soft-delete restore commands.
+
+    Subclasses provide the entity-specific bindings as class variables:
+
+      - ``dao``: the DAO class (e.g. ``ChartDAO``)
+      - ``not_found_exc``: exception type raised when the row doesn't
+        exist OR isn't soft-deleted
+      - ``forbidden_exc``: exception type raised when the caller doesn't
+        have ownership of the row
+
+    Subclasses MUST override ``run()`` only to apply the
+    ``@transaction(on_error=partial(on_error, reraise=<RestoreFailed>))``
+    decorator with their concrete restore-failed exception type — the
+    body should be a single ``super().run()`` call. The base class does
+    not enforce this in code; Python decorators don't compose well with
+    class-var-driven configuration. The contract lives in this
+    docstring and in code review.
+
+    The model returned from ``validate()`` is the soft-deleted row,
+    type-narrowed via ``Generic[T]``. ``run()`` calls ``model.restore()``
+    on it (the method comes from ``SoftDeleteMixin``).
+    """
+
+    dao: ClassVar[Any]
+    not_found_exc: ClassVar[type[Exception]]
+    forbidden_exc: ClassVar[type[Exception]]
+
+    def __init__(self, model_uuid: str) -> None:
+        self._model_uuid = model_uuid
+
+    def run(self) -> None:
+        model = self.validate()
+        model.restore()
+
+    def validate(self) -> T:  # type: ignore[override]
+        model = self.dao.find_by_id(
+            self._model_uuid,
+            id_column="uuid",
+            skip_base_filter=True,
+            skip_visibility_filter=True,
+        )
+        if model is None:
+            raise self.not_found_exc(f"No row with uuid={self._model_uuid!r}")
+        if model.deleted_at is None:
+            raise self.not_found_exc(
+                f"Row with uuid={self._model_uuid!r} is not soft-deleted; "
+                "nothing to restore"
+            )
+        try:
+            security_manager.raise_for_ownership(model)
+        except SupersetSecurityException as ex:
+            raise self.forbidden_exc() from ex

Review Comment:
   **Suggestion:** `raise_for_ownership()` re-queries the object with a plain ORM query, which is still subject to the global soft-delete visibility filter. For soft-deleted rows this re-query returns no row, so ownership check falls back to an empty owner list and incorrectly raises forbidden for non-admin users, making restore fail even for valid owners. Use an ownership check path that does not re-query through the filtered session (or passes the visibility-skip option) for restore flows. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Future chart/dashboard/dataset restore commands reject valid owners.
   - ⚠️ Ownership checks on soft-deleted rows inconsistent for owners.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Note the global soft-delete visibility filter `_add_soft_delete_filter` in
   `superset/models/helpers.py:69-107`, which applies a `deleted_at IS NULL` criterion to all
   ORM `SELECT`s for models inheriting `SoftDeleteMixin`, unless the `SKIP_VISIBILITY_FILTER`
   execution option (or `g.skip_visibility_filter`) is set.
   
   2. Observe `BaseRestoreCommand.validate()` in `superset/commands/restore.py:64-81`: it
   loads the target model via `self.dao.find_by_id(..., skip_visibility_filter=True)` so
   soft-deleted rows can be fetched, checks `model.deleted_at is not None`, and then calls
   `security_manager.raise_for_ownership(model)` at line 79.
   
   3. Inspect `SupersetSecurityManager.raise_for_ownership()` in
   `superset/security/manager.py:6-21`: for non-admins it re-queries the resource with
   `orig_resource = self.session.query(resource.__class__).get(resource.id)` using the
   security manager session, without setting the `SKIP_VISIBILITY_FILTER` execution option.
   
   4. For any resource class that (a) inherits `SoftDeleteMixin` and (b) has an `owners`
   relationship (e.g. future chart/dashboard/dataset models once SIP-208 rollouts add the
   mixin), if a non-admin owner tries to restore a soft-deleted row: `validate()` will
   retrieve the row via `skip_visibility_filter=True`, but `raise_for_ownership()` will
   re-load it through the globally filtered session, `orig_resource` will resolve to `None`
   due to the `deleted_at IS NULL` criterion from `_add_soft_delete_filter`, `owners` will
   fall back to `[]`, and the method will raise `SupersetSecurityException`.
   `BaseRestoreCommand.validate()` catches this at `superset/commands/restore.py:78-81` and
   raises `forbidden_exc`, so legitimate non-admin owners are incorrectly forbidden from
   restoring their own soft-deleted resources.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20superset%2Fcommands%2Frestore.py%0A%2A%2ALine%3A%2A%2A%2078%3A81%0A%2A%2AComment%3A%2A%2A%0A%09%2AApi%20Mismatch%3A%20%60raise_for_ownership%28%29%60%20re-queries%20the%20object%20with%20a%20plain%20ORM%20query%2C%20which%20is%20still%20subject%20to%20the%20global%20soft-delete%20visibility%20filter.%20For%20soft-deleted%20rows%20this%20re-query%20returns%20no%20row%2C%20so%20ownership%20check%20falls%20back%20to%20an%20empty%20owner%20list%20and%20incorrectly%20raises%20forbidden%20for%20non-admin%20users%2C%20making%20restore%20fail%20even%20for%20valid%20owners.%20Use%20an%20ownership%20check%20path%20that%20does%20not%20re-query%20through%20the%20filtered%20session%20%28or%20passes%20the%20visibility-skip%20option%29%20for%20restore%20flows.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%
 20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20superset%2Fcommands%2Frestore.py%0A%2A%2ALine%3A%2A%2A%2078%3A81%0A%2A%2AComment%3A%2A%2A%0A%09%2AApi%20Mismatch%3A%20%60raise_for_ownership%28%29%60%20re-queries%20the%20object%20with%20a%20plain%20ORM%20query%2C%20which%20is%20still%20subject%20to%20the%20global%20soft-delete%20visibility%20filter.%20For%20soft-deleted%20rows%20this%20re-query%20returns%20no%20row
 %2C%20so%20ownership%20check%20falls%20back%20to%20an%20empty%20owner%20list%20and%20incorrectly%20raises%20forbidden%20for%20non-admin%20users%2C%20making%20restore%20fail%20even%20for%20valid%20owners.%20Use%20an%20ownership%20check%20path%20that%20does%20not%20re-query%20through%20the%20filtered%20session%20%28or%20passes%20the%20visibility-skip%20option%29%20for%20restore%20flows.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
   
   *(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/restore.py
   **Line:** 78:81
   **Comment:**
   	*Api Mismatch: `raise_for_ownership()` re-queries the object with a plain ORM query, which is still subject to the global soft-delete visibility filter. For soft-deleted rows this re-query returns no row, so ownership check falls back to an empty owner list and incorrectly raises forbidden for non-admin users, making restore fail even for valid owners. Use an ownership check path that does not re-query through the filtered session (or passes the visibility-skip option) for restore flows.
   
   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%2F39977&comment_hash=78f44a444c1aa813d9a4c29e40182fadae4f12902ced5491ac3a4674b80ae347&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39977&comment_hash=78f44a444c1aa813d9a4c29e40182fadae4f12902ced5491ac3a4674b80ae347&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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   **Follow-up: moved the per-request bypass into `raise_for_ownership` itself.**
   
   In `1fb3aa4851`, I refactored the soft-delete↔ownership-check coupling so the per-request bypass lives inside `security_manager.raise_for_ownership` instead of being wrapped at the caller site.
   
   **Before** (what landed in `44e1d1710b` / `c499e318fe`):
   - `BaseRestoreCommand.validate` wrapped its `raise_for_ownership(model)` call with a per-request `g.skip_visibility_filter = True` (try/finally, restore previous value).
   - The bypass was visible at every restore-command site that needed it.
   - Dedicated unit tests pinned the bypass contract.
   
   **Now**:
   - `raise_for_ownership` scopes the bypass around its own internal re-query and restores the previous value before doing the actual ownership check (which still reads `g.user`).
   - `BaseRestoreCommand.validate` is back to a plain `raise_for_ownership(model)` call.
   - The bypass becomes a tightly-scoped internal mechanism of `raise_for_ownership` rather than a caller responsibility.
   
   Diff: **+28, −160** in this branch. The 5-line addition to `security/manager.py` is a `try/finally` around the existing re-query plus a local `SKIP_VISIBILITY_FILTER` import.
   
   Why this is better than the previous approach:
   
   1. **Single point of soft-delete↔ownership coupling.** Every caller of `raise_for_ownership` — restore, delete, update, refresh, FAB `pre_delete`, etc. — now gets the correct behavior automatically. If a future caller ever needs to ownership-check a soft-deleted resource, it just works.
   2. **Preserves the defense-in-depth re-query** (form-data tampering defense from the original 2016 PR #507) — we don't lose that for non-soft-delete callers.
   3. **Eliminates the dedicated bypass-contract tests** (`tests/unit_tests/commands/test_restore.py`, ~120 lines) — there's no caller-side mechanism to test anymore.
   4. **Supersedes sc-106314** (context-manager refactor to consolidate boilerplate) — there's only one in-tree caller of the per-request flag now and it's internal.
   5. **Reframes sc-106319** (remove the re-query entirely) — that ticket was driven primarily by the soft-delete coupling; with the coupling resolved here, it drops from "correctness fix" to "optional perf optimization."
   
   Bundling caveat: this *is* a touch of `security/manager.py` inside a soft-delete PR. The change is small (12 lines net) and tightly justified — the soft-delete listener and `raise_for_ownership` are now consistent. Happy to discuss if you'd prefer this lands as its own stacked PR before sc-106188.


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @richardfogaca thanks for the careful review — all four addressed in `c499e318fe` (or in earlier `44e1d1710b` for one of them). Per-item:
   
   **`views/filters.py:164` — broad bypass scope** — agreed, fixed. `BaseDeletedStateFilter` now applies the bypass per-query via `.execution_options(skip_visibility_filter=True)` on the primary list query only, and signals the response-augmentation step via a separate request-scoped flag (`g._augment_response_with_deleted_at`). The two concerns are decoupled. Soft-deleted rows of unrelated entities no longer leak through incidental relationship loads / serializer queries.
   
   **`commands/restore.py:79` — ownership re-query filtered out** — already fixed in `44e1d1710b` (independently flagged by `codeant-ai-for-open-source` on Sunday). `BaseRestoreCommand.validate()` now sets `g.skip_visibility_filter = True` for the scope of `raise_for_ownership` only, restoring the previous value in a `finally` block. New unit tests in `tests/unit_tests/commands/test_restore.py` cover the contract (flag set during check, restored after, restored even on the exception path).
   
   **`daos/database.py:82` — flag accepted but ignored** — agreed, fixed. The override now applies `execution_options(skip_visibility_filter=True)` to its query when the flag is passed, matching `BaseDAO.find_by_id`.
   
   **`daos/base.py:299` — positional ABI** — agreed, fixed. `skip_visibility_filter` moved to the end and made keyword-only across `find_by_id`, `find_by_ids`, `find_by_id_or_uuid`, `_find_by_column`, and the `DatabaseDAO.find_by_id` override. Existing in-tree callers all already use keyword form, so no churn there.
   
   Listener docstring updated to reflect the narrower documented use case for the per-request flag: it's now reserved for cases like wrapping `raise_for_ownership` where we don't directly control the internal queries. The list-endpoint use case has moved to the per-query option.
   
   The "Praise" item also stays accurate — the `do_orm_execute` + `with_loader_criteria` pattern is unchanged, just with the documented loader-path guards added (also in `44e1d1710b`, per the matching codeant comment).


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

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/importers/v1/utils.py:
##########
@@ -400,3 +401,51 @@ def get_resource_mappings_batched(
         mapping.update({str(x.uuid): value_func(x) for x in batch})
         offset += batch_size
     return mapping
+
+
+def find_existing_for_import(model_cls: type[Any], uuid: str) -> Any | None:
+    """Look up an existing row by UUID for an import operation,
+    bypassing the soft-delete visibility filter so soft-deleted matches
+    are returned too.

Review Comment:
   Nit, by [convention](https://peps.python.org/pep-0257/) docstrings should have a 1-line short description. Because it's a convention a lot of tooling will rely on it, and in this case IDEs and other tools would show only "Look up an existing row by UUID for an import operation," as the documentation for the function.



-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @richardfogaca thanks for the careful pass. All four addressed in `5115202a3f` (infrastructure) plus mechanical entity-branch updates. Per-item:
   
   **Item 1 — `find_existing_for_import` side-effect split — fixed.**
   
   You're right that the destructive cleanup happening as a side effect of "find" is the wrong shape — today's flow is safe only because `can_write` is checked once at the import command's top level, but a future overwrite-path permission check would have a quiet bypass via the soft-delete path.
   
   `find_existing_for_import` is now a pure lookup that returns the row as-is (live OR soft-deleted) or `None`. A new `clear_soft_deleted_for_import(existing)` does the explicit hard-delete + ORM flush. Each entity's v1 importer (sc-106189/90/91) now calls them in the order you suggested: lookup → permission check on the existing row → only then `clear_soft_deleted_for_import` if the match was soft-deleted. The destructive op is at the call site, audit-able, and gated by the same ownership check as the live-overwrite path.
   
   **Item 2 — `commands/restore.py:65-69` `skip_base_filter=True` — fixed.**
   
   Agreed it had no business being there. `BaseRestoreCommand.validate` now passes only `skip_visibility_filter=True`. The entity's RBAC `base_filter` stays in effect, matching how `find_by_ids` is called on the existing delete paths. The `DashboardFilter`/`ChartFilter`/`DatasetFilter` are pure RBAC — they don't filter on `deleted_at`, so leaving them on is the correct scope. Ownership is still verified by `raise_for_ownership` immediately after, so the rejection codes line up with delete's behavior.
   
   Test renamed and tightened: `test_validate_calls_dao_with_visibility_bypass_only` asserts the DAO call no longer includes `skip_base_filter`.
   
   **Item 3 — `run()` transaction wrapping contract — fixed (refactored, not just documented).**
   
   You're right that "subclass overrides `run()` ONLY to add `@transaction`" was fragile, especially across multiple entity rollouts. The base `BaseRestoreCommand` now owns the transactional wrapper directly:
   
   ```python
   class BaseRestoreCommand(BaseCommand, Generic[T]):
       dao: ClassVar[Any]
       not_found_exc: ClassVar[type[Exception]]
       forbidden_exc: ClassVar[type[Exception]]
       restore_failed_exc: ClassVar[type[Exception]]  # new
   
       def run(self) -> None:
           @transaction(on_error=partial(on_error, reraise=self.restore_failed_exc))
           def _perform() -> None:
               model = self.validate()
               model.restore()
           _perform()
   ```
   
   The wrapper is built at call time so `on_error` can reference the per-subclass `restore_failed_exc` ClassVar. Concrete entity restore commands collapse to four ClassVar assignments with no methods — strictly declarative. Less to remember, no contract to silently skip.
   
   New test `test_run_translates_sqlalchemy_errors_via_restore_failed_exc` pins the wrapping: a `SQLAlchemyError` raised inside the unit of work is translated to the subclass's `restore_failed_exc`, so a refactor that drops the wrapper or points it at the wrong type fails CI.
   
   **Item 4 — `SoftDeleteMixin` docstring nit — fixed.**
   
   `BaseDAO.delete()` now routes through the mixin to `soft_delete()` for `SoftDeleteMixin` models; `BaseDAO.hard_delete()` is the permanent-deletion path. Docstring updated to point at `hard_delete()` for the permanent case.
   
   **Re: the `expunge_all()` praise** — thanks. `Query.get()` short-circuiting through the identity map can make tests look correct while the listener never fires; flushing the map made the empirical proof airtight. Glad it reads as such.
   
   ---
   
   Entity branches (sc-106189/90/91) all rebased onto the new infra tip and pushed. CI should re-run on all four PRs.
   
   Let me know if anything else surfaces.
   


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   _Posting on Richard's behalf — this is his PR reviewer agent. Forward any pushback to him and he'll loop me back in._
   
   One follow-up from the second pass. Most of the earlier review notes look addressed, but I think there is still one functional gap around relationship loads. Line numbers verified against HEAD `543dff20c9`.
   
   - **`superset/models/helpers.py:751`**
   
     Would it be worth re-checking the `is_relationship_load` guard with the mixin-based `with_loader_criteria` target? I tested a small SQLAlchemy 1.4.54 repro with `Parent -> Child` where both classes inherit the soft-delete mixin: direct `Child` queries were filtered, but `parent.children` lazy loads returned soft-deleted children when this guard skipped relationship loads. Removing the relationship-load guard made the lazy load filter correctly.
   
     This seems to weaken the main invariant that soft-deleted rows are hidden from relationship/serializer queries by default, and it also means the deleted-state list filter can still expose unrelated soft-deleted related rows once multiple rollout entities use the mixin.
   
     WDYT about either applying the criteria on relationship loads too, or adding a regression test that proves lazy/eager relationship loads stay filtered?
   


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/importers/v1/utils.py:
##########
@@ -400,3 +400,36 @@ def get_resource_mappings_batched(
         mapping.update({str(x.uuid): value_func(x) for x in batch})
         offset += batch_size
     return mapping
+
+
+def find_existing_for_import(model_cls: Type[Any], uuid: str) -> Optional[Any]:

Review Comment:
   The per-query opt-out (`execution_options(skip_visibility_filter=True)`) is narrowly scoped to this UUID lookup. The importer also queries referenced entities (datasets, owners, tags) while building the new row; those lookups must continue to respect the soft-delete filter, or a fresh chart could end up linked to a soft-deleted dataset.



-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/importers/v1/utils.py:
##########
@@ -424,7 +424,7 @@ def find_existing_for_import(model_cls: type[Any], uuid: str) -> Any | None:
     """
     existing = (
         db.session.query(model_cls)
-        .execution_options(**{SKIP_VISIBILITY_FILTER: True})
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {model_cls}})

Review Comment:
   I'm changing this flag that allows you to override the default omission of soft-deleted rows (and prevents the predicate from being attached to a query) so that it is per-entity.  I'm worried that a flag that turns it on for all soft-deleted entity types will be too loose when we start to add new entity types beyond these 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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/39977?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 `43.20000%` with `71 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 63.09%. Comparing base ([`0250092`](https://app.codecov.io/gh/apache/superset/commit/0250092378cf557cab3c8ae66e7be8cbb1ddb0af?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`d54e7cc`](https://app.codecov.io/gh/apache/superset/commit/d54e7cc6fa04c3d2001dba2e819a503301d07793?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 2 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/39977?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/commands/restore.py](https://app.codecov.io/gh/apache/superset/pull/39977?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==) | 0.00% | [26 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39977?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/39977?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) | 52.38% | [6 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/39977?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/views/base\_api.py](https://app.codecov.io/gh/apache/superset/pull/39977?src=pr&el=tree&filepath=superset%2Fviews%2Fbase_api.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdmlld3MvYmFzZV9hcGkucHk=) | 44.44% | [9 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/39977?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/views/filters.py](https://app.codecov.io/gh/apache/superset/pull/39977?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==) | 47.05% | [9 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39977?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/39977?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=) | 71.42% | [8 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39977?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/39977?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) | 12.50% | [7 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39977?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/39977?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/39977?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #39977      +/-   ##
   ==========================================
   - Coverage   63.88%   63.09%   -0.79%     
   ==========================================
     Files        2584     2585       +1     
     Lines      136636   136753     +117     
     Branches    31503    31518      +15     
   ==========================================
   - Hits        87287    86286    -1001     
   - Misses      47833    48938    +1105     
   - Partials     1516     1529      +13     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/39977/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/39977/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `39.38% <38.40%> (-0.01%)` | :arrow_down: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/39977/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/39977/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/39977/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.07% <38.40%> (-0.01%)` | :arrow_down: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/39977/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `58.85% <43.20%> (-1.71%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/39977/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `58.72% <43.20%> (-0.04%)` | :arrow_down: |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/39977/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/39977?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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | d54e7cc6fa04c3d2001dba2e819a503301d07793 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/69fe32555e41e200083f4bac |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-39977--superset-docs-preview.netlify.app](https://deploy-preview-39977--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.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTM5OTc3LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.1fxDjF3hsek8A26Vh0Zo12dyE6KkWbfHwFlCTvi25_8)<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#DctNCoAgEEDhu8w6QSvDukHH8GekwFTGaRHR3XP3Ft97oVK5KsMGMIAjm_3Ru3mh5KKMEa1EFgETMoozR7KN6fZ8E3YfsKby7KEfyxpxGrXWOCscpZRmirOzHr4f) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-39977--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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/models/helpers.py:
##########
@@ -654,7 +655,94 @@ def created_on_humanized(self) -> str:
 
     @renders("changed_on")
     def modified(self) -> Markup:
-        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')
+        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')  # noqa: S704
+
+
+SKIP_VISIBILITY_FILTER = "skip_visibility_filter"
+
+
+class SoftDeleteMixin:
+    """Mixin that adds soft-delete support to a SQLAlchemy model.
+
+    Adds a nullable ``deleted_at`` column. When set, the row is treated as
+    deleted and excluded from standard ORM queries via a global
+    ``do_orm_execute`` listener registered at app init.
+
+    Delete commands should call ``soft_delete()`` to mark the object as
+    deleted.  Use ``BaseDAO.delete()`` (which calls ``session.delete()``)
+    for permanent hard deletion.
+
+    See also: ``_add_soft_delete_filter`` (the listener function) and
+    ``SKIP_VISIBILITY_FILTER`` (the execution-option key used to opt out
+    of the filter in restore commands and admin tooling).
+    """
+
+    deleted_at = sa.Column(sa.DateTime, nullable=True, index=True)
+
+    @hybrid_property
+    def is_deleted(self) -> bool:
+        return self.deleted_at is not None
+
+    @is_deleted.expression  # type: ignore
+    def is_deleted(cls) -> ColumnElement:  # noqa: N805
+        return cls.deleted_at.is_not(None)
+
+    @classmethod
+    def not_deleted(cls) -> ColumnElement:
+        """Filter clause for active (non-deleted) rows."""
+        return cls.deleted_at.is_(None)
+
+    def soft_delete(self) -> None:
+        """Mark this object as soft-deleted."""
+        # Naive datetime, mirroring AuditMixinNullable.changed_on. PR #33693
+        # reverted a UTC migration on the audit columns; if/when those move
+        # to UTC-aware, this assignment should follow.
+        self.deleted_at = datetime.now()

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>datetime.now() called without timezone</b></div>
   <div id="fix">
   
   Replace `datetime.now()` with `datetime.now(tz=pytz.utc)` or `datetime.now(tz=timezone.utc)` to ensure timezone-aware datetime objects.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
       def soft_delete(self) -> None:
           """Mark this object as soft-deleted."""
           # Naive datetime, mirroring AuditMixinNullable.changed_on. PR #33693
           # reverted a UTC migration on the audit columns; if/when those move
           # to UTC-aware, this assignment should follow.
           self.deleted_at = datetime.now(tz=pytz.utc)
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #096e88</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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @aminghadersohi thanks for the post-approval flags — both are worth addressing. **F-002 fixed in `8b0495aacb`; F-001 deferred to a focused follow-up PR.**
   
   ### F-002 — session bypass cleanup. Fixed.
   
   You're right that relying on session teardown left a within-request widened-visibility window. The fix uses a variation on your option B/C: the filter records classes it added in `g._deleted_state_added_classes` (request-scoped, auto-cleans), and `SoftDeleteApiMixin.pre_get_list` removes those entries from `session.info[SKIP_VISIBILITY_FILTER_CLASSES]` in a `try/finally` immediately after augmenting the response.
   
   ```python
   # BaseDeletedStateFilter._add_session_bypass — track for release
   bypass = query.session.info.setdefault(SKIP_VISIBILITY_FILTER_CLASSES, set())
   bypass.add(self.model)
   added = getattr(g, DELETED_STATE_ADDED_CLASSES, set()) | {self.model}
   setattr(g, DELETED_STATE_ADDED_CLASSES, added)
   
   # SoftDeleteApiMixin.pre_get_list — release after augmentation
   try:
       self._inject_deleted_at(data)
   finally:
       self._release_session_bypass()
   
   @staticmethod
   def _release_session_bypass() -> None:
       added = getattr(g, DELETED_STATE_ADDED_CLASSES, set())
       if not added:
           return
       bypass = db.session.info.get(SKIP_VISIBILITY_FILTER_CLASSES, set())
       bypass -= added
       setattr(g, DELETED_STATE_ADDED_CLASSES, set())
   ```
   
   Key property: the release is scoped to entries *the filter* added. A programmatic caller using the `skip_visibility_filter` context manager or a DAO `skip_visibility_filter=True` call earlier in the same request is unaffected — those bypasses manage their own lifecycles via try/finally or DAO call scope. Pinned by `test_mixin_release_does_not_touch_unrelated_bypass_entries`.
   
   Sequence within a list response:
   
   1. `BaseDeletedStateFilter.apply` adds `self.model` to both `session.info[SKIP_VISIBILITY_FILTER_CLASSES]` and `g._deleted_state_added_classes`.
   2. FAB issues count + inner + outer + relationship loads — all see the bypass.
   3. `pre_get_list` runs *after* the list query: consumes the augmentation flag, injects `deleted_at`, then releases the filter's bypass.
   4. Any code that runs later in the same request (audit hooks, `after_request` handlers, dependent serialisation) sees the normal filtered view.
   
   Four new tests:
   
   - `test_filter_records_added_classes_on_g` — pins the tracker
   - `test_mixin_releases_bypass_after_inject` — pins the release fires after `pre_get_list` returns
   - `test_mixin_release_does_not_touch_unrelated_bypass_entries` — pins that programmatic bypasses are preserved
   - `test_mixin_release_is_noop_when_filter_was_not_invoked` — pins the no-op path for requests that didn't use `deleted_state`
   
   44 unit tests pass on the infrastructure branch (was 40).
   
   ### F-001 — TOCTOU on restore. Deferred.
   
   You're right that the `validate()` → `model.restore()` → commit window has a stale-authorization race. The fix isn't a one-liner, though, and the design choice between the two options has real trade-offs:
   
   - **`SELECT ... FOR UPDATE`** on the re-query needs either a new `for_update` kwarg on `BaseDAO.find_by_id` (widening a load-bearing DAO method) or bypassing the DAO for restore (losing the abstraction). Plus dialect-specific behaviour: SQLite silently no-ops, PostgreSQL/MySQL differ on timeouts and `nowait` / `skip_locked` policy.
   - **Atomic conditional update** — `UPDATE … WHERE uuid = ? AND deleted_at IS NOT NULL` — closes the window precisely but **bypasses ORM `before_update` / `after_update` event listeners**, including `AuditMixinNullable`'s `changed_on` / `changed_by_fk` stamping. Losing audit attribution on restore is a real cost; we'd have to re-add stamping manually.
   
   Proper test coverage means an actual concurrent-session test rig (two sessions, observe lock contention or rowcount=0), not just a unit-level mock — a different kind of work than what's been in this PR.
   
   So F-001 lands separately, where the locking-vs-atomic-update design can get focused review and the concurrency tests can be built deliberately. Tracked in the spec at `sc-103157-soft-deletes/spec.md` under "Follow-up Items from Review."
   
   ---
   
   Infrastructure tip is now `8b0495aacb`. Entity branches rebased: `sc-106189` → `9c6d1584a2`, `sc-106190` → `5e26ebc084`, `sc-106191` → `ac38056b41`. CI re-running across all four.
   


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @mistercrunch @michael-s-molina @betodealmeida @eschutho @sadpandajoe @kgabryje: I lack the ability to add you as reviewers, so I'm tagging you instead. 


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @richardfogaca thanks for the second pass — addressed in `543dff20c9` for items 1 and 4; replying inline for items 2 and 3.
   
   **Item 1 (importers cleanup) — fixed.** You're right that the raw Core `DELETE` was trading correctness for perf. `find_existing_for_import` now uses `db.session.delete()` so `ObjectUpdater.after_delete` and `SqlaTable.after_delete` fire and clean up `tagged_object` rows + dataset permission rows. The original rationale was avoiding cascade-load on large relationship graphs, but an import operation isn't a steady-state hot path; the trade tilts toward correctness. Updated the function docstring and the bypass-primer doc to reflect the change.
   
   **Item 4 (hardcoded id PK) — fixed.** `_get_deleted_at_map` now resolves the PK via `self.datamodel.get_pk_name()` and the signature is `list[Any]` to match the broader PK contract. Same behaviour for the chart/dashboard/dataset rollout (all int PKs); future soft-deletable entities with a different PK will work without changes here.
   
   **Item 2 (per-query bypass scope) — accepted YAGNI, comment added in follow-up.** You're the third reviewer to raise this from a slightly different angle (codeant flagged the listener guards, I raised it during initial design, you raised it for the request-scoped flag, and now for the per-query option). The mechanism in all cases is the same: `with_loader_criteria(SoftDeleteMixin, ...)` applies polymorphically to every subclass, so any bypass affects all subclasses in the same query.
   
   In the current code path, the bypass is set by `BaseDeletedStateFilter` on the primary list query, which targets one concrete entity. The list queries for chart/dashboard/dataset don't currently join across other soft-deletable entities in the same statement, so the over-broad bypass is theoretical rather than actual.
   
   Per-entity scoping is a real future-proofing option (e.g., `execution_options(skip_visibility_filter_for=[Slice])`) but it materially expands the listener and the bypass API surface. I'd prefer to defer it until a use case actually surfaces. Happy to add a code comment in `BaseDeletedStateFilter.apply` flagging the contract:
   
   ```python
   # The execution-option bypass is per-statement but not per-class — it
   # skips the soft-delete listener for every SoftDeleteMixin subclass in
   # the statement, not just self.model. Today the list endpoints don't
   # join across soft-deletable entities, so this is moot in practice.
   # If a future list query starts joining (e.g., a dashboard list that
   # eagerly loads charts in the same statement), revisit per-entity
   # scoping rather than continuing to use the broad bypass here.
   ```
   
   WDYT — comment in code as a forward-looking warning, or do you think the per-entity scoping is worth doing now?
   
   **Item 3 (visibility auth gap) — SIP-208 question rather than code review.** Legitimate concern. The proposal in SIP-208 maps restore to `write` but leaves visibility on the existing list-read permission. Whether seeing soft-deleted rows should require something stronger is a policy choice the SIP didn't address — I think it belongs back on the SIP-208 issue thread or dev@ rather than getting decided in this PR. If you'd like to take the discussion there, happy to be the lightning rod for the dev@ post.
   
   Praise on the try/finally — noted, thank you. That ordering took a couple of iterations to land on.


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/daos/base.py:
##########
@@ -181,11 +182,15 @@ def find_by_id_or_uuid(
         cls,
         model_id_or_uuid: str,
         skip_base_filter: bool = False,
+        *,
+        skip_visibility_filter: bool = False,

Review Comment:
   In this and other places, this is a flag argument.  I would leave it in for this PR because this is the existing pattern, but we might want to change it later in tandem with `skip_base_filter`.  E.g. it could be `find_by_id_or_uuid` and `find_by_id_or_uuid_with_soft_deletes`, maybe.



-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/models/helpers.py:
##########
@@ -654,7 +656,94 @@ def created_on_humanized(self) -> str:
 
     @renders("changed_on")
     def modified(self) -> Markup:
-        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')
+        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')  # noqa: S704
+
+
+SKIP_VISIBILITY_FILTER = "skip_visibility_filter"
+
+
+class SoftDeleteMixin:
+    """Mixin that adds soft-delete support to a SQLAlchemy model.
+
+    Adds a nullable ``deleted_at`` column. When set, the row is treated as
+    deleted and excluded from standard ORM queries via a global
+    ``do_orm_execute`` listener registered at app init.
+
+    Delete commands should call ``soft_delete()`` to mark the object as
+    deleted.  Use ``BaseDAO.delete()`` (which calls ``session.delete()``)
+    for permanent hard deletion.
+
+    See also: ``_add_soft_delete_filter`` (the listener function) and
+    ``SKIP_VISIBILITY_FILTER`` (the execution-option key used to opt out
+    of the filter in restore commands and admin tooling).
+    """
+
+    deleted_at = sa.Column(sa.DateTime, nullable=True, index=True)
+
+    @hybrid_property
+    def is_deleted(self) -> bool:
+        return self.deleted_at is not None
+
+    @is_deleted.expression  # type: ignore
+    def is_deleted(cls) -> ColumnElement:  # noqa: N805
+        return cls.deleted_at.is_not(None)
+
+    @classmethod
+    def not_deleted(cls) -> ColumnElement:
+        """Filter clause for active (non-deleted) rows."""
+        return cls.deleted_at.is_(None)
+
+    def soft_delete(self) -> None:
+        """Mark this object as soft-deleted."""
+        # Naive datetime, mirroring AuditMixinNullable.changed_on. PR #33693
+        # reverted a UTC migration on the audit columns; if/when those move
+        # to UTC-aware, this assignment should follow.
+        self.deleted_at = datetime.now()
+
+    def restore(self) -> None:
+        """Clear the soft-delete marker, making this object active again."""
+        self.deleted_at = None
+
+
+def _add_soft_delete_filter(execute_state: ORMExecuteState) -> None:
+    """Global ``do_orm_execute`` listener that automatically excludes
+    soft-deleted rows from every ORM SELECT.
+
+    Uses SQLAlchemy's recommended soft-delete pattern
+    (``do_orm_execute`` + ``with_loader_criteria``).
+
+    Two opt-out paths:
+
+    * **Per-query** — ``execution_options(skip_visibility_filter=True)``.
+      The narrow tool. Use this from any non-user-facing code path
+      (background jobs, import pipelines, internal admin tools) that
+      needs to query soft-deleted rows.
+    * **Per-request** — ``flask.g.skip_visibility_filter = True``.
+      The broad tool. Reserved for user-facing list endpoints whose
+      rison filter (``*_deleted_state=include|only``) explicitly asks
+      to surface soft-deleted rows for the rest of that request.
+      Anything else needing to bypass the filter should use the
+      per-query option, since the request-scoped flag also affects
+      any incidental query inside the same request.
+    """
+    skip_visibility_filter = execute_state.execution_options.get(
+        SKIP_VISIBILITY_FILTER, False
+    )
+    try:
+        skip_visibility_filter = skip_visibility_filter or getattr(
+            g, SKIP_VISIBILITY_FILTER, False
+        )
+    except RuntimeError:
+        pass
+
+    if execute_state.is_select and not skip_visibility_filter:
+        execute_state.statement = execute_state.statement.options(
+            with_loader_criteria(
+                SoftDeleteMixin,
+                lambda cls: cls.deleted_at.is_(None),
+                include_aliases=True,
+            )
+        )

Review Comment:
   Confirmed and fixed in 44e1d1710b. The two loader guards are now in place:
   
   ```python
   if (
       execute_state.is_select
       and not execute_state.is_column_load
       and not execute_state.is_relationship_load
       and not skip_visibility_filter
   ):
       execute_state.statement = execute_state.statement.options(...)
   ```
   
   This matches Mike Bayer's documented pattern in sqlalchemy/sqlalchemy#7973 — the same reference the PR description cites, so we should have had it from the start. Thanks for catching this; without these guards, lazy/eager relationship loads accumulate redundant `deleted_at IS NULL` clauses on every reload, which is both a perf regression and a correctness risk if SQLAlchemy stacks the same criteria across loader paths.



-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @aminghadersohi thanks for the careful pass. Most items addressed in `06a64f02c1`; two deferred with reasoning below.
   
   ### HIGH
   
   **H1 — uncached subclass walk → cached registry via `__init_subclass__`. Fixed.**
   
   You're right that retrofitting under live traffic is harder than getting it right now. `SoftDeleteMixin` now maintains a sorted `_registered_subclasses: ClassVar[list[type[SoftDeleteMixin]]]` updated by `__init_subclass__` at class-definition time; `_all_soft_delete_subclasses()` is now a `return SoftDeleteMixin._registered_subclasses` — no walk, no `sorted()` allocation per call. Sort happens once per registration (rare event at app init), not per query.
   
   I chose the `__init_subclass__` registry over `functools.lru_cache` because the cache would freeze at first call — tests that define synthetic subclasses (we have ~6 of them) would never be picked up by the listener, breaking the test suite. The registry hook handles class-definition events naturally and works for both production and test contexts.
   
   **H2 — non-restorable / GDPR hook. Deferred.**
   
   The concern is valid but I'd push back on landing the interface now. Two reasons:
   
   1. **No concrete use case yet**: SIP-208 V1 doesn't include compliance flows. Designing a `deletion_policy` or `locked_at` interface without a real GDPR/audit/admin-purge workflow risks getting the API wrong — and once entity migrations land, the migration to a richer interface becomes the expensive change you're trying to avoid.
   2. **The natural retrofit isn't catastrophic**: if compliance becomes V2 scope, the cheap path is a separate `LockedDeletion` table (UUID-keyed, points at the soft-deleted row) checked in `BaseRestoreCommand.validate()`. That's a one-migration add — no column on the mixin, no change to the existing entity migrations. The expense Amin is anticipating ("five entity rollouts already landed") doesn't actually accrue, because the lock lives outside the entity table.
   
   If GDPR work gets scheduled, I'll do the design then with the actual constraints in hand. Tracking as a follow-up rather than a speculative interface here.
   
   ### MEDIUM
   
   **M3 — `SoftDeleteMixin` inline import in `BaseDAO.delete`. Fixed.** Moved to top-level (no cycle); `SKIP_VISIBILITY_FILTER_CLASSES` from the same module was already top-level so adding `SoftDeleteMixin` to the existing import line was the right cleanup.
   
   **M4 — `raise_for_ownership` pylint-disable. Documented (kept inline).** Tried moving to top-level — it does cause a real circular: `security.manager` → `models.helpers` → `models.core` → lazy `superset.feature_flag_manager`. Kept the inline import but added a comment naming the specific cycle so a future maintainer doesn't try to "fix" it and re-trip the issue:
   
   ```python
   # Inline import: ``superset.models.helpers`` transitively imports
   # ``superset.models.core``, which depends on lazily-initialised
   # ``superset.feature_flag_manager``. A top-level import here would
   # create a circular dependency (security ↔ models.core ↔ superset).
   ```
   
   **M5 — `BaseDeletedStateFilter.model: Any` → typed. Fixed.**
   
   ```python
   # Subclasses bind ``model`` to a concrete ``SoftDeleteMixin``
   # subclass. Typed as ``type[SoftDeleteMixin]`` so a subclass that
   # accidentally binds to a non-soft-deletable entity fails mypy
   # rather than crashing at runtime on ``.deleted_at``.
   model: ClassVar[type[SoftDeleteMixin]]
   ```
   
   **M6 — listener placement. Documented.** Investigated and confirmed the placement is intentional — the `do_orm_execute` hook attaches to the `Session` *class* (process-wide), not a Session instance, so it has no Flask-app-context dependency. `setup_db()` runs earlier in `init_app` so the `Session` import is already initialised. Added a six-line comment in `init_app` explaining the placement so the rationale doesn't have to be re-derived from review history.
   
   **M7 — no tests for `BaseDeletedStateFilter` / `SoftDeleteApiMixin`. Fixed.** New `tests/unit_tests/views/test_soft_delete_filter.py` with 10 tests:
   
   - Filter: value-absent / include / only / case-insensitivity / unknown-value — including assertions that the session bypass set and the `g` augmentation flag are both correctly populated.
   - Mixin: no-op-without-flag / inject-with-flag / **consume-flag-on-call** (the read-and-clear semantics you specifically called out as subtle enough to warrant a dedicated test) / `_serialize_deleted_at` handling of `None` and `datetime`.
   
   **M8 — `deleted_at` schema mutation undocumented. Acknowledged.** This is intentional — `deleted_state=include` augments rows with `deleted_at`, and that's the point of the filter. I'll add a "ADDITIONAL INFORMATION" callout to each entity rollout PR body (#40128 / #40129 / #40130) noting the response schema additions, and call out the OpenAPI response-schema update as a per-entity-PR responsibility so it's explicit on the checklist. Not changing the infrastructure PR for this — the augmentation logic itself is correct.
   
   ### Nits
   
   - **Explicit `orig_resource is None` guard in `raise_for_ownership`. Fixed.** The fallthrough was correct in effect (`hasattr(None, "owners") → False → owners=[] → MISSING_OWNERSHIP_ERROR`) but the error reads "you don't own this" when the actual cause is "this row was hard-deleted between the caller's load and the re-query." Now raises the precise cause:
   
     ```python
     if orig_resource is None:
         raise SupersetSecurityException(...
             message=_("Resource was removed before ownership could be verified"),
         ...)
     ```
   
   - **Unit tests for `find_existing_for_import` / `clear_soft_deleted_for_import`. Fixed.** New `tests/unit_tests/commands/importers/v1/test_find_existing_for_import.py` (5 tests) — pure-lookup behaviour for live + soft-deleted + missing rows, `clear` hard-deletes via the ORM (fires `after_delete` listeners), and the composed find-then-clear contract that's the documented caller sequence.
   
   - **Feature-flag kill switch (`ENABLE_SOFT_DELETE`)**: deliberately not adding. SIP-208 explicitly discusses this: a global flag risks confusing partial states (some entities filtered, others not, depending on which adopters have the mixin at the time the flag flips). The rollback path is "revert the entity rollout PR" rather than a runtime kill — the infrastructure is a no-op without an adopter, so a problem in production means a specific entity rollout PR misbehaves, and reverting that single PR is the right escape hatch.
   
   - **`Query.get()` → `session.get(Model, pk)` (SQLAlchemy 2.0 idiom)**: skipping. The pattern is pre-existing in `raise_for_ownership` and unrelated to soft-delete; doing it here would mix scopes. Worth a separate cleanup PR for the codebase once the SQLAlchemy 1.4 → 2.x migration is on the roadmap (the `Mapped[]` adoption thread already touches this area).
   
   - **`register_soft_delete_listener()` public function**: skipping. The inline `from superset.models.helpers import _add_soft_delete_filter` in `setup_soft_delete_listener` is one line in one place; the indirection doesn't pay for itself.
   
   ### Architecture notes
   
   - **Cascade decision per entity**: agreed, documenting as a per-entity checklist item. Updating the three entity rollout PR bodies (#40128 / #40129 / #40130) to call out the cascade-neutral choice for each (charts: dashboards keep their reference, render a placeholder; dashboards: child slices stay live; datasets: dependent charts render an error at chart-load).
   
   - **`owners` M2M constraint**: noted. Logging as a documented constraint on future soft-deletable additions — if `User` or `Role` were ever to become soft-deletable, `raise_for_ownership`'s `.owners` lookup would silently return empty for legitimate restores. Not a current risk (neither model is on the SIP-208 roadmap), but worth pinning in the mixin docstring as a future-proofing note. Will add in a follow-up tidy.
   
   ### Re: the praise
   
   Thanks. The dual-bypass mechanism in particular went through ~5 design iterations — per-request `g` flag → moved into `raise_for_ownership` → per-query `execution_options` → discovered FAB's outer/inner reconstruction strips them → session-scoped `session.info` → per-class scoping. The "design doc woven into the code" effect is partly because each iteration's reasoning *had* to land in docstrings to keep the next reviewer (and future-me) from re-deriving the same trade-offs.
   
   ---
   
   Infrastructure tip: `06a64f02c1`. Entity branches rebased: `sc-106189` → `a3ac63be0b`, `sc-106190` → `8bff0145b5`, `sc-106191` → `0a56e67842`. CI re-running across all four PRs.
   
   40 unit tests pass (was 26; added 14 covering filter, mixin, importer helpers). Let me know if anything else surfaces.
   


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/importers/v1/utils.py:
##########
@@ -400,3 +401,51 @@ def get_resource_mappings_batched(
         mapping.update({str(x.uuid): value_func(x) for x in batch})
         offset += batch_size
     return mapping
+
+
+def find_existing_for_import(model_cls: type[Any], uuid: str) -> Any | None:
+    """Look up an existing row by UUID for an import operation,
+    bypassing the soft-delete visibility filter so soft-deleted matches
+    are returned too.
+
+    Side-effect-free: returns the row as-is whether it's live or
+    soft-deleted (or ``None`` if no row exists). The caller is
+    responsible for deciding what to do with a soft-deleted match —
+    typically calling :func:`clear_soft_deleted_for_import` to remove
+    it before re-import, but only after the caller has validated
+    overwrite/permission decisions.
+
+    Splitting the lookup from the destructive cleanup keeps the
+    destructive action explicit at the call site, so a future change
+    that adds a permission check on the overwrite path doesn't
+    silently leave a "duck around it via soft-delete" backdoor.
+    """
+    return (
+        db.session.query(model_cls)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {model_cls}})
+        .filter_by(uuid=uuid)
+        .first()
+    )
+
+
+def clear_soft_deleted_for_import(existing: Any) -> None:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing transaction decorator</b></div>
   <div id="fix">
   
   The `clear_soft_deleted_for_import` function performs `db.session.delete()` but lacks the `@transaction()` decorator that `import_tag` (line 265) uses for database operations. Without this decorator, callers who invoke this function outside an existing transaction context risk uncommitted or unrolled-back deletes.
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/commands/importers/v1/utils.py (lines 431-451) ---
    431:+@transaction()
    431: def clear_soft_deleted_for_import(existing: Any) -> None:
    432:     """Hard-delete a soft-deleted row so a subsequent import of the
    433:     same UUID does not collide with the unique constraint.
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #3f7778</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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/importers/v1/utils.py:
##########
@@ -400,3 +400,36 @@ def get_resource_mappings_batched(
         mapping.update({str(x.uuid): value_func(x) for x in batch})
         offset += batch_size
     return mapping
+
+
+def find_existing_for_import(model_cls: Type[Any], uuid: str) -> Optional[Any]:

Review Comment:
   We use the per-query opt-out (`execution_options(skip_visibility_filter=True)`) rather than the per-request flag (`flask.g.skip_visibility_filter`) so the bypass affects only this UUID lookup. The importer also queries referenced entities (datasets, owners, tags) while building the new row — those lookups must continue to respect the visibility filter, or a fresh chart could end up linked to a soft-deleted dataset. The per-query option is also the only one available outside a Flask request context (CLI / Celery imports), where `flask.g` doesn't exist. 



-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/importers/v1/utils.py:
##########
@@ -400,3 +401,51 @@ def get_resource_mappings_batched(
         mapping.update({str(x.uuid): value_func(x) for x in batch})
         offset += batch_size
     return mapping
+
+
+def find_existing_for_import(model_cls: type[Any], uuid: str) -> Any | None:
+    """Look up an existing row by UUID for an import operation,
+    bypassing the soft-delete visibility filter so soft-deleted matches
+    are returned too.
+
+    Side-effect-free: returns the row as-is whether it's live or
+    soft-deleted (or ``None`` if no row exists). The caller is
+    responsible for deciding what to do with a soft-deleted match —
+    typically calling :func:`clear_soft_deleted_for_import` to remove
+    it before re-import, but only after the caller has validated
+    overwrite/permission decisions.
+
+    Splitting the lookup from the destructive cleanup keeps the
+    destructive action explicit at the call site, so a future change
+    that adds a permission check on the overwrite path doesn't
+    silently leave a "duck around it via soft-delete" backdoor.
+    """
+    return (
+        db.session.query(model_cls)
+        .execution_options(**{SKIP_VISIBILITY_FILTER_CLASSES: {model_cls}})
+        .filter_by(uuid=uuid)
+        .first()
+    )
+
+
+def clear_soft_deleted_for_import(existing: Any) -> None:

Review Comment:
   False positive. `clear_soft_deleted_for_import` is always called from inside the v1 importer's outer `@transaction()` wrapper (`ImportModelsCommand.run` → `import_dashboard`/`import_chart`/`import_dataset` → `clear_soft_deleted_for_import`). The transaction decorator detects nesting via `getattr(g, "in_transaction", False)` and short-circuits to direct invocation when already inside one — so adding the decorator here would be redundant. The destructive op is committed (or rolled back) as part of the outer import unit-of-work, which is the right scope.



-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/commands/restore.py:
##########
@@ -0,0 +1,82 @@
+# 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.
+"""Base class shared by all soft-delete restore commands."""
+
+from typing import Any, ClassVar, Generic, TypeVar
+
+from superset import security_manager
+from superset.commands.base import BaseCommand
+from superset.exceptions import SupersetSecurityException
+from superset.models.helpers import SoftDeleteMixin
+
+T = TypeVar("T", bound=SoftDeleteMixin)
+
+
+class BaseRestoreCommand(BaseCommand, Generic[T]):
+    """Base class for soft-delete restore commands.
+
+    Subclasses provide the entity-specific bindings as class variables:
+
+      - ``dao``: the DAO class (e.g. ``ChartDAO``)
+      - ``not_found_exc``: exception type raised when the row doesn't
+        exist OR isn't soft-deleted
+      - ``forbidden_exc``: exception type raised when the caller doesn't
+        have ownership of the row
+
+    Subclasses MUST override ``run()`` only to apply the
+    ``@transaction(on_error=partial(on_error, reraise=<RestoreFailed>))``
+    decorator with their concrete restore-failed exception type — the
+    body should be a single ``super().run()`` call. The base class does
+    not enforce this in code; Python decorators don't compose well with
+    class-var-driven configuration. The contract lives in this
+    docstring and in code review.
+
+    The model returned from ``validate()`` is the soft-deleted row,
+    type-narrowed via ``Generic[T]``. ``run()`` calls ``model.restore()``
+    on it (the method comes from ``SoftDeleteMixin``).
+    """
+
+    dao: ClassVar[Any]
+    not_found_exc: ClassVar[type[Exception]]
+    forbidden_exc: ClassVar[type[Exception]]
+
+    def __init__(self, model_uuid: str) -> None:
+        self._model_uuid = model_uuid
+
+    def run(self) -> None:
+        model = self.validate()
+        model.restore()
+
+    def validate(self) -> T:  # type: ignore[override]
+        model = self.dao.find_by_id(
+            self._model_uuid,
+            id_column="uuid",
+            skip_base_filter=True,
+            skip_visibility_filter=True,
+        )
+        if model is None:
+            raise self.not_found_exc(f"No row with uuid={self._model_uuid!r}")
+        if model.deleted_at is None:
+            raise self.not_found_exc(
+                f"Row with uuid={self._model_uuid!r} is not soft-deleted; "
+                "nothing to restore"
+            )
+        try:
+            security_manager.raise_for_ownership(model)
+        except SupersetSecurityException as ex:
+            raise self.forbidden_exc() from ex

Review Comment:
   Confirmed and fixed in 44e1d1710b. Thanks for catching this — the existing unit tests mocked `raise_for_ownership` directly so they never exercised the real re-query path, which is exactly why the bug slipped through.
   
   The fix sets `g.skip_visibility_filter = True` for the scope of the `raise_for_ownership` call only, restoring the previous value afterward (so it composes correctly with any caller that already had the per-request flag set). New tests in `tests/unit_tests/commands/test_restore.py` exercise the contract — flag set during the check, flag restored after, flag restored even on the exception 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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   <!-- Bito Reply -->
   The explanation accurately describes the code in superset/commands/importers/v1/utils.py, where the per-query execution_options(**{SKIP_VISIBILITY_FILTER: True}) bypasses the visibility filter only for the UUID lookup in find_existing_for_import, allowing access to soft-deleted rows while keeping other entity queries filtered.


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   @aminghadersohi A couple points to add:
   
   - for H2, I don't see current patterns for GDPR in the codebase; I think it's a good idea to address but I think it should be part of a broader concern
   - As for the `ENABLE_SOFT_DELETE` flag/kill-switch, it was in my original design but the general in-person consensus was that we would try to avoid having two code paths


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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(core): SoftDeleteMixin and restore infrastructure [superset]

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


-- 
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(core): SoftDeleteMixin and restore infrastructure [superset]

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


##########
superset/models/helpers.py:
##########
@@ -654,7 +655,94 @@ def created_on_humanized(self) -> str:
 
     @renders("changed_on")
     def modified(self) -> Markup:
-        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')
+        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')  # noqa: S704
+
+
+SKIP_VISIBILITY_FILTER = "skip_visibility_filter"
+
+
+class SoftDeleteMixin:
+    """Mixin that adds soft-delete support to a SQLAlchemy model.
+
+    Adds a nullable ``deleted_at`` column. When set, the row is treated as
+    deleted and excluded from standard ORM queries via a global
+    ``do_orm_execute`` listener registered at app init.
+
+    Delete commands should call ``soft_delete()`` to mark the object as
+    deleted.  Use ``BaseDAO.delete()`` (which calls ``session.delete()``)
+    for permanent hard deletion.
+
+    See also: ``_add_soft_delete_filter`` (the listener function) and
+    ``SKIP_VISIBILITY_FILTER`` (the execution-option key used to opt out
+    of the filter in restore commands and admin tooling).
+    """
+
+    deleted_at = sa.Column(sa.DateTime, nullable=True, index=True)
+
+    @hybrid_property
+    def is_deleted(self) -> bool:
+        return self.deleted_at is not None
+
+    @is_deleted.expression  # type: ignore
+    def is_deleted(cls) -> ColumnElement:  # noqa: N805
+        return cls.deleted_at.is_not(None)
+
+    @classmethod
+    def not_deleted(cls) -> ColumnElement:
+        """Filter clause for active (non-deleted) rows."""
+        return cls.deleted_at.is_(None)
+
+    def soft_delete(self) -> None:
+        """Mark this object as soft-deleted."""
+        # Naive datetime, mirroring AuditMixinNullable.changed_on. PR #33693
+        # reverted a UTC migration on the audit columns; if/when those move
+        # to UTC-aware, this assignment should follow.
+        self.deleted_at = datetime.now()

Review Comment:
   Thanks for flagging — declining this one.
   
   Four reasons the naive `datetime.now()` is deliberate here:
   
   1. **Project precedent.** `AuditMixinNullable.changed_on` and `.created_on` use naive `datetime.now()`. [PR #33693](https://github.com/apache/superset/pull/33693) explicitly reverted a UTC migration on those audit columns. `deleted_at` is semantically an audit column and should match the convention; diverging would produce a model with mixed-TZ columns.
   
   2. **Schema mismatch.** The `deleted_at` column ships as `DateTime`, not `DateTime(timezone=True)`. Storing a TZ-aware Python value into a TZ-naive Postgres/MySQL column silently strips the timezone on insert, so the suggestion would not actually achieve TZ-awareness end-to-end — it would just introduce a representation gap between Python and the database.
   
   3. **`pytz.utc` is the wrong import even hypothetically.** Python 3.9+ has `datetime.timezone.utc` built-in and `zoneinfo` is the modern stdlib path; `pytz` is being phased out. If Superset ever moves to TZ-aware datetimes, it won't be via `pytz`.
   
   4. **The PR already documents this.** The inline comment on the `soft_delete()` method cites PR #33693 and explicitly notes that `deleted_at` should follow if/when the audit columns move to UTC-aware. The bot didn't have visibility into that comment.
   
   Resolving as not-applicable.



-- 
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(core): SoftDeleteMixin and restore infrastructure [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 #39977:
URL: https://github.com/apache/superset/pull/39977#discussion_r3220689675


##########
superset/models/helpers.py:
##########
@@ -654,7 +656,94 @@ def created_on_humanized(self) -> str:
 
     @renders("changed_on")
     def modified(self) -> Markup:
-        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')
+        return Markup(f'<span class="no-wrap">{self.changed_on_humanized}</span>')  # noqa: S704
+
+
+SKIP_VISIBILITY_FILTER = "skip_visibility_filter"
+
+
+class SoftDeleteMixin:
+    """Mixin that adds soft-delete support to a SQLAlchemy model.
+
+    Adds a nullable ``deleted_at`` column. When set, the row is treated as
+    deleted and excluded from standard ORM queries via a global
+    ``do_orm_execute`` listener registered at app init.
+
+    Delete commands should call ``soft_delete()`` to mark the object as
+    deleted.  Use ``BaseDAO.delete()`` (which calls ``session.delete()``)
+    for permanent hard deletion.
+
+    See also: ``_add_soft_delete_filter`` (the listener function) and
+    ``SKIP_VISIBILITY_FILTER`` (the execution-option key used to opt out
+    of the filter in restore commands and admin tooling).
+    """
+
+    deleted_at = sa.Column(sa.DateTime, nullable=True, index=True)
+
+    @hybrid_property
+    def is_deleted(self) -> bool:
+        return self.deleted_at is not None
+
+    @is_deleted.expression  # type: ignore
+    def is_deleted(cls) -> ColumnElement:  # noqa: N805
+        return cls.deleted_at.is_not(None)
+
+    @classmethod
+    def not_deleted(cls) -> ColumnElement:
+        """Filter clause for active (non-deleted) rows."""
+        return cls.deleted_at.is_(None)
+
+    def soft_delete(self) -> None:
+        """Mark this object as soft-deleted."""
+        # Naive datetime, mirroring AuditMixinNullable.changed_on. PR #33693
+        # reverted a UTC migration on the audit columns; if/when those move
+        # to UTC-aware, this assignment should follow.
+        self.deleted_at = datetime.now()
+
+    def restore(self) -> None:
+        """Clear the soft-delete marker, making this object active again."""
+        self.deleted_at = None
+
+
+def _add_soft_delete_filter(execute_state: ORMExecuteState) -> None:
+    """Global ``do_orm_execute`` listener that automatically excludes
+    soft-deleted rows from every ORM SELECT.
+
+    Uses SQLAlchemy's recommended soft-delete pattern
+    (``do_orm_execute`` + ``with_loader_criteria``).
+
+    Two opt-out paths:
+
+    * **Per-query** — ``execution_options(skip_visibility_filter=True)``.
+      The narrow tool. Use this from any non-user-facing code path
+      (background jobs, import pipelines, internal admin tools) that
+      needs to query soft-deleted rows.
+    * **Per-request** — ``flask.g.skip_visibility_filter = True``.
+      The broad tool. Reserved for user-facing list endpoints whose
+      rison filter (``*_deleted_state=include|only``) explicitly asks
+      to surface soft-deleted rows for the rest of that request.
+      Anything else needing to bypass the filter should use the
+      per-query option, since the request-scoped flag also affects
+      any incidental query inside the same request.
+    """
+    skip_visibility_filter = execute_state.execution_options.get(
+        SKIP_VISIBILITY_FILTER, False
+    )
+    try:
+        skip_visibility_filter = skip_visibility_filter or getattr(
+            g, SKIP_VISIBILITY_FILTER, False
+        )
+    except RuntimeError:
+        pass
+
+    if execute_state.is_select and not skip_visibility_filter:
+        execute_state.statement = execute_state.statement.options(
+            with_loader_criteria(
+                SoftDeleteMixin,
+                lambda cls: cls.deleted_at.is_(None),
+                include_aliases=True,
+            )
+        )

Review Comment:
   **Suggestion:** The global `do_orm_execute` hook applies `with_loader_criteria` to every SELECT, including relationship and column loader queries; SQLAlchemy's recommended pattern excludes those loader paths to avoid repeatedly stacking the same predicate. Without those guards, lazy/eager relationship loads can accumulate redundant `deleted_at IS NULL` clauses and increase query complexity/latency. Gate this block with `not execute_state.is_column_load` and `not execute_state.is_relationship_load`. [performance]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Soft-deletable model queries gain redundant soft-delete predicates.
   - ⚠️ Relationship loads perform extra filtering work per lazy load.
   - ⚠️ High-traffic chart and dashboard APIs may slow slightly.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. At app initialization, `SupersetAppInitializer.setup_soft_delete_listener()` (added in
   this PR at `superset/initialization/__init__.py:770-771`) registers
   `_add_soft_delete_filter` from `superset/models/helpers.py:708-746` as a `do_orm_execute`
   listener on SQLAlchemy `Session`, so it runs on every ORM statement.
   
   2. `_add_soft_delete_filter()` computes `skip_visibility_filter` from
   `execute_state.execution_options` and `flask.g` at `superset/models/helpers.py:729-735`,
   then unconditionally applies `with_loader_criteria(SoftDeleteMixin, ...)` for any
   `execute_state.is_select` where `skip_visibility_filter` is false at lines 739-746.
   
   3. SQLAlchemy's documented best-practice pattern for this hook (referenced in the
   docstring at `superset/models/helpers.py:712-713`) includes additional guards `not
   execute_state.is_column_load` and `not execute_state.is_relationship_load` to avoid
   reapplying identical `with_loader_criteria` options on per-column and per-relationship
   loader SELECTs; those guards are currently missing in this implementation.
   
   4. Once real Superset entities (e.g. charts, dashboards, datasets) adopt `SoftDeleteMixin`
   in their respective rollout PRs as described in the SIP-208 summary, any ORM operation
   that performs lazy or eager relationship loading for those models (for example, API
   handlers like `ChartRestApi` and `DashboardRestApi` registered in `init_views()` at
   `superset/initialization/__init__.py:154-269`) will trigger `do_orm_execute` both for the
   primary SELECT and for each relationship/column load; `_add_soft_delete_filter()` will
   reapply `with_loader_criteria` on each of those loader queries, stacking redundant
   `deleted_at IS NULL` criteria and increasing query complexity and latency compared to the
   recommended guarded pattern.
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20superset%2Fmodels%2Fhelpers.py%0A%2A%2ALine%3A%2A%2A%20739%3A746%0A%2A%2AComment%3A%2A%2A%0A%09%2APerformance%3A%20The%20global%20%60do_orm_execute%60%20hook%20applies%20%60with_loader_criteria%60%20to%20every%20SELECT%2C%20including%20relationship%20and%20column%20loader%20queries%3B%20SQLAlchemy%27s%20recommended%20pattern%20excludes%20those%20loader%20paths%20to%20avoid%20repeatedly%20stacking%20the%20same%20predicate.%20Without%20those%20guards%2C%20lazy%2Feager%20relationship%20loads%20can%20accumulate%20redundant%20%60deleted_at%20IS%20NULL%60%20clauses%20and%20increase%20query%20complexity%2Flatency.%20Gate%20this%20block%20with%20%60not%20execute_state.is_column_load%60%20and%20%60not%20execute_state.is_relationship_load%60.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%2
 0I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20superset%2Fmodels%2Fhelpers.py%0A%2A%2ALine%3A%2A%2A%20739%3A746%0A%2A%2AComment%3A%2A%2A%0A%09%2APerformance%3A%20The%20global%20%60do_orm_execute%60%20hook%20applies%20%60with_loader_criteria%60%20to%20every%20SELECT%2C%20including%20relationship%20and%20column%20loader%20queries%3B%20SQLAlchemy%27s%20recommended%20pattern%20excludes%20those%20loader%20paths%20to%20avoid%20rep
 eatedly%20stacking%20the%20same%20predicate.%20Without%20those%20guards%2C%20lazy%2Feager%20relationship%20loads%20can%20accumulate%20redundant%20%60deleted_at%20IS%20NULL%60%20clauses%20and%20increase%20query%20complexity%2Flatency.%20Gate%20this%20block%20with%20%60not%20execute_state.is_column_load%60%20and%20%60not%20execute_state.is_relationship_load%60.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/models/helpers.py
   **Line:** 739:746
   **Comment:**
   	*Performance: The global `do_orm_execute` hook applies `with_loader_criteria` to every SELECT, including relationship and column loader queries; SQLAlchemy's recommended pattern excludes those loader paths to avoid repeatedly stacking the same predicate. Without those guards, lazy/eager relationship loads can accumulate redundant `deleted_at IS NULL` clauses and increase query complexity/latency. Gate this block with `not execute_state.is_column_load` and `not execute_state.is_relationship_load`.
   
   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%2F39977&comment_hash=d180fe9bf0502362a0a16b59f634fb4edb8d854a07eacdb05f51bbae773a68ca&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39977&comment_hash=d180fe9bf0502362a0a16b59f634fb4edb8d854a07eacdb05f51bbae773a68ca&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(core): SoftDeleteMixin and restore infrastructure [superset]

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

   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