mikebridge commented on code in PR #41549:
URL: https://github.com/apache/superset/pull/41549#discussion_r3574287594


##########
superset/migrations/versions/2026-06-23_13-00_e7d93a524ff6_add_purge_audit_log.py:
##########
@@ -0,0 +1,66 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add purge_audit_log
+
+Immutable, content-free audit record for deletion-retention purges. Survives
+the entity it names; written write-ahead (pending -> confirmed).
+
+Revision ID: e7d93a524ff6
+Revises: 8f3a1b2c4d5e
+Create Date: 2026-06-23 13:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "e7d93a524ff6"
+down_revision = "8f3a1b2c4d5e"
+
+
+def upgrade() -> None:
+    op.create_table(
+        "purge_audit_log",
+        sa.Column("id", sa.Integer(), nullable=False),
+        sa.Column("status", sa.String(length=16), nullable=False),
+        sa.Column("trigger", sa.String(length=16), nullable=False),
+        sa.Column("actor", sa.String(length=256), nullable=False),
+        sa.Column("entity_type", sa.String(length=64), nullable=False),
+        sa.Column("entity_uuid", sa.String(length=36), nullable=True),
+        sa.Column("affected_referrers", sa.Text(), nullable=True),
+        sa.Column(
+            "removed_dashboard_slices",
+            sa.Integer(),
+            server_default="0",
+            nullable=False,
+        ),
+        sa.Column("created_on", sa.DateTime(), nullable=False),
+        sa.Column("confirmed_on", sa.DateTime(), nullable=True),
+        sa.PrimaryKeyConstraint("id"),
+    )

Review Comment:
   Addressed in 5b4b2460fc: the migration now creates the table through the 
shared create_table helper.



##########
superset/migrations/versions/2026-06-23_13-00_e7d93a524ff6_add_purge_audit_log.py:
##########
@@ -0,0 +1,66 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add purge_audit_log
+
+Immutable, content-free audit record for deletion-retention purges. Survives
+the entity it names; written write-ahead (pending -> confirmed).
+
+Revision ID: e7d93a524ff6
+Revises: 8f3a1b2c4d5e
+Create Date: 2026-06-23 13:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "e7d93a524ff6"
+down_revision = "8f3a1b2c4d5e"
+
+
+def upgrade() -> None:
+    op.create_table(
+        "purge_audit_log",
+        sa.Column("id", sa.Integer(), nullable=False),
+        sa.Column("status", sa.String(length=16), nullable=False),
+        sa.Column("trigger", sa.String(length=16), nullable=False),
+        sa.Column("actor", sa.String(length=256), nullable=False),
+        sa.Column("entity_type", sa.String(length=64), nullable=False),
+        sa.Column("entity_uuid", sa.String(length=36), nullable=True),
+        sa.Column("affected_referrers", sa.Text(), nullable=True),
+        sa.Column(
+            "removed_dashboard_slices",
+            sa.Integer(),
+            server_default="0",
+            nullable=False,
+        ),
+        sa.Column("created_on", sa.DateTime(), nullable=False),
+        sa.Column("confirmed_on", sa.DateTime(), nullable=True),
+        sa.PrimaryKeyConstraint("id"),
+    )
+    op.create_index(
+        "ix_purge_audit_log_entity_uuid",
+        "purge_audit_log",
+        ["entity_uuid"],
+        unique=False,
+    )

Review Comment:
   Addressed in 5b4b2460fc: migration indexes now use the shared create_index 
helper.



