| # 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. | |
| """Persisted saves through the real baseline, Continuum and change listeners.""" | |
| from collections.abc import Iterator | |
| from datetime import datetime, timezone | |
| from itertools import chain, repeat | |
| from typing import Any | |
| from unittest.mock import MagicMock, patch | |
| from uuid import UUID | |
| import pytest | |
| import sqlalchemy as sa | |
| from flask_appbuilder import Model | |
| from sqlalchemy.orm import Session, SessionTransaction | |
| from sqlalchemy_continuum import version_class | |
| from superset.app import SupersetApp | |
| from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn | |
| from superset.extensions import db | |
| from superset.models.core import Database | |
| from superset.models.dashboard import Dashboard | |
| from superset.models.slice import Slice | |
| from superset.versioning.activity.render import apply_record_decoration | |
| from superset.versioning.changes.table import version_changes_table | |
| from superset.versioning.queries import derive_version_uuid, get_version | |
| pytestmark: pytest.MarkDecorator = pytest.mark.parametrize( | |
| "app", [{"SQLALCHEMY_DATABASE_URI": "sqlite://"}], indirect=True | |
| ) | |
| @pytest.fixture | |
| def capture_session(app: SupersetApp) -> Iterator[Session]: | |
| """Create only disposable in-memory tables; retain native listener wiring.""" | |
| assert db.engine.url.get_backend_name() == "sqlite" | |
| assert not db.engine.url.database | |
| Model.metadata.create_all(db.engine) | |
| session: Session = db.session() | |
| yield session | |
| db.session.remove() | |
| Model.metadata.drop_all(db.engine) | |
| def history_counts(session: Session) -> dict[str, int]: | |
| """Count every shadow, association, transaction and semantic-change table.""" | |
| return { | |
| table.name: session.scalar(sa.select(sa.func.count()).select_from(table)) | |
| for table in Model.metadata.tables.values() | |
| if table.name.endswith("_version") | |
| or table.name in {"version_transaction", "version_changes"} | |
| } | |
| @pytest.mark.parametrize("chart_side", [False, True]) | |
| def test_membership_activity_only_offers_existing_snapshots( | |
| capture_session: Session, chart_side: bool | |
| ) -> None: | |
| """Membership-only saves stay visible without advertising missing snapshots.""" | |
| first: Slice = Slice(slice_name="first", viz_type="table", params="{}") | |
| dashboard: Dashboard = Dashboard(dashboard_title="original", slices=[first]) | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| dashboard.dashboard_title = "renamed" | |
| capture_session.commit() | |
| second: Slice = Slice(slice_name="second", viz_type="table", params="{}") | |
| capture_session.add(second) | |
| capture_session.commit() | |
| if chart_side: | |
| second.dashboards = [dashboard] | |
| else: | |
| dashboard.slices.append(second) | |
| capture_session.commit() | |
| records: list[dict[str, Any]] = [ | |
| dict(row) | |
| for row in capture_session.execute( | |
| sa.select(version_changes_table).where( | |
| version_changes_table.c.entity_kind == "dashboard", | |
| version_changes_table.c.entity_id == dashboard.id, | |
| ) | |
| ).mappings() | |
| ] | |
| assert any(record["kind"] == "chart" for record in records) | |
| for record in records: | |
| record["entity_name"] = dashboard.dashboard_title | |
| with patch( | |
| "superset.versioning.activity.render.resolve_editorship", | |
| return_value={("Dashboard", dashboard.id): True}, | |
| ): | |
| apply_record_decoration(records, "Dashboard", dashboard.id) | |
| dashboard_uuid = dashboard.uuid | |
| assert dashboard_uuid is not None | |
| for record in records: | |
| if record["kind"] == "chart": | |
| assert record["version_uuid"] is None | |
| else: | |
| assert record["version_uuid"] is not None | |
| assert ( | |
| get_version(Dashboard, dashboard_uuid, UUID(record["version_uuid"])) | |
| is not None | |
| ) | |
| def test_chart_activity_requires_its_own_snapshot(capture_session: Session) -> None: | |
| """A different chart's snapshot cannot make this chart previewable at that tx.""" | |
| chart: Slice = Slice(slice_name="first", viz_type="table", params="{}") | |
| capture_session.add(chart) | |
| capture_session.commit() | |
| other: Slice = Slice(slice_name="other", viz_type="table", params="{}") | |
| capture_session.add(other) | |
| capture_session.commit() | |
| shadow: Any = version_class(Slice) | |
| own_tx: int = ( | |
| capture_session.query(shadow).filter_by(id=chart.id).one().transaction_id | |
| ) | |
| other_tx: int = ( | |
| capture_session.query(shadow).filter_by(id=other.id).one().transaction_id | |
| ) | |
| records: list[dict[str, Any]] = [ | |
| { | |
| "entity_kind": "chart", | |
| "entity_id": chart.id, | |
| "transaction_id": tx, | |
| "entity_name": chart.slice_name, | |
| "kind": "field", | |
| } | |
| for tx in (own_tx, other_tx) | |
| ] | |
| with patch( | |
| "superset.versioning.activity.render.resolve_editorship", | |
| return_value={("Slice", chart.id): True}, | |
| ): | |
| apply_record_decoration(records, "Slice", chart.id) | |
| assert records[0]["version_uuid"] is not None | |
| chart_uuid = chart.uuid | |
| assert chart_uuid is not None | |
| assert get_version(Slice, chart_uuid, UUID(records[0]["version_uuid"])) is not None | |
| assert records[1]["version_uuid"] is None | |
| assert records[1]["entity_uuid"] == str(chart.uuid) | |
| @pytest.mark.parametrize("enabled", [False, True]) | |
| @pytest.mark.parametrize( | |
| "model,field", | |
| [(Slice, "slice_name"), (Dashboard, "dashboard_title"), (SqlaTable, "table_name")], | |
| ) | |
| def test_runtime_capture_new_and_edited_save( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| model: type[Model], | |
| field: str, | |
| enabled: bool, | |
| ) -> None: | |
| """Denied new/edit saves persist live state without any history writes.""" | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: enabled | |
| ) | |
| database: Database = Database(database_name="private", sqlalchemy_uri="sqlite://") | |
| capture_session.add(database) | |
| capture_session.commit() | |
| entity: Any = model(**{field: "created"}) | |
| if model is SqlaTable: | |
| entity.database = database | |
| if model is Slice: | |
| entity.viz_type = "table" | |
| entity.params = "{}" | |
| before: dict[str, int] = history_counts(capture_session) | |
| capture_session.add(entity) | |
| capture_session.commit() | |
| setattr(entity, field, "edited") | |
| capture_session.flush() | |
| setattr(entity, field, "final") | |
| capture_session.commit() | |
| capture_session.expire_all() | |
| assert getattr(capture_session.get(model, entity.id), field) == "final" | |
| if enabled: | |
| assert capture_session.query(version_class(model)).count() == 2 | |
| else: | |
| assert history_counts(capture_session) == before | |
| def test_capture_reenable_relations_and_rollback( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """Denied association statements and rolled-back edits cannot leak forward.""" | |
| policy: dict[str, bool] = {"enabled": True} | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: policy["enabled"] | |
| ) | |
| chart: Slice = Slice(slice_name="original", viz_type="table", params="{}") | |
| dashboard: Dashboard = Dashboard(dashboard_title="original") | |
| capture_session.add_all([chart, dashboard]) | |
| capture_session.commit() | |
| before: dict[str, int] = history_counts(capture_session) | |
| policy["enabled"] = False | |
| dashboard.slices.append(chart) | |
| chart.slice_name = "skipped" | |
| capture_session.flush() | |
| dashboard.dashboard_title = "skipped twice" | |
| capture_session.flush() | |
| capture_session.commit() | |
| assert dashboard.slices == [chart] | |
| assert history_counts(capture_session) == before | |
| chart.slice_name = "rolled back" | |
| capture_session.flush() | |
| capture_session.rollback() | |
| assert chart.slice_name == "skipped" | |
| policy["enabled"] = True | |
| chart.slice_name = "captured again" | |
| capture_session.commit() | |
| after: dict[str, int] = history_counts(capture_session) | |
| assert after["slices_version"] == before["slices_version"] + 1 | |
| assert after["dashboard_slices_version"] == before["dashboard_slices_version"] | |
| assert after["dashboards_version"] == before["dashboards_version"] | |
| shadow: Any = version_class(Slice) | |
| assert [ | |
| row.slice_name | |
| for row in capture_session.query(shadow).order_by(shadow.transaction_id) | |
| ] == ["original", "captured again"] | |
| def test_denied_import_style_child_writes_leave_no_capture_intent( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """Children and import action metadata follow the same non-request policy.""" | |
| from superset.versioning.changes.listener import ACTION_KIND_KEY | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: False | |
| ) | |
| database: Database = Database(database_name="private", sqlalchemy_uri="sqlite://") | |
| dataset: SqlaTable = SqlaTable(table_name="imported", database=database) | |
| dataset.columns = [TableColumn(column_name="first", type="STRING")] | |
| dataset.metrics = [SqlMetric(metric_name="count", expression="COUNT(*)")] | |
| capture_session.info[ACTION_KIND_KEY] = "import" | |
| capture_session.add(dataset) | |
| capture_session.flush() | |
| dataset.columns.append(TableColumn(column_name="second", type="STRING")) | |
| capture_session.commit() | |
| assert len(dataset.columns) == 2 | |
| assert len(dataset.metrics) == 1 | |
| assert not any(history_counts(capture_session).values()) | |
| assert ACTION_KIND_KEY not in capture_session.info | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: True | |
| ) | |
| dataset.table_name = "enabled" | |
| capture_session.commit() | |
| assert history_counts(capture_session)["tables_version"] == 2 | |
| def test_first_enabled_edit_uses_current_baseline( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """Re-enable records the existing pre-edit baseline, not skipped edit events.""" | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: False | |
| ) | |
| dashboard: Dashboard = Dashboard(dashboard_title="uncaptured creation") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| dashboard.dashboard_title = "last uncaptured state" | |
| capture_session.commit() | |
| assert not any(history_counts(capture_session).values()) | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: True | |
| ) | |
| dashboard.dashboard_title = "captured edit" | |
| capture_session.commit() | |
| shadow: Any = version_class(Dashboard) | |
| assert [ | |
| row.dashboard_title | |
| for row in capture_session.query(shadow).order_by(shadow.transaction_id) | |
| ] == ["last uncaptured state", "captured edit"] | |
| def test_runtime_denial_refuses_restore_before_mutation( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """An authorized request cannot perform a restore when capture is denied.""" | |
| from uuid import uuid4 | |
| from superset.commands.dashboard.exceptions import DashboardNotFoundError | |
| from superset.commands.dashboard.restore_version import ( | |
| RestoreDashboardVersionCommand, | |
| ) | |
| dashboard: Dashboard = Dashboard(dashboard_title="preserved") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| dashboard_uuid = dashboard.uuid | |
| assert dashboard_uuid is not None | |
| before: dict[str, int] = history_counts(capture_session) | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: False | |
| ) | |
| with pytest.raises(DashboardNotFoundError): | |
| RestoreDashboardVersionCommand(dashboard_uuid, uuid4()).run() | |
| assert dashboard.dashboard_title == "preserved" | |
| assert history_counts(capture_session) == before | |
| @pytest.mark.parametrize("existing_transaction", [False, True]) | |
| @pytest.mark.parametrize("initially_enabled", [False, True]) | |
| def test_restore_capture_decision_covers_persisted_mutation( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| existing_transaction: bool, | |
| initially_enabled: bool, | |
| ) -> None: | |
| """A restore binds its first capture decision before policy can change.""" | |
| from superset import security_manager | |
| from superset.commands.dashboard.exceptions import DashboardNotFoundError | |
| from superset.commands.dashboard.restore_version import ( | |
| RestoreDashboardVersionCommand, | |
| ) | |
| dashboard: Dashboard = Dashboard(dashboard_title="original") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| entity_uuid = dashboard.uuid | |
| assert entity_uuid is not None | |
| shadow: Any = version_class(Dashboard) | |
| transaction_id: int = capture_session.scalar( | |
| sa.select(shadow.transaction_id).where(shadow.id == dashboard.id) | |
| ) | |
| target_uuid: UUID = derive_version_uuid(entity_uuid, transaction_id) | |
| dashboard.dashboard_title = "edited" | |
| capture_session.commit() | |
| before: dict[str, int] = history_counts(capture_session) | |
| db.session.remove() | |
| session: Session = db.session() | |
| assert session.get_transaction() is None | |
| if existing_transaction: | |
| session.begin() | |
| # Model the host contract: memoize only for a real transaction; a policy | |
| # change after the first decision must not authorize an untracked restore. | |
| decisions: Iterator[bool] = chain( | |
| [initially_enabled], repeat(not initially_enabled) | |
| ) | |
| memo: dict[SessionTransaction, bool] = {} | |
| def predicate(active_session: Session) -> bool: | |
| assert active_session is session | |
| transaction: SessionTransaction | None = active_session.get_transaction() | |
| if transaction is None: | |
| return next(decisions) | |
| if transaction not in memo: | |
| memo[transaction] = next(decisions) | |
| return memo[transaction] | |
| from superset.versioning.utils import capture_enabled | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| capture_gate: MagicMock | |
| with ( | |
| patch.object(security_manager, "raise_for_editorship"), | |
| patch( | |
| "superset.commands.version_restore.capture_enabled", wraps=capture_enabled | |
| ) as capture_gate, | |
| ): | |
| if initially_enabled: | |
| RestoreDashboardVersionCommand(entity_uuid, target_uuid).run() | |
| else: | |
| with pytest.raises(DashboardNotFoundError): | |
| RestoreDashboardVersionCommand(entity_uuid, target_uuid).run() | |
| capture_gate.assert_called_once_with(session) | |
| # Both commit and denial/rollback leave no command-owned transaction open. | |
| assert session.get_transaction() is None | |
| db.session.remove() | |
| session = db.session() | |
| assert session.scalar( | |
| sa.select(Dashboard.dashboard_title).where(Dashboard.uuid == entity_uuid) | |
| ) == ("original" if initially_enabled else "edited") | |
| after: dict[str, int] = history_counts(session) | |
| if initially_enabled: | |
| assert after["dashboards_version"] == before["dashboards_version"] + 1 | |
| assert after["version_transaction"] == before["version_transaction"] + 1 | |
| assert after["version_changes"] > before["version_changes"] | |
| else: | |
| assert after == before | |
| def test_read_helpers_consult_predicate_with_request_session( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """Version reads hand the shared gate the request session the save will use.""" | |
| from superset.versioning import api_helpers, utils | |
| dashboard: Dashboard = Dashboard(dashboard_title="read") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| seen: list[Session] = [] | |
| def predicate(active_session: Session) -> bool: | |
| seen.append(active_session) | |
| return True | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| capture_gate: MagicMock | |
| with patch.object( | |
| utils, "capture_enabled", wraps=utils.capture_enabled | |
| ) as capture_gate: | |
| info: api_helpers.EntityVersionInfo = api_helpers.current_entity_version_info( | |
| Dashboard, dashboard.id | |
| ) | |
| token: str | None = api_helpers.entity_concurrency_token( | |
| Dashboard, dashboard.id, dashboard.uuid | |
| ) | |
| assert info.version_uuid is not None | |
| assert token == info.version_uuid | |
| # Discriminating check: every read-side call passes the session explicitly, | |
| # matching the restore command, rather than relying on the gate's fallback. | |
| assert capture_gate.call_args_list | |
| assert all( | |
| gate_call.args == (capture_session,) | |
| for gate_call in capture_gate.call_args_list | |
| ), capture_gate.call_args_list | |
| assert seen | |
| assert all(active is capture_session for active in seen) | |
| def test_read_helpers_accept_a_plain_session_binding( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| ) -> None: | |
| """A ``Session`` bound where the scoped proxy lives is passed through unchanged.""" | |
| from superset.versioning import api_helpers | |
| capture_gate: MagicMock = MagicMock(return_value=True) | |
| db_double: MagicMock | |
| with ( | |
| patch("superset.versioning.api_helpers.db") as db_double, | |
| patch("superset.versioning.utils.capture_enabled", capture_gate), | |
| ): | |
| db_double.session = capture_session | |
| assert api_helpers._capture_enabled() is True | |
| capture_gate.assert_called_once_with(capture_session) | |
| def test_none_predicate_result_denies_capture_and_is_memoized( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """A predicate returning ``None`` denies capture and is not re-asked.""" | |
| from sqlalchemy_continuum import versioning_manager | |
| from superset.versioning.unit_of_work import CaptureUnitOfWork | |
| from superset.versioning.utils import capture_enabled | |
| predicate: MagicMock = MagicMock(return_value=None) | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| assert capture_enabled(capture_session) is False | |
| unit: CaptureUnitOfWork = CaptureUnitOfWork(versioning_manager) | |
| predicate.reset_mock() | |
| assert unit._capture_enabled(capture_session) is False | |
| assert unit._capture_enabled(capture_session) is False | |
| predicate.assert_called_once_with(capture_session) | |
| @pytest.mark.parametrize("enabled", [False, True]) | |
| def test_nonversioned_transaction_never_consults_capture_policy( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| enabled: bool, | |
| ) -> None: | |
| """Unrelated writes and empty commits do not ask the host for policy.""" | |
| predicate: MagicMock = MagicMock(return_value=enabled) | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| database: Database = Database(database_name="unrelated", sqlalchemy_uri="sqlite://") | |
| capture_session.add(database) | |
| capture_session.flush() | |
| database.database_name = "edited" | |
| capture_session.commit() | |
| capture_session.commit() | |
| assert not any(history_counts(capture_session).values()) | |
| predicate.assert_not_called() | |
| @pytest.mark.parametrize("unrelated_first", [False, True]) | |
| @pytest.mark.parametrize("enabled", [False, True]) | |
| def test_first_versioned_flush_freezes_policy_through_finalization( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| unrelated_first: bool, | |
| enabled: bool, | |
| ) -> None: | |
| """One decision covers shadows and semantic changes across mixed flushes.""" | |
| dashboard: Dashboard = Dashboard(dashboard_title="original") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| before: dict[str, int] = history_counts(capture_session) | |
| predicate: MagicMock = MagicMock(return_value=enabled) | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| if unrelated_first: | |
| capture_session.add( | |
| Database(database_name="unrelated", sqlalchemy_uri="sqlite://") | |
| ) | |
| capture_session.flush() | |
| predicate.assert_not_called() | |
| dashboard.dashboard_title = "intermediate" | |
| capture_session.flush() | |
| predicate.assert_called_once_with(capture_session) | |
| predicate.return_value = not enabled | |
| dashboard.dashboard_title = "final" | |
| capture_session.commit() | |
| predicate.assert_called_once_with(capture_session) | |
| after: dict[str, int] = history_counts(capture_session) | |
| assert after["dashboards_version"] == before["dashboards_version"] + int(enabled) | |
| assert (after["version_changes"] > before["version_changes"]) is enabled | |
| @pytest.mark.parametrize( | |
| "enabled,rollback_nested", | |
| [ | |
| (False, False), | |
| (False, True), | |
| (True, False), | |
| (True, True), | |
| ], | |
| ) | |
| def test_lazy_capture_savepoint_and_query_autoflush( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| rollback_nested: bool, | |
| enabled: bool, | |
| ) -> None: | |
| """Savepoint completion keeps the outer decision through query autoflush.""" | |
| predicate: MagicMock = MagicMock(return_value=enabled) | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| capture_session.add(Database(database_name="unrelated", sqlalchemy_uri="sqlite://")) | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| predicate.assert_not_called() | |
| dashboard: Dashboard = Dashboard(dashboard_title="nested") | |
| capture_session.add(dashboard) | |
| assert ( | |
| capture_session.scalar(sa.select(sa.func.count()).select_from(Dashboard)) == 1 | |
| ) | |
| predicate.assert_called_once_with(capture_session) | |
| predicate.return_value = not enabled | |
| if rollback_nested: | |
| nested.rollback() | |
| else: | |
| nested.commit() | |
| capture_session.add(Dashboard(dashboard_title="outer")) | |
| capture_session.commit() | |
| predicate.assert_called_once_with(capture_session) | |
| assert history_counts(capture_session)["dashboards_version"] == ( | |
| (1 if rollback_nested else 2) if enabled else 0 | |
| ) | |
| @pytest.mark.parametrize("soft_delete", [False, True]) | |
| @pytest.mark.parametrize("enabled", [False, True]) | |
| def test_lazy_capture_delete_policy( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| soft_delete: bool, | |
| enabled: bool, | |
| ) -> None: | |
| """Both deletion paths consult policy once and preserve allowed history.""" | |
| dashboard: Dashboard = Dashboard(dashboard_title="delete me") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| before: dict[str, int] = history_counts(capture_session) | |
| predicate: MagicMock = MagicMock(return_value=enabled) | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| if soft_delete: | |
| dashboard.deleted_at = datetime.now(timezone.utc) | |
| else: | |
| capture_session.delete(dashboard) | |
| capture_session.commit() | |
| predicate.assert_called_once_with(capture_session) | |
| assert history_counts(capture_session)["dashboards_version"] == ( | |
| before["dashboards_version"] + int(enabled and not soft_delete) | |
| ) | |
| def test_lazy_capture_predicate_error_still_propagates( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """Laziness does not turn a host programming failure into silent denial.""" | |
| predicate: MagicMock = MagicMock(side_effect=RuntimeError("policy failed")) | |
| monkeypatch.setitem(app.config, "VERSIONING_CAPTURE_PREDICATE", predicate) | |
| capture_session.add(Dashboard(dashboard_title="not committed")) | |
| with pytest.raises(RuntimeError, match="policy failed"): | |
| capture_session.commit() | |
| capture_session.rollback() | |
| assert not any(history_counts(capture_session).values()) | |
| def test_capture_after_savepoint_rollback_with_stable_policy( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| ) -> None: | |
| """A rolled-back shadow cannot poison a subsequent outer-transaction save.""" | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: True | |
| ) | |
| capture_session.add(Database(database_name="unrelated", sqlalchemy_uri="sqlite://")) | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| capture_session.add(Dashboard(dashboard_title="rolled back")) | |
| capture_session.flush() | |
| nested.rollback() | |
| capture_session.add(Dashboard(dashboard_title="outer")) | |
| capture_session.commit() | |
| assert history_counts(capture_session)["dashboards_version"] == 1 | |
| @pytest.mark.parametrize("query_autoflush", [False, True]) | |
| def test_capture_after_savepoint_rollback( | |
| capture_session: Session, | |
| query_autoflush: bool, | |
| ) -> None: | |
| """A rolled-back insert cannot poison history for a surviving insert.""" | |
| from sqlalchemy_continuum import versioning_manager | |
| capture_session.add(Database(database_name="unrelated", sqlalchemy_uri="sqlite://")) | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| capture_session.add(Dashboard(dashboard_title="rolled back")) | |
| if query_autoflush: | |
| assert ( | |
| capture_session.scalar(sa.select(sa.func.count()).select_from(Dashboard)) | |
| == 1 | |
| ) | |
| else: | |
| capture_session.flush() | |
| nested.rollback() | |
| capture_session.add(Dashboard(dashboard_title="outer")) | |
| capture_session.commit() | |
| shadow: Any = version_class(Dashboard) | |
| assert capture_session.scalars(sa.select(Dashboard.dashboard_title)).all() == [ | |
| "outer" | |
| ] | |
| assert capture_session.execute( | |
| sa.select( | |
| shadow.dashboard_title, shadow.operation_type, shadow.end_transaction_id | |
| ) | |
| ).all() == [("outer", 0, None)] | |
| assert history_counts(capture_session)["version_transaction"] == 1 | |
| # Shadow transaction IDs must reference surviving rows on every dialect. | |
| assert capture_session.scalar(sa.select(shadow.transaction_id)) in ( | |
| capture_session.scalars(sa.select(versioning_manager.transaction_cls.id)).all() | |
| ) | |
| def test_savepoint_rollback_reapplying_same_value(capture_session: Session) -> None: | |
| """Reapplying a rolled-back value must dirty the cached shadow again.""" | |
| dashboard: Dashboard = Dashboard(dashboard_title="original") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| dashboard.dashboard_title = "outer edit" | |
| capture_session.flush() | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| dashboard.dashboard_title = "discarded edit" | |
| capture_session.flush() | |
| nested.rollback() | |
| dashboard.dashboard_title = "discarded edit" | |
| capture_session.commit() | |
| shadow: Any = version_class(Dashboard) | |
| assert dashboard.dashboard_title == "discarded edit" | |
| assert capture_session.scalars( | |
| sa.select(shadow.dashboard_title).order_by(shadow.transaction_id) | |
| ).all() == ["original", "discarded edit"] | |
| @pytest.mark.parametrize("rollback_nested", [False, True]) | |
| def test_ending_enclosing_savepoint_clears_inner_checkpoints( | |
| capture_session: Session, rollback_nested: bool | |
| ) -> None: | |
| """Closing an enclosing savepoint must release its open descendants' state.""" | |
| from superset.versioning.savepoints import _CHECKPOINTS_KEY | |
| dashboard: Dashboard = Dashboard(dashboard_title="outer") | |
| capture_session.add(dashboard) | |
| capture_session.flush() | |
| enclosing: SessionTransaction = capture_session.begin_nested() | |
| inner: SessionTransaction = capture_session.begin_nested() | |
| dashboard.dashboard_title = "inner" | |
| capture_session.flush() | |
| assert len(capture_session.info[_CHECKPOINTS_KEY]) == 2 | |
| if rollback_nested: | |
| enclosing.rollback() | |
| else: | |
| enclosing.commit() | |
| assert not inner.is_active | |
| assert not capture_session.info.get(_CHECKPOINTS_KEY) | |
| capture_session.commit() | |
| shadow: Any = version_class(Dashboard) | |
| expected: str = "outer" if rollback_nested else "inner" | |
| assert dashboard.dashboard_title == expected | |
| assert capture_session.scalars(sa.select(shadow.dashboard_title)).all() == [ | |
| expected | |
| ] | |
| @pytest.mark.parametrize("inner_commit", [False, True]) | |
| @pytest.mark.parametrize("edit_after_rollback", [False, True]) | |
| def test_savepoint_rollback_preserves_outer_history( | |
| capture_session: Session, | |
| inner_commit: bool, | |
| edit_after_rollback: bool, | |
| ) -> None: | |
| """Rollback restores cached shadows and pending diffs, including nested work.""" | |
| from superset.versioning.changes.table import version_changes_table | |
| dashboard: Dashboard = Dashboard(dashboard_title="original") | |
| chart: Slice = Slice(slice_name="chart", viz_type="table", params="{}") | |
| capture_session.add_all([dashboard, chart]) | |
| capture_session.commit() | |
| dashboard.dashboard_title = "outer edit" | |
| capture_session.flush() | |
| shadow: Any = version_class(Dashboard) | |
| outer_tx: int = capture_session.scalar( | |
| sa.select(sa.func.max(shadow.transaction_id)) | |
| ) | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| dashboard.dashboard_title = "discarded edit" | |
| dashboard.slices.append(chart) | |
| capture_session.add(Dashboard(dashboard_title="discarded insert")) | |
| capture_session.flush() | |
| if inner_commit: | |
| with capture_session.begin_nested(): | |
| dashboard.dashboard_title = "discarded inner edit" | |
| capture_session.flush() | |
| nested.rollback() | |
| if edit_after_rollback: | |
| dashboard.dashboard_title = "surviving edit" | |
| capture_session.commit() | |
| expected: str = "surviving edit" if edit_after_rollback else "outer edit" | |
| assert dashboard.dashboard_title == expected | |
| assert dashboard.slices == [] | |
| assert capture_session.execute( | |
| sa.select( | |
| shadow.dashboard_title, shadow.operation_type, shadow.end_transaction_id | |
| ).order_by(shadow.transaction_id) | |
| ).all() == [("original", 0, outer_tx), (expected, 1, None)] | |
| assert history_counts(capture_session)["version_transaction"] == 2 | |
| assert history_counts(capture_session)["dashboard_slices_version"] == 0 | |
| assert capture_session.execute( | |
| sa.select(version_changes_table.c.from_value, version_changes_table.c.to_value) | |
| .where(version_changes_table.c.entity_kind == "dashboard") | |
| .where(version_changes_table.c.transaction_id == outer_tx) | |
| ).all() == [("original", expected)] | |
| @pytest.mark.parametrize("enabled", [False, True]) | |
| @pytest.mark.parametrize("rollback_outer", [False, True]) | |
| def test_savepoint_commit_obeys_outer_transaction( | |
| capture_session: Session, | |
| app: SupersetApp, | |
| monkeypatch: pytest.MonkeyPatch, | |
| enabled: bool, | |
| rollback_outer: bool, | |
| ) -> None: | |
| """Releasing a savepoint does not independently commit live or history rows.""" | |
| monkeypatch.setitem( | |
| app.config, "VERSIONING_CAPTURE_PREDICATE", lambda session: enabled | |
| ) | |
| capture_session.add(Database(database_name="unrelated", sqlalchemy_uri="sqlite://")) | |
| with capture_session.begin_nested(): | |
| capture_session.add(Dashboard(dashboard_title="nested")) | |
| capture_session.flush() | |
| if rollback_outer: | |
| capture_session.rollback() | |
| else: | |
| capture_session.commit() | |
| assert capture_session.scalars(sa.select(Dashboard.dashboard_title)).all() == ( | |
| [] if rollback_outer else ["nested"] | |
| ) | |
| assert history_counts(capture_session)["dashboards_version"] == int( | |
| enabled and not rollback_outer | |
| ) | |
| def test_savepoint_rollback_removes_deleted_entity_and_action_intent( | |
| capture_session: Session, | |
| ) -> None: | |
| """A rolled-back deletion/action cannot change a later ordinary save's history.""" | |
| from sqlalchemy_continuum import versioning_manager | |
| from superset.versioning.changes.listener import ACTION_KIND_KEY | |
| from superset.versioning.changes.table import version_changes_table | |
| dashboard: Dashboard = Dashboard(dashboard_title="original") | |
| capture_session.add(dashboard) | |
| capture_session.commit() | |
| capture_session.add(Database(database_name="unrelated", sqlalchemy_uri="sqlite://")) | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| capture_session.info[ACTION_KIND_KEY] = "restore" | |
| capture_session.delete(dashboard) | |
| capture_session.flush() | |
| nested.rollback() | |
| dashboard.dashboard_title = "surviving edit" | |
| capture_session.commit() | |
| shadow: Any = version_class(Dashboard) | |
| assert capture_session.execute( | |
| sa.select(shadow.dashboard_title, shadow.operation_type).order_by( | |
| shadow.transaction_id | |
| ) | |
| ).all() == [("original", 0), ("surviving edit", 1)] | |
| assert capture_session.scalars( | |
| sa.select(versioning_manager.transaction_cls.action_kind) | |
| ).all() == ["create", None] | |
| assert capture_session.execute( | |
| sa.select(version_changes_table.c.from_value, version_changes_table.c.to_value) | |
| ).all() == [("original", "surviving edit")] | |
| @pytest.mark.parametrize("rollback_nested", [False, True]) | |
| def test_capture_after_savepoint_and_unrelated_flush( | |
| capture_session: Session, rollback_nested: bool | |
| ) -> None: | |
| """An unrelated flush cannot detach a surviving shadow from later edits.""" | |
| dashboard: Dashboard = Dashboard(dashboard_title="first") | |
| capture_session.add(dashboard) | |
| capture_session.flush() | |
| nested: SessionTransaction = capture_session.begin_nested() | |
| dashboard.dashboard_title = "nested" | |
| capture_session.flush() | |
| if rollback_nested: | |
| nested.rollback() | |
| else: | |
| nested.commit() | |
| capture_session.add(Database(database_name="unrelated", sqlalchemy_uri="sqlite://")) | |
| capture_session.flush() | |
| dashboard.dashboard_title = "last" | |
| capture_session.commit() | |
| shadow: Any = version_class(Dashboard) | |
| assert capture_session.scalars(sa.select(shadow.dashboard_title)).all() == ["last"] |