codeant-ai-for-open-source[bot] commented on code in PR #41549:
URL: https://github.com/apache/superset/pull/41549#discussion_r3656640304


##########
superset/commands/deletion_retention/force_purge.py:
##########
@@ -0,0 +1,147 @@
+# 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.
+"""Compliance force-purge of a single entity by UUID.
+
+Immediate, irreversible removal of one entity regardless of the retention
+window or whether it is currently soft-deleted or live. Runs the same cascade
+as the time-based task with ``enforce_window=False`` — identical dependent
+handling with legacy hard-delete semantics: M:N join rows hard-deleted,
+a referencing live chart's loose ``datasource_id`` left dangling (the chart is
+never modified). Idempotent: a UUID that resolves to nothing is a no-op.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, cast
+
+from superset import db
+from superset.commands.deletion_retention import audit
+from superset.commands.deletion_retention.purge_cascade import (
+    cascade_hard_delete,
+    CascadeResult,
+    dashboard_slice_count,
+    suppress_purge_association_versions,
+)
+from superset.models.helpers import skip_visibility_filter, SoftDeleteMixin
+
+logger: logging.Logger = logging.getLogger(__name__)
+
+
+class ForcePurgeCommand:
+    """Force-purge the entity identified by *uuid*, if any."""
+
+    def __init__(self, uuid: str, actor: str = "operator") -> None:
+        self._uuid: str = uuid
+        self._actor: str = actor
+
+    def _resolve(self) -> SoftDeleteMixin | None:
+        """Find the entity across every soft-delete model by UUID, matching
+        live or soft-deleted rows (visibility-filter bypassed)."""
+        for model in SoftDeleteMixin._registered_subclasses:  # noqa: SLF001
+            if not hasattr(model, "uuid"):
+                continue
+            with skip_visibility_filter(db.session, model):
+                entity = (
+                    db.session.query(model).filter(model.uuid == 
self._uuid).first()
+                )
+            if entity is not None:
+                return entity
+        return None
+
+    def run(self) -> dict[str, Any]:
+        """Resolve + purge. Returns a summary; a no-op when nothing matches."""
+        audit.reconcile_pending()
+        entity = self._resolve()
+        if entity is None:
+            logger.info("force_purge: no entity for uuid=%s (no-op)", 
self._uuid)
+            return {"purged": False, "reason": "not_found", "uuid": self._uuid}
+
+        entity_type = str(cast(Any, type(entity)).__tablename__)
+        removed_dashboard_slices = dashboard_slice_count(db.session, entity)
+        # The audit row commits independently. Release the resolving read
+        # transaction first, then resolve again against post-audit state.
+        db.session.rollback()  # pylint: disable=consider-using-transaction
+        record_id = audit.write_ahead(
+            trigger=audit.TRIGGER_FORCE,
+            actor=self._actor,
+            entity_type=entity_type,
+            entity_uuid=self._uuid,
+            removed_dashboard_slices=removed_dashboard_slices,
+        )
+        entity = self._resolve()

Review Comment:
   **Suggestion:** The purge proceeds when `audit.write_ahead` returns `None`, 
which happens whenever the independent audit transaction fails. The entity can 
therefore be permanently deleted without any audit attempt being recorded, 
contradicting the stated audit guarantee. Either fail closed when the audit row 
cannot be written or provide a durable retry mechanism before allowing the 
purge. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Critical 🚨</summary>
   
   ```mdx
   - ❌ Force purge can delete entities without an audit record.
   - ❌ Compliance operators lose the guaranteed purge-attempt trail.
   - ⚠️ Audit finalization may fail after irreversible deletion.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Run the operator command implemented by 
`superset/cli/deletion_retention.py:79`, which
   constructs and executes `ForcePurgeCommand.run()` from
   `superset/commands/deletion_retention/force_purge.py:66`.
   
   2. Resolve an existing dashboard, chart, or dataset by UUID through
   `ForcePurgeCommand._resolve()` at `force_purge.py:52-64`.
   
   3. Cause `audit.write_ahead()` at `force_purge.py:79-85` to fail its 
independent audit
   transaction; the audit helper returns `None` when it cannot create the audit 
row.
   
   4. `ForcePurgeCommand.run()` does not check `record_id` and immediately 
resolves the
   entity again at `force_purge.py:86`, then executes `cascade_hard_delete()` at
   `force_purge.py:96` and commits at `force_purge.py:101`.
   
   5. The entity can therefore be permanently deleted while `audit.confirm()`,
   `audit.block()`, or `audit.fail()` later receives an invalid record 
identifier, leaving no
   durable write-ahead audit attempt.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6644f86796be41088b9f4a204d7c114c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6644f86796be41088b9f4a204d7c114c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/deletion_retention/force_purge.py
   **Line:** 79:86
   **Comment:**
        *Possible Bug: The purge proceeds when `audit.write_ahead` returns 
`None`, which happens whenever the independent audit transaction fails. The 
entity can therefore be permanently deleted without any audit attempt being 
recorded, contradicting the stated audit guarantee. Either fail closed when the 
audit row cannot be written or provide a durable retry mechanism before 
allowing the purge.
   
   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%2F41549&comment_hash=1017cae8accaff329ee1bf65c33a71f08a9dd8ae7a75670fb18f22b535a5c47d&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41549&comment_hash=1017cae8accaff329ee1bf65c33a71f08a9dd8ae7a75670fb18f22b535a5c47d&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: [email protected]

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


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

Reply via email to