##########
superset/migrations/versions/2026-06-23_13-00_e7d93a524ff6_add_purge_audit_log.py:
##########
@@ -0,0 +1,66 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add purge_audit_log
+
+Immutable, content-free audit record for deletion-retention purges. Survives
+the entity it names; written write-ahead (pending -> confirmed).
+
+Revision ID: e7d93a524ff6
+Revises: 8f3a1b2c4d5e
+Create Date: 2026-06-23 13:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "e7d93a524ff6"
+down_revision = "8f3a1b2c4d5e"
+
+
+def upgrade() -> None:
+    op.create_table(
+        "purge_audit_log",
+        sa.Column("id", sa.Integer(), nullable=False),
+        sa.Column("status", sa.String(length=16), nullable=False),
+        sa.Column("trigger", sa.String(length=16), nullable=False),
+        sa.Column("actor", sa.String(length=256), nullable=False),
+        sa.Column("entity_type", sa.String(length=64), nullable=False),
+        sa.Column("entity_uuid", sa.String(length=36), nullable=True),
+        sa.Column("affected_referrers", sa.Text(), nullable=True),
+        sa.Column(
+            "removed_dashboard_slices",
+            sa.Integer(),
+            server_default="0",
+            nullable=False,
+        ),
+        sa.Column("created_on", sa.DateTime(), nullable=False),
+        sa.Column("confirmed_on", sa.DateTime(), nullable=True),
+        sa.PrimaryKeyConstraint("id"),
+    )
+    op.create_index(
+        "ix_purge_audit_log_entity_uuid",
+        "purge_audit_log",
+        ["entity_uuid"],
+        unique=False,
+    )
+
+
+def downgrade() -> None:
+    op.drop_index("ix_purge_audit_log_entity_uuid", 
table_name="purge_audit_log")
+    op.drop_table("purge_audit_log")

Review Comment:
   Addressed in 5b4b2460fc: downgrade now uses the shared drop_index and 
drop_table helpers.



##########
tests/integration_tests/deletion_retention/window_tests.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.
+"""Integration coverage for the per-workspace retention window."""
+
+from __future__ import annotations
+
+from superset.commands.deletion_retention.window import 
resolve_retention_window
+from superset.key_value.shared_entries import get_shared_value, 
upsert_shared_value
+from superset.key_value.types import SharedKey
+from superset.models.slice import Slice
+from superset.tasks.deletion_retention import _purge_impl
+
+from ._base import DeletionRetentionTestBase
+
+
+class TestRetentionWindow(DeletionRetentionTestBase):
+    def tearDown(self) -> None:
+        # clear any shared window value this test set so the env default is
+        # restored for other tests
+        from uuid import uuid3
+
+        from superset import db
+        from superset.daos.key_value import KeyValueDAO
+        from superset.key_value.shared_entries import RESOURCE
+        from superset.key_value.utils import get_uuid_namespace
+
+        try:
+            KeyValueDAO.delete_entry(
+                RESOURCE,
+                uuid3(get_uuid_namespace(""), 
SharedKey.SOFT_DELETE_RETENTION_DAYS),
+            )
+            db.session.commit()
+        except Exception:  # pylint: disable=broad-except
+            db.session.rollback()
+        super().tearDown()
+
+    def test_shared_value_overrides_env_and_is_used_by_task(self) -> None:
+        """A per-workspace shared value takes
+        precedence over the env default and is honored by the purge."""
+        upsert_shared_value(SharedKey.SOFT_DELETE_RETENTION_DAYS, 10)
+        assert resolve_retention_window() == 10
+
+        # 20 days old: still inside the env default (30) but past the 10-day
+        # per-workspace override, so the override is what gets it purged
+        chart = self.make_chart("c")
+        chart_id = chart.id
+        self.soft_delete(chart, days_ago=20)
+
+        _purge_impl(resolve_retention_window(), dry_run=False)

Review Comment:
   Addressed in 5b4b2460fc: the integration test invokes 
purge_soft_deleted.run() and verifies the shared retention override through the 
real task entrypoint.



##########
tests/unit_tests/tasks/test_deletion_retention.py:
##########
@@ -0,0 +1,131 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for deletion-retention configuration and window resolution.
+
+The shared value overrides config, an unset value falls back to config, ``0``
+is preserved as the disable value, and malformed shared values use the 
fallback.
+"""
+
+from datetime import datetime
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+from flask.config import Config
+
+
[email protected]
+def app_config(app_context: None) -> Config:
+    from flask import current_app
+
+    current_app.config["SUPERSET_SOFT_DELETE_RETENTION_DAYS"] = 30
+    return current_app.config
+
+
+def _resolve() -> int:
+    from superset.commands.deletion_retention.window import 
resolve_retention_window
+
+    return resolve_retention_window()
+
+
+def test_unset_falls_back_to_config(app_config: Config) -> None:
+    with patch(
+        "superset.commands.deletion_retention.window.get_shared_value",
+        return_value=None,
+    ):
+        assert _resolve() == 30
+
+
+def test_shared_value_overrides_config(app_config: Config) -> None:
+    with patch(
+        "superset.commands.deletion_retention.window.get_shared_value",
+        return_value=7,
+    ):
+        assert _resolve() == 7
+
+
+def test_zero_shared_value_is_preserved_not_coerced(app_config: Config) -> 
None:
+    # `0` is a meaningful "disable"; it must survive (never `or`-coerced to 
30).
+    with patch(
+        "superset.commands.deletion_retention.window.get_shared_value",
+        return_value=0,
+    ):
+        assert _resolve() == 0
+
+
+def test_malformed_shared_value_falls_back(app_config: Config) -> None:
+    for bad in ("oops", -3, True, 1.5):
+        with patch(
+            "superset.commands.deletion_retention.window.get_shared_value",
+            return_value=bad,
+        ):
+            assert _resolve() == 30
+
+
+def test_window_zero_disables_the_task(app_context: None) -> None:
+    # A zero window short-circuits the purge entirely.
+    import superset.tasks.deletion_retention as mod
+
+    with patch.object(mod, "_soft_delete_models") as models:
+        result = mod._purge_impl(0, dry_run=False)
+    assert result == {"skipped": 1}
+    models.assert_not_called()
+
+
+def test_clock_uses_now_not_utcnow() -> None:
+    # The cutoff uses the same clock as the soft-delete substrate's deleted_at.
+    import inspect
+
+    import superset.tasks.deletion_retention as mod
+
+    src = inspect.getsource(mod._purge_impl)
+    assert "datetime.now()" in src
+    assert "datetime.utcnow()" not in src

Review Comment:
   Addressed in 5b4b2460fc: the source-text assertion was replaced with a 
behavioral clock/cutoff assertion.



##########
tests/unit_tests/tasks/test_deletion_retention.py:
##########
@@ -0,0 +1,131 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for deletion-retention configuration and window resolution.
+
+The shared value overrides config, an unset value falls back to config, ``0``
+is preserved as the disable value, and malformed shared values use the 
fallback.
+"""
+
+from datetime import datetime
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+from flask.config import Config
+
+
[email protected]
+def app_config(app_context: None) -> Config:
+    from flask import current_app
+
+    current_app.config["SUPERSET_SOFT_DELETE_RETENTION_DAYS"] = 30
+    return current_app.config
+
+
+def _resolve() -> int:
+    from superset.commands.deletion_retention.window import 
resolve_retention_window
+
+    return resolve_retention_window()
+
+
+def test_unset_falls_back_to_config(app_config: Config) -> None:
+    with patch(
+        "superset.commands.deletion_retention.window.get_shared_value",
+        return_value=None,
+    ):
+        assert _resolve() == 30
+
+
+def test_shared_value_overrides_config(app_config: Config) -> None:
+    with patch(
+        "superset.commands.deletion_retention.window.get_shared_value",
+        return_value=7,
+    ):
+        assert _resolve() == 7
+
+
+def test_zero_shared_value_is_preserved_not_coerced(app_config: Config) -> 
None:
+    # `0` is a meaningful "disable"; it must survive (never `or`-coerced to 
30).
+    with patch(
+        "superset.commands.deletion_retention.window.get_shared_value",
+        return_value=0,
+    ):
+        assert _resolve() == 0
+
+
+def test_malformed_shared_value_falls_back(app_config: Config) -> None:
+    for bad in ("oops", -3, True, 1.5):
+        with patch(
+            "superset.commands.deletion_retention.window.get_shared_value",
+            return_value=bad,
+        ):
+            assert _resolve() == 30
+
+
+def test_window_zero_disables_the_task(app_context: None) -> None:
+    # A zero window short-circuits the purge entirely.
+    import superset.tasks.deletion_retention as mod
+
+    with patch.object(mod, "_soft_delete_models") as models:
+        result = mod._purge_impl(0, dry_run=False)
+    assert result == {"skipped": 1}
+    models.assert_not_called()
+
+
+def test_clock_uses_now_not_utcnow() -> None:
+    # The cutoff uses the same clock as the soft-delete substrate's deleted_at.
+    import inspect
+
+    import superset.tasks.deletion_retention as mod
+
+    src = inspect.getsource(mod._purge_impl)
+    assert "datetime.now()" in src
+    assert "datetime.utcnow()" not in src
+
+
+def test_default_config_is_safe() -> None:
+    from superset import config
+
+    assert config.SUPERSET_SOFT_DELETE_RETENTION_DAYS == 30
+    assert config.SUPERSET_SOFT_DELETE_PURGE_DRY_RUN is True
+
+
+def test_default_celery_config_registers_daily_purge() -> None:
+    from superset import config
+
+    assert "superset.tasks.deletion_retention" in config.CeleryConfig.imports
+    entry: dict[str, Any] = config.CeleryConfig.beat_schedule[
+        "deletion_retention.purge_soft_deleted"
+    ]
+    assert entry["task"] == "deletion_retention.purge_soft_deleted"

Review Comment:
   Addressed in 5b4b2460fc: the test now asserts the schedule minute and hour 
fields are both {0}.



##########
superset/commands/deletion_retention/force_purge.py:
##########
@@ -0,0 +1,118 @@
+# 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,
+    suspend_version_capture,
+)
+from superset.models.helpers import skip_visibility_filter, SoftDeleteMixin
+
+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 = uuid
+        self._actor = 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__)
+        record_id = audit.write_ahead(
+            trigger=audit.TRIGGER_FORCE,
+            actor=self._actor,
+            entity_type=entity_type,
+            entity_uuid=self._uuid,
+            removed_dashboard_slices=dashboard_slice_count(db.session, entity),
+        )
+        try:
+            with suspend_version_capture():
+                result: CascadeResult = cascade_hard_delete(
+                    db.session, entity, enforce_window=False
+                )
+                db.session.commit()
+        except Exception:
+            db.session.rollback()
+            audit.fail(record_id)
+            raise
+        if result.purged:
+            audit.confirm(
+                record_id,
+                affected_referrers=result.dangling_chart_uuids,
+                removed_dashboard_slices=result.removed_dashboard_slices,
+            )
+        elif result.blocked_reason is not None:
+            audit.block(record_id)
+        else:
+            audit.fail(record_id)
+        logger.info(
+            "force_purge: purged %s uuid=%s (dangling charts=%d, 
dashboard_slices=%d)",
+            result.entity_type,
+            self._uuid,
+            len(result.dangling_chart_uuids),
+            result.removed_dashboard_slices,
+        )

Review Comment:
   Addressed in 5b4b2460fc: force-purge logging now distinguishes purged, 
blocked, and no-op outcomes, with blocked behavior covered by an integration 
assertion.



##########
superset/commands/deletion_retention/window.py:
##########
@@ -0,0 +1,63 @@
+# 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.
+"""Resolve the soft-delete retention window."""
+
+from __future__ import annotations
+
+import logging
+
+from flask import current_app
+
+from superset.key_value.shared_entries import get_shared_value
+from superset.key_value.types import SharedKey
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_RETENTION_DAYS = 30
+
+
+def resolve_retention_window() -> int:
+    """Return the retention window in days, read live on each call.
+
+    Resolution order:
+
+    1. The per-workspace value persisted under
+       ``SharedKey.SOFT_DELETE_RETENTION_DAYS`` (read live; takes
+       precedence when present).
+    2. Otherwise the ``SUPERSET_SOFT_DELETE_RETENTION_DAYS`` config /
+       environment seed default (itself defaulting to 30).
+
+    ``0`` from either source is a meaningful "disable", so the shared
+    value is selected with an explicit ``is None`` check — never ``or``,
+    which would treat ``0`` as unset. A malformed shared value is
+    rejected (logged) and the fallback is used rather than crashing the
+    scheduled task.
+    """
+    if (shared := get_shared_value(SharedKey.SOFT_DELETE_RETENTION_DAYS)) is 
not None:
+        if isinstance(shared, bool) or not isinstance(shared, int) or shared < 
0:
+            logger.warning(
+                "deletion_retention: ignoring malformed shared retention value 
%r; "
+                "falling back to config",
+                shared,
+            )
+        else:
+            return shared
+    return int(
+        current_app.config.get(
+            "SUPERSET_SOFT_DELETE_RETENTION_DAYS", _DEFAULT_RETENTION_DAYS
+        )
+    )

Review Comment:
   Addressed in 5b4b2460fc: config retention values are validated and malformed 
values log a warning and fall back to 30 days; malformed cases are covered by 
tests.



##########
superset/commands/deletion_retention/purge_cascade.py:
##########
@@ -0,0 +1,526 @@
+# 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.
+"""Shared hard-delete cascade for the purge task and force-purge command.
+
+A single code path keeps the two surfaces from drifting. Every dependent row
+is removed by an explicit ``sa.delete``;
+the DB ``ON DELETE CASCADE`` constraints are a backstop only — SQLite does
+not enforce FKs unless ``PRAGMA foreign_keys=ON`` and Core bulk DML fires
+only DB-level cascades, so relying on cascade silently leaks rows.
+
+Cascade tiers:
+
+* **M:N join rows** — hard-deleted for the purged entity, including join
+  rows owned by *surviving* entities (e.g. a live dashboard's
+  ``dashboard_slices`` row to a purged chart). The entity on the other side
+  is never touched except to lose that one relationship row.
+* **Owned children** (``delete-orphan``, no independent existence) — a
+  dataset's columns and metrics, hard-deleted with it.
+* **Independently-owned entities** (a dashboard's charts, a chart's dataset)
+  are **preserved**. A live chart's loose ``datasource_id`` to a purged
+  dataset is left dangling — legacy hard-delete semantics, no guard.
+* **Version history** — the entity's own ``*_version`` shadows and
+  the ``version_changes`` scoped to them, plus an orphan-sweep of any
+  ``version_transaction`` left owning zero surviving shadows. Runs
+  behind a ``has_table`` check so it no-ops when versioning is absent.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+import sqlalchemy as sa
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.orm import Session
+
+logger = logging.getLogger(__name__)
+
+
+@contextmanager
+def suspend_version_capture() -> Iterator[None]:
+    """Turn Continuum's write tracking off for the duration of the block.
+
+    A purge *removes* version history; it must not *generate* it. Flipping
+    Continuum's master ``versioning`` option off also stops the association
+    tracker (``track_association_operations``) from firing on the cascade's
+    raw ``sa.delete`` of tracked join tables (``dashboard_slices``), which
+    otherwise raises ``KeyError`` because there is no Continuum unit-of-work
+    for a Core delete. No-op when Continuum is absent or capture is already
+    off; the prior value is always restored.
+    """
+    try:
+        from sqlalchemy_continuum import versioning_manager
+    except ImportError:
+        yield
+        return
+    previous = versioning_manager.options.get("versioning", True)
+    versioning_manager.options["versioning"] = False
+    try:
+        yield
+    finally:
+        versioning_manager.options["versioning"] = previous

Review Comment:
   Addressed in 5b4b2460fc: purge suppression is session-scoped and removes 
only association statements appended by the purge without mutating the 
process-global versioning option.



##########
superset/migrations/versions/2026-06-23_13-00_e7d93a524ff6_add_purge_audit_log.py:
##########
@@ -0,0 +1,66 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add purge_audit_log
+
+Immutable, content-free audit record for deletion-retention purges. Survives
+the entity it names; written write-ahead (pending -> confirmed).
+
+Revision ID: e7d93a524ff6
+Revises: 8f3a1b2c4d5e
+Create Date: 2026-06-23 13:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "e7d93a524ff6"
+down_revision = "8f3a1b2c4d5e"
+
+
+def upgrade() -> None:
+    op.create_table(
+        "purge_audit_log",
+        sa.Column("id", sa.Integer(), nullable=False),
+        sa.Column("status", sa.String(length=16), nullable=False),
+        sa.Column("trigger", sa.String(length=16), nullable=False),
+        sa.Column("actor", sa.String(length=256), nullable=False),
+        sa.Column("entity_type", sa.String(length=64), nullable=False),
+        sa.Column("entity_uuid", sa.String(length=36), nullable=True),
+        sa.Column("affected_referrers", sa.Text(), nullable=True),
+        sa.Column(
+            "removed_dashboard_slices",
+            sa.Integer(),
+            server_default="0",
+            nullable=False,
+        ),
+        sa.Column("created_on", sa.DateTime(), nullable=False),
+        sa.Column("confirmed_on", sa.DateTime(), nullable=True),
+        sa.PrimaryKeyConstraint("id"),
+    )
+    op.create_index(
+        "ix_purge_audit_log_entity_uuid",
+        "purge_audit_log",
+        ["entity_uuid"],
+        unique=False,

Review Comment:
   Addressed in 5b4b2460fc: the migration adds 
ix_purge_audit_log_status_created_on on (status, created_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: [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