You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/07/18 18:07:01 UTC
(superset) branch master updated: feat(versioning): cross-entity version activity view (#41076)
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new caf017bd0b3 feat(versioning): cross-entity version activity view (#41076)
caf017bd0b3 is described below
commit caf017bd0b3636c6a2e19f9a98958866d0a500d5
Author: Mike Bridge <mi...@bridgecanada.com>
AuthorDate: Sat Jul 18 12:06:54 2026 -0600
feat(versioning): cross-entity version activity view (#41076)
Co-authored-by: Mike Bridge <mi...@ext.preset.io>
Co-authored-by: Claude Opus 4.8 (1M context) <no...@anthropic.com>
---
UPDATING.md | 13 +
superset/charts/api.py | 85 +-
superset/constants.py | 1 +
superset/dashboards/api.py | 91 +-
superset/datasets/api.py | 93 +-
superset/versioning/activity/__init__.py | 102 ++
superset/versioning/activity/impact.py | 186 +++
superset/versioning/activity/kinds.py | 210 ++++
superset/versioning/activity/orchestrator.py | 434 +++++++
superset/versioning/activity/queries.py | 870 ++++++++++++++
superset/versioning/activity/render.py | 285 +++++
superset/versioning/activity/scope.py | 138 +++
superset/versioning/activity/visibility.py | 206 ++++
superset/versioning/activity/windows.py | 108 ++
superset/versioning/api_helpers.py | 127 +-
superset/versioning/changes/listener.py | 26 +
superset/versioning/diff.py | 8 +-
superset/versioning/schemas.py | 332 +++++-
.../versioning/activity_view_tests.py | 1256 ++++++++++++++++++++
.../versioning/change_records_tests.py | 718 +++++++++++
.../versioning/perf_validation_tests.py | 423 +++++++
tests/unit_tests/versioning/test_activity.py | 827 +++++++++++++
22 files changed, 6477 insertions(+), 62 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index fc2fe98b655..a7662dc5728 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -241,6 +241,19 @@ A few save- and import-path internals change **unconditionally** (independent of
These are behavior changes that take effect on upgrade regardless of `ENABLE_VERSIONING_CAPTURE`; no operator action is required.
+### Cross-entity version activity stream
+
+A read-only companion to the version-history endpoints: each entity type gains a `GET /api/v1/{chart,dashboard,dataset}/<uuid>/activity/` endpoint returning a chronological, access-filtered stream of edits — the entity's own edits plus, for charts and dashboards, transitive edits to related entities during their association windows. Datasets have no related layer in V2, so `include=related` returns an empty stream for a dataset and `include=all` reduces to the dataset's own edits.
+
+| Param | Type | Default | Purpose |
+|---|---|---|---|
+| `since` / `until` | ISO 8601 | — | Bound `issued_at` |
+| `include` | `self` \| `related` \| `all` | `all` | Own edits, related edits, or both |
+| `q` | string | — | Case-insensitive search over the full history, applied before pagination (so `count` reflects matches) |
+| `page` / `page_size` | integer | `0` / `25` | Pagination (`page_size` clamped to 200) |
+
+Authorization reuses the resource's `can_read` permission and per-object `raise_for_access`; related-entity rows are visibility-filtered to what the caller may see. The stream is empty unless version capture is on (`ENABLE_VERSIONING_CAPTURE`).
+
### Webhook alerts/reports block private/internal hosts by default
Webhook alert/report dispatch (`WebhookNotification.send`) now validates the target URL's host against the same private/internal-IP block applied to dataset import URLs. If the resolved host is in a loopback, link-local, private (RFC-1918), shared-CGNAT, or multicast range, the webhook is rejected with `NotificationParamException`.
diff --git a/superset/charts/api.py b/superset/charts/api.py
index f9d0f7e684a..137c6dfac6e 100644
--- a/superset/charts/api.py
+++ b/superset/charts/api.py
@@ -158,6 +158,7 @@ class ChartRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
"warm_up_cache",
"list_versions",
"get_version",
+ "activity",
}
class_permission_name = "Chart"
# Custom methods (``restore``) need an explicit entry; FAB's @protect()
@@ -1467,7 +1468,7 @@ class ChartRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
404:
$ref: '#/components/responses/404'
"""
- return list_versions_endpoint(self, Slice, uuid_str, access_kwarg="chart")
+ return list_versions_endpoint(self, Slice, uuid_str)
@expose(
"/<uuid_str>/versions/<version_uuid_str>/",
@@ -1524,6 +1525,82 @@ class ChartRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
404:
$ref: '#/components/responses/404'
"""
- return get_version_endpoint(
- self, Slice, uuid_str, version_uuid_str, access_kwarg="chart"
- )
+ return get_version_endpoint(self, Slice, uuid_str, version_uuid_str)
+
+ @expose("/<uuid_str>/activity/", methods=("GET",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.activity",
+ log_to_statsd=False,
+ )
+ def activity(self, uuid_str: str) -> Response:
+ """Return the cross-entity activity stream for a chart.
+ ---
+ get:
+ summary: Activity stream — chart own edits + datasets the
+ chart pointed at during association
+ parameters:
+ - in: path
+ schema:
+ type: string
+ format: uuid
+ name: uuid_str
+ description: Chart UUID
+ - in: query
+ schema:
+ type: string
+ format: date-time
+ name: since
+ - in: query
+ schema:
+ type: string
+ format: date-time
+ name: until
+ - in: query
+ schema:
+ type: string
+ enum: [self, related, all]
+ default: all
+ name: include
+ - in: query
+ schema:
+ type: string
+ name: q
+ description: >-
+ Case-insensitive search over the full history (summary,
+ entity name, kind, path, values) — applied before
+ pagination, so `count` reflects the matches.
+ - in: query
+ schema:
+ type: integer
+ minimum: 0
+ default: 0
+ name: page
+ - in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 200
+ default: 25
+ name: page_size
+ responses:
+ 200:
+ description: Activity stream ordered newest-first
+ content:
+ application/json:
+ schema: ActivityResponseSchema
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 403:
+ $ref: '#/components/responses/403'
+ 404:
+ $ref: '#/components/responses/404'
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.versioning.activity import activity_endpoint
+
+ return activity_endpoint(self, Slice, uuid_str, request.args)
diff --git a/superset/constants.py b/superset/constants.py
index 3525abc882c..3ceede47bdb 100644
--- a/superset/constants.py
+++ b/superset/constants.py
@@ -181,6 +181,7 @@ MODEL_API_RW_METHOD_PERMISSION_MAP = {
"restore": "write",
"list_versions": "read",
"get_version": "read",
+ "activity": "read",
}
EXTRA_FORM_DATA_APPEND_KEYS = {
diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py
index f38e13db05e..ed7e768c774 100644
--- a/superset/dashboards/api.py
+++ b/superset/dashboards/api.py
@@ -276,6 +276,7 @@ class DashboardRestApi(
"export_as_example",
"list_versions",
"get_version",
+ "activity",
}
resource_name = "dashboard"
allow_browser_login = True
@@ -2481,9 +2482,7 @@ class DashboardRestApi(
404:
$ref: '#/components/responses/404'
"""
- return list_versions_endpoint(
- self, Dashboard, uuid_str, access_kwarg="dashboard"
- )
+ return list_versions_endpoint(self, Dashboard, uuid_str)
@expose(
"/<uuid_str>/versions/<version_uuid_str>/",
@@ -2540,6 +2539,86 @@ class DashboardRestApi(
404:
$ref: '#/components/responses/404'
"""
- return get_version_endpoint(
- self, Dashboard, uuid_str, version_uuid_str, access_kwarg="dashboard"
- )
+ return get_version_endpoint(self, Dashboard, uuid_str, version_uuid_str)
+
+ @expose("/<uuid_str>/activity/", methods=("GET",))
+ @protect()
+ @safe
+ @permission_name("get")
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.activity",
+ log_to_statsd=False,
+ )
+ def activity(self, uuid_str: str) -> Response:
+ """Return the cross-entity activity stream for a dashboard.
+ ---
+ get:
+ summary: Activity stream — dashboard own edits + transitive
+ chart-on-dashboard and dataset-via-chart edits, time-bounded
+ by association windows
+ parameters:
+ - in: path
+ schema:
+ type: string
+ format: uuid
+ name: uuid_str
+ description: Dashboard UUID
+ - in: query
+ schema:
+ type: string
+ format: date-time
+ name: since
+ description: Lower bound on issued_at (ISO 8601, UTC)
+ - in: query
+ schema:
+ type: string
+ format: date-time
+ name: until
+ description: Upper bound on issued_at (ISO 8601, UTC)
+ - in: query
+ schema:
+ type: string
+ enum: [self, related, all]
+ default: all
+ name: include
+ - in: query
+ schema:
+ type: string
+ name: q
+ description: >-
+ Case-insensitive search over the full history (summary,
+ entity name, kind, path, values) — applied before
+ pagination, so `count` reflects the matches.
+ - in: query
+ schema:
+ type: integer
+ minimum: 0
+ default: 0
+ name: page
+ - in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 200
+ default: 25
+ name: page_size
+ responses:
+ 200:
+ description: Activity stream ordered newest-first
+ content:
+ application/json:
+ schema: ActivityResponseSchema
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 403:
+ $ref: '#/components/responses/403'
+ 404:
+ $ref: '#/components/responses/404'
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.versioning.activity import activity_endpoint
+
+ return activity_endpoint(self, Dashboard, uuid_str, request.args)
diff --git a/superset/datasets/api.py b/superset/datasets/api.py
index 99a8a84739a..ca353e9872d 100644
--- a/superset/datasets/api.py
+++ b/superset/datasets/api.py
@@ -24,6 +24,7 @@ from typing import Any, Callable
from zipfile import is_zipfile, ZipFile
from flask import request, Response, send_file
+from flask_appbuilder import permission_name
from flask_appbuilder.api import expose, protect, rison as parse_rison, safe
from flask_appbuilder.api.schemas import get_item_schema
from flask_appbuilder.const import API_RESULT_RES_KEY, API_SELECT_COLUMNS_RIS_KEY
@@ -150,6 +151,7 @@ class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
"get_drill_info",
"list_versions",
"get_version",
+ "activity",
}
list_columns = [
"id",
@@ -1744,9 +1746,7 @@ class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
404:
$ref: '#/components/responses/404'
"""
- return list_versions_endpoint(
- self, SqlaTable, uuid_str, access_kwarg="datasource"
- )
+ return list_versions_endpoint(self, SqlaTable, uuid_str)
@expose(
"/<uuid_str>/versions/<version_uuid_str>/",
@@ -1808,6 +1808,87 @@ class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
404:
$ref: '#/components/responses/404'
"""
- return get_version_endpoint(
- self, SqlaTable, uuid_str, version_uuid_str, access_kwarg="datasource"
- )
+ return get_version_endpoint(self, SqlaTable, uuid_str, version_uuid_str)
+
+ @expose("/<uuid_str>/activity/", methods=("GET",))
+ @protect()
+ @safe
+ @permission_name("get")
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.activity",
+ log_to_statsd=False,
+ )
+ def activity(self, uuid_str: str) -> Response:
+ """Return the activity stream for a dataset.
+ ---
+ get:
+ summary: Activity stream — dataset's own edits only.
+ Datasets have no transitive layer in V2 — chart and
+ dashboard edits that touch this dataset do NOT appear here.
+ ``?include=self`` and ``?include=all`` return the dataset's
+ own edits; ``?include=related`` returns an empty stream
+ (a dataset has no related entities to fan out to).
+ parameters:
+ - in: path
+ schema:
+ type: string
+ format: uuid
+ name: uuid_str
+ description: Dataset UUID
+ - in: query
+ schema:
+ type: string
+ format: date-time
+ name: since
+ - in: query
+ schema:
+ type: string
+ format: date-time
+ name: until
+ - in: query
+ schema:
+ type: string
+ enum: [self, related, all]
+ default: all
+ name: include
+ - in: query
+ schema:
+ type: string
+ name: q
+ description: >-
+ Case-insensitive search over the full history (summary,
+ entity name, kind, path, values) — applied before
+ pagination, so `count` reflects the matches.
+ - in: query
+ schema:
+ type: integer
+ minimum: 0
+ default: 0
+ name: page
+ - in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 200
+ default: 25
+ name: page_size
+ responses:
+ 200:
+ description: Activity stream ordered newest-first
+ content:
+ application/json:
+ schema: ActivityResponseSchema
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 403:
+ $ref: '#/components/responses/403'
+ 404:
+ $ref: '#/components/responses/404'
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.versioning.activity import activity_endpoint
+
+ return activity_endpoint(self, SqlaTable, uuid_str, request.args)
diff --git a/superset/versioning/activity/__init__.py b/superset/versioning/activity/__init__.py
new file mode 100644
index 00000000000..5dd9bec0292
--- /dev/null
+++ b/superset/versioning/activity/__init__.py
@@ -0,0 +1,102 @@
+# 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.
+"""Read-side queries for the cross-entity activity-view API.
+
+Companion to :mod:`superset.versioning.queries`. Whereas ``queries.py``
+returns transaction-level history for a single entity, the helpers
+here unify change-record history across an entity's transitive
+dependency chain — a dashboard's activity stream includes edits to
+charts that were attached to it AND edits to datasets those charts
+pointed at, each time-bounded by when the relationship was active.
+
+One public entry point — :func:`get_activity` — dispatches on the
+first argument to serve all three endpoint families:
+
+* ``get_activity(Dashboard, dashboard_uuid, ...)`` — own edits +
+ charts attached during their dashboard window + datasets those
+ charts used during their chart window.
+* ``get_activity(Slice, chart_uuid, ...)`` — own edits + datasets the
+ chart pointed at during association.
+* ``get_activity(SqlaTable, dataset_uuid, ...)`` — own edits only.
+ Datasets are not transitive recipients of activity in V2.
+
+Package layout (descends from public entry point to leaf helpers):
+
+* :mod:`.orchestrator` — :func:`get_activity` (public), the
+ ``activity_endpoint`` REST helper, the request param parser
+ (:func:`parse_activity_query_params`), and the observability
+ instrumentation (request-shape + per-kind metrics).
+* :mod:`.scope` — scope resolution (DB-touching):
+ :func:`resolve_scope` / :func:`_resolve_dashboard_scope` /
+ :func:`_resolve_chart_scope` / :func:`_resolve_related_scope`.
+* :mod:`.windows` — pure window arithmetic on half-open
+ ``[start_tx, end_tx)`` intervals: :func:`intersect_windows` /
+ :func:`union_windows` / :func:`merge_entity_windows` /
+ :func:`row_within_any_window`. Extracted from :mod:`.scope` so
+ :mod:`.queries` can import the pure helpers at module-top instead
+ of through a cycle-dodging lazy import.
+* :mod:`.queries` — every DB-touching helper: Phase A relationship
+ walks, Phase B change-record fetch, name denormalization,
+ path-entity resolution, and tombstone-state lookup.
+* :mod:`.impact` — per-record impact-count computation (the only
+ field that requires its own batched query).
+* :mod:`.visibility` — the silent visibility filter; uses
+ the same SQL-side access filters FAB applies on list endpoints.
+* :mod:`.render` — record-decoration helpers that turn raw rows into
+ the ActivityRecord DTO (summary headlines, ``changed_by`` projection,
+ uuid lookup).
+* :mod:`.kinds` — the kind-translation tables, the ``Window`` /
+ ``EntityWindows`` type aliases, and :func:`load_live_model`.
+
+The public surface (re-exported here) is the eight symbols below.
+Sub-module privates are intentionally NOT re-exported — tests and
+new internal callers should import them from their owning submodule
+(e.g. ``from superset.versioning.activity.windows import
+intersect_windows``) so the package's public API stays scannable.
+
+``PathEntityResponseError`` and ``resolve_endpoint_path_entity`` are
+re-exported here from :mod:`superset.versioning.api_helpers` (where
+they live alongside the ``/versions/`` endpoint handlers) so the
+three ``/activity/`` endpoint callers can ``from
+superset.versioning.activity import resolve_endpoint_path_entity``
+without crossing into the ``/versions/`` module name.
+"""
+
+from __future__ import annotations
+
+from superset.versioning.activity.kinds import EntityWindows, Window
+from superset.versioning.activity.orchestrator import (
+ activity_endpoint,
+ ActivityParamsError,
+ get_activity,
+ parse_activity_query_params,
+)
+from superset.versioning.api_helpers import (
+ PathEntityResponseError,
+ resolve_endpoint_path_entity,
+)
+
+__all__: list[str] = [
+ "ActivityParamsError",
+ "EntityWindows",
+ "PathEntityResponseError",
+ "Window",
+ "activity_endpoint",
+ "get_activity",
+ "parse_activity_query_params",
+ "resolve_endpoint_path_entity",
+]
diff --git a/superset/versioning/activity/impact.py b/superset/versioning/activity/impact.py
new file mode 100644
index 00000000000..e4684c20b1a
--- /dev/null
+++ b/superset/versioning/activity/impact.py
@@ -0,0 +1,186 @@
+# 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.
+"""Per-record impact computation for the activity DTO.
+
+Only dashboard-path activity records pointing at a ``SqlaTable``
+related entity carry an ``impact`` field — the number of charts on
+the dashboard at that transaction that were pointing at the dataset.
+This module computes that count in a single batched query per
+request:
+
+* :func:`collect_impact_pairs` — pulls the distinct
+ ``(dataset_id, transaction_id)`` pairs that need counts.
+* :func:`batch_chart_counts` — one SQL query joining
+ ``dashboard_slices_version`` and ``slices_version`` to count
+ the matching charts validity-strategy-style.
+* :func:`impact_for_record` — pure projection from the pre-fetched
+ counts onto each record (returns ``None`` for non-Dashboard paths
+ or non-SqlaTable kinds, matching the ``impact`` computation).
+
+Splitting the count batching from the pure projection keeps the SQL
+inside one function (the batched read) and the per-record decoration
+inside another (no DB).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import sqlalchemy as sa
+
+from superset.extensions import db
+from superset.versioning.activity.kinds import (
+ chunked_ids,
+ ENTITY_ID_CHUNK_SIZE,
+ TABLE_KIND_TO_API,
+)
+
+
+def collect_impact_pairs(
+ records: list[dict[str, Any]], path_kind: str
+) -> set[tuple[int, int]]:
+ """Distinct ``(dataset_id, transaction_id)`` pairs from *records*
+ that require an impact computation.
+
+ Only dashboard-path records whose related entity is a ``SqlaTable``
+ produce a non-null ``impact`` field; for any other shape this set
+ is empty and no DB query needs to fire.
+ """
+ if path_kind != "Dashboard":
+ return set()
+ return {
+ (record["entity_id"], record["transaction_id"])
+ for record in records
+ if TABLE_KIND_TO_API.get(record["entity_kind"]) == "SqlaTable"
+ }
+
+
+def batch_chart_counts(
+ dashboard_id: int, pairs: set[tuple[int, int]]
+) -> dict[tuple[int, int], int]:
+ """For every ``(dataset_id, target_tx)`` in *pairs*, count the
+ distinct charts that were both on *dashboard_id* and pointing at
+ *dataset_id* at *target_tx*.
+
+ One SELECT against ``dashboard_slices_version`` ⨝ ``slices_version``,
+ pulling the (slice, dataset, validity-window) state for every slice
+ ever on the dashboard whose dataset matches one of the requested
+ dataset_ids. The Python loop then applies the validity-strategy
+ predicate per pair. Replaces the previous N+1 shape that fired one
+ COUNT per related record.
+
+ Returns ``{(dataset_id, target_tx): count}``; pairs whose count
+ would be zero are omitted so the caller's ``.get(key, 0)`` is
+ correct.
+ """
+ if not pairs:
+ return {}
+
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ from superset.models.slice import Slice
+
+ metadata = version_class(Slice).__table__.metadata
+ m2m_tbl = metadata.tables.get("dashboard_slices_version")
+ slices_tbl = version_class(Slice).__table__
+ if m2m_tbl is None:
+ return {}
+
+ dataset_ids: set[int] = {dataset_id for dataset_id, _ in pairs}
+ # Bound both validity windows to the transaction range the page-set
+ # needs. Both the attachment (m2m) and the chart→dataset (slice) window
+ # must straddle a requested target_tx, so a row whose window starts
+ # after the newest target, or closes at/before the oldest one, can
+ # never contribute a match. Without this the join multiplies every
+ # attachment row by the full slice version history — an unbounded cross
+ # product on dashboards with long-lived, frequently-edited charts.
+ target_txs: set[int] = {target_tx for _, target_tx in pairs}
+ min_tx, max_tx = min(target_txs), max(target_txs)
+ # Chunk the datasource_id IN-clause to stay under SQLite's bind-variable
+ # floor (a dashboard pointing at very many datasets can exceed it).
+ rows: list[Any] = []
+ for chunk in chunked_ids(dataset_ids, ENTITY_ID_CHUNK_SIZE):
+ stmt = sa.select(
+ m2m_tbl.c.slice_id,
+ slices_tbl.c.datasource_id,
+ m2m_tbl.c.transaction_id.label("m2m_start"),
+ m2m_tbl.c.end_transaction_id.label("m2m_end"),
+ slices_tbl.c.transaction_id.label("slice_start"),
+ slices_tbl.c.end_transaction_id.label("slice_end"),
+ ).where(
+ m2m_tbl.c.dashboard_id == dashboard_id,
+ m2m_tbl.c.operation_type != 2,
+ slices_tbl.c.id == m2m_tbl.c.slice_id,
+ slices_tbl.c.datasource_id.in_(chunk),
+ slices_tbl.c.datasource_type == "table",
+ slices_tbl.c.operation_type != 2,
+ m2m_tbl.c.transaction_id <= max_tx,
+ sa.or_(
+ m2m_tbl.c.end_transaction_id.is_(None),
+ m2m_tbl.c.end_transaction_id > min_tx,
+ ),
+ slices_tbl.c.transaction_id <= max_tx,
+ sa.or_(
+ slices_tbl.c.end_transaction_id.is_(None),
+ slices_tbl.c.end_transaction_id > min_tx,
+ ),
+ )
+ rows.extend(db.session.connection().execute(stmt).mappings().all())
+
+ # For each pair, collect the slice_ids whose two validity windows
+ # both straddle target_tx. ``set`` dedupes within a pair.
+ matches: dict[tuple[int, int], set[int]] = {}
+ pairs_by_dataset: dict[int, list[int]] = {}
+ for dataset_id, target_tx in pairs:
+ pairs_by_dataset.setdefault(dataset_id, []).append(target_tx)
+
+ for row in rows:
+ ds_id = row["datasource_id"]
+ for target_tx in pairs_by_dataset.get(ds_id, ()):
+ in_m2m = row["m2m_start"] <= target_tx and (
+ row["m2m_end"] is None or row["m2m_end"] > target_tx
+ )
+ in_slice = row["slice_start"] <= target_tx and (
+ row["slice_end"] is None or row["slice_end"] > target_tx
+ )
+ if in_m2m and in_slice:
+ matches.setdefault((ds_id, target_tx), set()).add(row["slice_id"])
+
+ return {pair: len(slice_ids) for pair, slice_ids in matches.items()}
+
+
+def impact_for_record(
+ record: dict[str, Any],
+ path_kind: str,
+ counts: dict[tuple[int, int], int],
+) -> dict[str, int] | None:
+ """Synthesize the ``impact`` field for one record using the pre-
+ fetched *counts* mapping. Pure function — no DB.
+
+ For the ``impact`` computation: only
+ ``path=Dashboard`` and ``related=SqlaTable`` shapes carry an
+ impact; everything else returns ``None``.
+ """
+ api_kind = TABLE_KIND_TO_API.get(record["entity_kind"])
+ if path_kind != "Dashboard" or api_kind != "SqlaTable":
+ return None
+ key = (record["entity_id"], record["transaction_id"])
+ chart_count = counts.get(key, 0)
+ if chart_count == 0:
+ return None
+ return {"charts": chart_count}
diff --git a/superset/versioning/activity/kinds.py b/superset/versioning/activity/kinds.py
new file mode 100644
index 00000000000..2770f0434c4
--- /dev/null
+++ b/superset/versioning/activity/kinds.py
@@ -0,0 +1,210 @@
+# 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.
+"""Kind translation tables, shared types, and the shadow-model loader.
+
+The activity-view module operates in two "kind" namespaces — the
+table-stored value (``"chart"`` / ``"dashboard"`` / ``"dataset"``) that
+``version_changes.entity_kind`` carries, and the Python class-name
+form (``"Slice"`` / ``"Dashboard"`` / ``"SqlaTable"``) used internally
+for dispatch and returned in the DTO's ``entity_kind`` field. The four
+mappings here translate between them. Adjacent kind-keyed dicts live
+here too: the per-kind human-readable label, the user-facing
+lowercase form, and the 404 exception class.
+
+The :func:`load_live_model` helper exists in the same module
+because each lookup is keyed on the same set of class names — keeping
+it adjacent to the mappings makes the kind-translation surface
+discoverable at a glance.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Iterator
+from dataclasses import dataclass
+
+from flask_appbuilder import Model
+
+from superset.commands.chart.exceptions import ChartNotFoundError
+from superset.commands.dashboard.exceptions import DashboardNotFoundError
+from superset.commands.dataset.exceptions import DatasetNotFoundError
+from superset.versioning.changes import ENTITY_KIND_BY_CLASS_NAME
+
+# Max entity ids per ``IN (...)`` clause across the activity-view queries.
+# Bounds the bind-parameter count under SQLite's ``SQLITE_MAX_VARIABLE_NUMBER``
+# floor (default 999 in many builds); Postgres/MySQL accept the full list but
+# the chunk is dialect-agnostic. 500 leaves headroom for the other bound
+# params on each statement.
+ENTITY_ID_CHUNK_SIZE = 500
+
+
+def chunked_ids(
+ ids: Iterable[int], size: int = ENTITY_ID_CHUNK_SIZE
+) -> Iterator[list[int]]:
+ """Yield *ids* in fixed-size lists (final chunk may be smaller). Shared by
+ the activity-view query helpers so every ``IN (...)`` stays under the
+ SQLite bind-variable floor."""
+ items = list(ids)
+ for i in range(0, len(items), size):
+ yield items[i : i + size]
+
+
+# ---- Kind translation -----------------------------------------------------
+
+# ``version_changes.entity_kind`` stores the friendly downstream-tooling
+# value (``"chart"``, ``"dashboard"``, ``"dataset"``) per the
+# ``ENTITY_KIND_BY_CLASS_NAME``. The activity-view DTO returns the
+# Python class name instead (``"Slice"``, ``"Dashboard"``,
+# ``"SqlaTable"``) so the contract aligns with ``__class__.__name__``
+# (the ``ActivityRecord`` DTO). Translate at the boundary.
+TABLE_KIND_TO_API: dict[str, str] = {
+ table_kind: class_name
+ for class_name, table_kind in ENTITY_KIND_BY_CLASS_NAME.items()
+}
+API_KIND_TO_TABLE: dict[str, str] = dict(ENTITY_KIND_BY_CLASS_NAME)
+
+# Human-readable label for summary headlines
+# ("Dataset updated: Sales Transactions"). Keyed by the internal API kind
+# (Python class name; matches ``model_cls.__name__``).
+API_KIND_LABEL: dict[str, str] = {
+ "Dashboard": "Dashboard",
+ "Slice": "Chart",
+ "SqlaTable": "Dataset",
+}
+
+# User-facing lowercase rendering of the kind. This is what appears in
+# the JSON response's ``entity_kind`` field and the
+# ``ActivityRecordSchema.entity_kind`` enum. Internal code keeps the
+# Python class-name form because it matches ``model_cls.__name__`` and is
+# convenient for dispatch — translation happens at serialization time
+# only, in :func:`render.apply_record_decoration`.
+USER_FACING_KIND: dict[str, str] = {
+ "Dashboard": "dashboard",
+ "Slice": "chart",
+ "SqlaTable": "dataset",
+}
+
+# 404 exception class per API kind. Each accepts a string positional arg
+# (the path-entity UUID) that gets formatted into the exception message.
+NOT_FOUND_EXC: dict[str, type[Exception]] = {
+ "Dashboard": DashboardNotFoundError,
+ "Slice": ChartNotFoundError,
+ "SqlaTable": DatasetNotFoundError,
+}
+
+# Per-API-kind (model class name, display column) used by
+# ``_resolve_names_for_kind`` to read the user-facing entity name from
+# the shadow table valid at a given transaction.
+NAME_COLUMN: dict[str, tuple[str, str]] = {
+ "Dashboard": ("Dashboard", "dashboard_title"),
+ "Slice": ("Slice", "slice_name"),
+ "SqlaTable": ("SqlaTable", "table_name"),
+}
+
+
+# ---- Types ----------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Window:
+ """A validity window in Continuum transaction-id space, half-open as
+ ``[start_tx, end_tx)``.
+
+ Immutable and equal-by-attributes — two windows with the same
+ ``start_tx`` / ``end_tx`` are interchangeable. Constructor rejects
+ ``end_tx <= start_tx``. ``end_tx = None`` means "open ended
+ (current)" and acts as positive infinity throughout the helpers.
+
+ Helper methods (``contains`` / ``intersect`` / ``merges_with``)
+ live on the type so callers don't re-implement the half-open
+ predicate inline. Previously a ``tuple[int, int | None]`` alias;
+ promoted to a dataclass so a function accepting a ``Window`` can't
+ silently accept any other 2-tuple and so the constructor enforces
+ the half-open invariant.
+ """
+
+ start_tx: int
+ end_tx: int | None
+
+ def __post_init__(self) -> None:
+ if self.end_tx is not None and self.end_tx <= self.start_tx:
+ raise ValueError(
+ f"Window end_tx must be > start_tx; "
+ f"got [{self.start_tx}, {self.end_tx})"
+ )
+
+ def contains(self, tx_id: int) -> bool:
+ """``True`` iff *tx_id* falls inside this half-open interval."""
+ return self.start_tx <= tx_id and (self.end_tx is None or tx_id < self.end_tx)
+
+ def intersect(self, other: Window) -> Window | None:
+ """Return the clipped overlap of this window with *other*, or
+ ``None`` when they are disjoint. ``end_tx = None`` acts as
+ positive infinity on either side."""
+ start = max(self.start_tx, other.start_tx)
+ end: int | None
+ if self.end_tx is None:
+ end = other.end_tx
+ elif other.end_tx is None:
+ end = self.end_tx
+ else:
+ end = min(self.end_tx, other.end_tx)
+ if end is not None and end <= start:
+ return None
+ return Window(start, end)
+
+ def merges_with(self, other: Window) -> bool:
+ """``True`` iff *self* and *other* overlap or touch (so their
+ union is one contiguous window). Assumes the caller has placed
+ them in start-ascending order."""
+ if self.end_tx is None:
+ # self extends to +∞; everything past it merges in.
+ return True
+ return other.start_tx <= self.end_tx
+
+
+#: A related-entity scope row: ``(api_kind, entity_id, [windows])``.
+#: ``api_kind`` is the DTO-facing kind (``"Slice"``, etc.), not the
+#: table-stored kind. Modelled as a tuple alias — the
+#: ``(api_kind, entity_id)`` pair is logically a key with the window
+#: list as its value, so a dict shape may fit better than a flat
+#: dataclass.
+EntityWindows = tuple[str, int, list[Window]]
+
+
+def load_live_model(model_name: str) -> type[Model]:
+ """Inline-import a live model class by name. Deferred until call
+ time because the versioning package is initialised before all model
+ mappers are configured (same idiom used throughout
+ :mod:`superset.versioning.changes`).
+
+ Returns the LIVE model class (``Dashboard`` / ``Slice`` /
+ ``SqlaTable``), not a Continuum shadow class — callers derive the
+ shadow table separately via ``version_class(...)`` where needed."""
+ # pylint: disable=import-outside-toplevel
+ if model_name == "Dashboard":
+ from superset.models.dashboard import Dashboard
+
+ return Dashboard
+ if model_name == "Slice":
+ from superset.models.slice import Slice
+
+ return Slice
+ if model_name == "SqlaTable":
+ from superset.connectors.sqla.models import SqlaTable
+
+ return SqlaTable
+ raise LookupError(f"No live model registered for {model_name!r}")
diff --git a/superset/versioning/activity/orchestrator.py b/superset/versioning/activity/orchestrator.py
new file mode 100644
index 00000000000..1c71def71d4
--- /dev/null
+++ b/superset/versioning/activity/orchestrator.py
@@ -0,0 +1,434 @@
+# 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.
+"""Top-level orchestrator + query-param parsing + observability.
+
+This is the public entry point for the activity-view read path. One
+function — :func:`get_activity` — dispatches on the path entity's
+model class to assemble the cross-entity activity stream:
+
+1. ``resolve_path_entity`` (queries.py) — resolve UUID → live entity.
+2. ``resolve_scope`` (scope.py) — build the related-entity window list.
+3. ``fetch_change_records`` (queries.py) — pull rows from
+ ``version_changes`` joined with ``version_transaction`` and ``ab_user``.
+4. ``filter_records_by_visibility`` (visibility.py) — silent
+ drop of records the requester can't read.
+5. ``apply_entity_name_denormalization`` (queries.py) — resolve entity names
+ from the shadow row valid at each record's transaction_id.
+6. ``apply_record_decoration`` (render.py) — synthesize the ActivityRecord
+ DTO fields and strip internal-only columns.
+7. Paginate in Python over the post-filter list.
+
+Parameter parsing for the REST endpoints lives here too —
+:func:`parse_activity_query_params` is called by the three
+``/activity/`` endpoint handlers before they call ``get_activity``.
+Same for the observability instrumentation: ``_phase_timer`` and
+``_emit_request_shape_attributes`` emit the per-phase timing and
+request-shape metrics, on the same prefix the cross-coupling test pins.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from collections.abc import Iterator
+from datetime import datetime, timezone
+from typing import Any
+from uuid import UUID
+
+from flask import Response
+from flask_appbuilder import Model
+
+from superset.utils import json
+from superset.versioning.activity.kinds import EntityWindows
+from superset.versioning.activity.queries import (
+ apply_entity_name_denormalization,
+ fetch_change_records,
+ first_tracked_tx,
+ mark_first_tracked_saves,
+ resolve_path_entity,
+)
+from superset.versioning.activity.render import apply_record_decoration
+from superset.versioning.activity.scope import resolve_scope
+from superset.versioning.activity.visibility import filter_records_by_visibility
+from superset.versioning.api_helpers import (
+ PathEntityResponseError,
+ resolve_endpoint_path_entity,
+)
+
+_DEFAULT_PAGE_SIZE: int = 25
+_MAX_PAGE_SIZE: int = 200
+_VALID_INCLUDE_VALUES: frozenset[str] = frozenset({"self", "related", "all"})
+
+
+# Upper bound on the ``q`` search string. The search is a substring scan over
+# the (already-capped) materialized record set, so this is a cheap-DoS guard,
+# not a correctness limit.
+_MAX_Q_LENGTH: int = 1024
+
+
+class ActivityParamsError(ValueError):
+ """Raised by :func:`parse_activity_query_params` when a query param is
+ malformed. The endpoint catches this and maps to ``response_400``;
+ no other callers should depend on the exception type."""
+
+
+def parse_activity_query_params(args: Any) -> dict[str, Any]:
+ """Parse the ``since`` / ``until`` / ``include`` / ``page`` / ``page_size``
+ query parameters into the kwargs ``get_activity`` accepts.
+
+ Raises :class:`ActivityParamsError` (subclass of ``ValueError``) when
+ a parameter is malformed. Shared across the three endpoint families
+ (dashboards, charts, datasets) so the parsing and 400-messaging stay
+ consistent.
+ """
+ params: dict[str, Any] = {
+ "include": _parse_include(args.get("include", "all")),
+ "page": _parse_page(args.get("page", "0")),
+ "page_size": _parse_page_size(args.get("page_size")),
+ }
+ if (since := _parse_optional_iso(args.get("since"), name="since")) is not None:
+ params["since"] = since
+ if (until := _parse_optional_iso(args.get("until"), name="until")) is not None:
+ params["until"] = until
+ if q := (args.get("q") or "").strip():
+ if len(q) > _MAX_Q_LENGTH:
+ raise ActivityParamsError(f"'q' must be at most {_MAX_Q_LENGTH} characters")
+ params["q"] = q
+ return params
+
+
+def _parse_optional_iso(raw: str | None, *, name: str) -> datetime | None:
+ """Parse a missing-or-ISO-datetime field; ``None`` for missing,
+ ``ActivityParamsError`` for malformed."""
+ if not raw:
+ return None
+ parsed = _parse_iso_datetime(raw)
+ if parsed is None:
+ raise ActivityParamsError(f"Invalid {name!r} datetime: {raw!r}")
+ return parsed
+
+
+def _parse_include(value: str) -> str:
+ if value not in _VALID_INCLUDE_VALUES:
+ raise ActivityParamsError(
+ f"Invalid 'include' value: {value!r}; "
+ f"must be one of {sorted(_VALID_INCLUDE_VALUES)}"
+ )
+ return value
+
+
+def _parse_page(raw: str) -> int:
+ try:
+ value = int(raw)
+ except (TypeError, ValueError) as exc:
+ raise ActivityParamsError(f"Invalid 'page' value: {raw!r}") from exc
+ if value < 0:
+ raise ActivityParamsError("Invalid 'page' value: must be >= 0")
+ return value
+
+
+def _parse_page_size(raw: str | None) -> int:
+ """``page_size`` honours the default when missing, raises when invalid,
+ and silently clamps to ``_MAX_PAGE_SIZE`` (so ``?page_size=500``
+ returns 200 records instead of a 400)."""
+ if raw is None:
+ return _DEFAULT_PAGE_SIZE
+ try:
+ value = int(raw)
+ except (TypeError, ValueError) as exc:
+ raise ActivityParamsError(f"Invalid 'page_size' value: {raw!r}") from exc
+ if value < 1:
+ raise ActivityParamsError("Invalid 'page_size' value: must be >= 1")
+ return min(value, _MAX_PAGE_SIZE)
+
+
+def _parse_iso_datetime(value: str) -> datetime | None:
+ """Parse an ISO-8601 datetime string. Tolerates the trailing ``Z``
+ suffix that Python <3.11 ``fromisoformat`` rejects, and normalises any
+ timezone-aware result to naive UTC.
+
+ The ``since`` / ``until`` filters bind directly against
+ ``version_transaction.issued_at``, which is ``sa.DateTime()`` — a
+ timezone-*naive* column (UTC by convention). Binding a tz-aware value
+ against it shifts the comparison by the session offset on PostgreSQL
+ (and raises on some drivers), so collapse aware inputs to naive UTC
+ here. Naive inputs pass through unchanged (already treated as UTC).
+ """
+ candidate = value[:-1] + "+00:00" if value.endswith("Z") else value
+ try:
+ parsed = datetime.fromisoformat(candidate)
+ except ValueError:
+ return None
+ if parsed.tzinfo is not None:
+ parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None)
+ return parsed
+
+
+def _record_matches(record: dict[str, Any], q: str) -> bool:
+ """Case-insensitive substring match for the ``q`` search filter,
+ over the human-meaningful surfaces of a decorated activity record:
+ ``summary``, ``entity_name``, ``kind``, the joined ``path`` segments,
+ and the JSON form of ``from_value`` / ``to_value`` (JSON, not Python
+ ``str()``: the client searches the serialized text it renders, so
+ ``false`` / ``null`` / double-quoted keys must match — and falsy
+ values like ``False`` / ``0`` must not collapse to unsearchable
+ empty strings).
+ """
+
+ def _value_text(value: Any) -> str:
+ if value is None:
+ return ""
+ try:
+ return json.dumps(value)
+ except (TypeError, ValueError):
+ return str(value)
+
+ needle = q.lower()
+ haystacks = (
+ record.get("summary") or "",
+ record.get("entity_name") or "",
+ record.get("kind") or "",
+ " ".join(str(seg) for seg in (record.get("path") or [])),
+ _value_text(record.get("from_value")),
+ _value_text(record.get("to_value")),
+ )
+ return any(needle in h.lower() for h in haystacks)
+
+
+def get_activity(
+ model_cls: type[Model],
+ entity_uuid: UUID,
+ *,
+ since: datetime | None = None,
+ until: datetime | None = None,
+ include: str = "all",
+ q: str | None = None,
+ page: int = 0,
+ page_size: int = _DEFAULT_PAGE_SIZE,
+ resolved_entity: Any | None = None,
+) -> tuple[list[dict[str, Any]], int, bool]:
+ """Cross-entity activity stream for one path entity.
+
+ Single polymorphic entry point. Dispatches on *model_cls* to
+ assemble the path entity's self records plus the transitive related-
+ entity records (charts attached to a dashboard, datasets a chart
+ pointed at, etc.).
+
+ Returns ``(records, total_count, truncated)``. ``truncated`` is
+ ``True`` when the per-kind fetch ceiling
+ (``queries._MAX_FETCHED_RECORDS``) bit for any kind — the stream is
+ clamped to a clean time cut and older records exist beyond it, so
+ ``count`` is a floor, not the absolute total.
+
+ *resolved_entity*, when supplied, is the already-resolved live path
+ entity (the endpoint resolves it once via ``resolve_endpoint_path_entity``
+ for the ``raise_for_access`` gate); passing it here skips a second
+ identical ``find_active_by_uuid`` lookup and the TOCTOU window between
+ them. The count is post-visibility (silent visibility filter),
+ post-include-filter, and — when ``q`` is supplied — post-
+ search-filter (``count`` reflects the matches, the contract the
+ server-side search exists to provide), not just the size of the
+ returned slice — clients paginate by passing ``page`` forward until
+ ``page * page_size >= count``.
+
+ Raises ``DashboardNotFoundError`` / ``ChartNotFoundError`` /
+ ``DatasetNotFoundError`` when the path entity doesn't exist.
+ """
+ if resolved_entity is not None:
+ path_entity, path_id = resolved_entity, resolved_entity.id
+ else:
+ path_entity, path_id = resolve_path_entity(model_cls, entity_uuid)
+ path_kind = model_cls.__name__
+ kind_key = path_kind.lower() # "dashboard" / "slice" / "sqlatable"
+
+ # Lower-bound the self window at the entity's first tracked transaction
+ # (matched on (id, uuid)) so a reused integer id can't inherit a
+ # hard-deleted predecessor's history.
+ self_start_tx = first_tracked_tx(model_cls, path_id, path_entity.uuid)
+ with _phase_timer(kind_key, "relationship_resolution_ms"):
+ entity_windows = resolve_scope(path_kind, path_id, include, self_start_tx)
+ if not entity_windows:
+ _emit_request_shape_attributes(
+ kind_key,
+ include=include,
+ has_since_filter=since is not None,
+ page_size=page_size,
+ record_count=0,
+ entity_windows=[],
+ path_kind=path_kind,
+ path_id=path_id,
+ )
+ return [], 0, False
+
+ # Visibility filter runs before decoration: it needs the raw
+ # ``entity_id`` column (which decoration strips), and dropping
+ # invisible records early means we don't pay for name lookup +
+ # tombstone probes + impact counts on records the requester
+ # can't see (the silent-filter contract).
+ with _phase_timer(kind_key, "fetch_ms"):
+ records, truncated = fetch_change_records(entity_windows, since, until)
+ with _phase_timer(kind_key, "visibility_filter_ms"):
+ records = filter_records_by_visibility(records)
+ with _phase_timer(kind_key, "denormalize_ms"):
+ apply_entity_name_denormalization(records)
+ # Runs post-visibility (fewer entities to probe) and pre-
+ # decoration (needs the raw table-form entity_kind/entity_id
+ # that decoration rewrites).
+ mark_first_tracked_saves(records)
+ with _phase_timer(kind_key, "decorate_ms"):
+ apply_record_decoration(records, path_kind, path_id)
+
+ # Server-side search (the panel's client-side
+ # search only covers loaded pages). Applied post-decoration so the
+ # synthesized ``summary`` / ``entity_name`` participate, and pre-
+ # count so pagination paginates the MATCHES — the full record set
+ # is already materialized in Python (the documented design),
+ # so the filter adds no extra query.
+ if q:
+ records = [r for r in records if _record_matches(r, q)]
+
+ total = len(records)
+ bounded_size = max(1, min(page_size, _MAX_PAGE_SIZE))
+ offset = max(0, page) * bounded_size
+
+ _emit_request_shape_attributes(
+ kind_key,
+ include=include,
+ has_since_filter=since is not None,
+ page_size=bounded_size,
+ record_count=total,
+ entity_windows=entity_windows,
+ path_kind=path_kind,
+ path_id=path_id,
+ )
+
+ return records[offset : offset + bounded_size], total, truncated
+
+
+def activity_endpoint(
+ api: Any, model_cls: type[Model], uuid_str: str, request_args: Any
+) -> Response:
+ """Body of ``GET /api/v1/{resource}/<uuid>/activity/``.
+
+ Same shape as :func:`superset.versioning.api_helpers.list_versions_endpoint`
+ for the ``/versions/`` endpoint family. Resolves the path entity,
+ parses the request query params, runs :func:`get_activity`, and
+ wraps the result through ``ActivityResponseSchema``.
+
+ *api* is the FAB ``ModelRestApi`` instance (pass ``self`` from the
+ endpoint method). *request_args* is ``request.args`` from
+ ``flask.request`` — passed explicitly so the helper is testable
+ without a live Flask context.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.versioning.schemas import ActivityResponseSchema
+
+ try:
+ entity, _ = resolve_endpoint_path_entity(api, model_cls, uuid_str)
+ except PathEntityResponseError as exc:
+ return exc.response
+
+ try:
+ params = parse_activity_query_params(request_args)
+ except ActivityParamsError as exc:
+ return api.response_400(message=str(exc))
+
+ records, count, truncated = get_activity(
+ model_cls, entity.uuid, resolved_entity=entity, **params
+ )
+ payload = ActivityResponseSchema().dump(
+ {"result": records, "count": count, "truncated": truncated}
+ )
+ return api.response(200, **payload)
+
+
+# ---- Observability -------------------------------------------------------
+
+#: Common prefix for every metric this module emits.
+_METRIC_PREFIX = "superset.activity_view"
+
+
+@contextlib.contextmanager
+def _phase_timer(kind_key: str, phase: str) -> Iterator[None]:
+ """Time the wrapped block and emit
+ ``superset.activity_view.<kind>.<phase>`` to ``stats_logger_manager``.
+ Wrapper around :func:`superset.utils.decorators.stats_timing` that
+ centralises the key construction.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.extensions import stats_logger_manager
+ from superset.utils.decorators import stats_timing
+
+ with stats_timing(
+ f"{_METRIC_PREFIX}.{kind_key}.{phase}",
+ stats_logger_manager.instance,
+ ):
+ yield
+
+
+def _emit_request_shape_attributes(
+ kind_key: str,
+ *,
+ include: str,
+ has_since_filter: bool,
+ page_size: int,
+ record_count: int,
+ entity_windows: list[EntityWindows],
+ path_kind: str,
+ path_id: int,
+) -> None:
+ """Emit non-PII shape counters about the request and its result set.
+
+ Emits: include_mode / has_since_filter / page_size / record_count
+ + per-related-kind entity counts. **No PII**: entity names, diff
+ content, user identifiers — none of those reach the metric layer.
+ The counters use ``incr`` (counters) since they're tags, not
+ latencies; the timing keys above carry the latency dimension.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.extensions import stats_logger_manager
+
+ sl = stats_logger_manager.instance
+
+ # Tag-style metrics: one counter per attribute value. The statsd
+ # bridge accepts arbitrary strings; downstream dashboards filter by
+ # the value segment.
+ sl.incr(f"{_METRIC_PREFIX}.{kind_key}.requests.include_{include}")
+ sl.incr(
+ f"{_METRIC_PREFIX}.{kind_key}.requests."
+ f"has_since_filter_{'true' if has_since_filter else 'false'}"
+ )
+ sl.gauge(f"{_METRIC_PREFIX}.{kind_key}.page_size", float(page_size))
+ sl.gauge(f"{_METRIC_PREFIX}.{kind_key}.record_count", float(record_count))
+
+ # Per-related-kind entity counts. The scope
+ # list includes the path entity itself (the "self" window); exclude
+ # it so the gauge reflects only the *related* entities the request
+ # fanned out to, not "this request touched itself".
+ by_kind: dict[str, int] = {"Slice": 0, "SqlaTable": 0}
+ for api_kind, entity_id, _windows in entity_windows:
+ if (api_kind, entity_id) == (path_kind, path_id):
+ continue
+ if api_kind in by_kind:
+ by_kind[api_kind] += 1
+ sl.gauge(
+ f"{_METRIC_PREFIX}.{kind_key}.related_entity_count.charts",
+ float(by_kind["Slice"]),
+ )
+ sl.gauge(
+ f"{_METRIC_PREFIX}.{kind_key}.related_entity_count.datasets",
+ float(by_kind["SqlaTable"]),
+ )
diff --git a/superset/versioning/activity/queries.py b/superset/versioning/activity/queries.py
new file mode 100644
index 00000000000..548815bbb1d
--- /dev/null
+++ b/superset/versioning/activity/queries.py
@@ -0,0 +1,870 @@
+# 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.
+"""DB-touching helpers for the activity-view read path.
+
+All Phase A relationship walks (``charts_attached_to_dashboard``,
+``datasets_used_by_chart``, ``batch_datasets_used_by_charts``),
+the Phase B change-record fetch (``fetch_change_records`` /
+``_select_change_rows_for_kinds``), the name-denormalization helpers
+(``_resolve_names_for_kind`` / ``apply_entity_name_denormalization``), the
+path-entity resolution helper (``resolve_path_entity``), and the
+tombstone-state lookup (``check_entity_tombstones``) live here.
+
+Each helper is a thin SELECT-and-shape function — no orchestration,
+no business logic. Callers in :mod:`scope`, :mod:`render`, and
+:mod:`orchestrator` compose them into the end-to-end request.
+
+**Inline imports.** Continuum's ``version_class`` / ``versioning_manager``
+and the Superset model classes are imported inside each helper because
+this package is loaded from ``init_versioning()`` before all SQLAlchemy
+mappers are configured.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime
+from heapq import heappush, heapreplace
+from typing import Any
+from uuid import UUID
+
+import sqlalchemy as sa
+from flask_appbuilder import Model
+
+from superset.extensions import db
+from superset.versioning.activity.kinds import (
+ API_KIND_TO_TABLE,
+ chunked_ids,
+ EntityWindows,
+ load_live_model,
+ NAME_COLUMN,
+ NOT_FOUND_EXC,
+ TABLE_KIND_TO_API,
+ Window,
+)
+from superset.versioning.activity.windows import row_within_any_window
+from superset.versioning.changes import version_changes_table
+
+logger = logging.getLogger(__name__)
+
+RecordSortKey = tuple[datetime, int, int, str, int]
+BoundedRecordHeap = list[tuple[RecordSortKey, int, dict[str, Any]]]
+
+# ---- Path-entity resolution -----------------------------------------------
+
+
+def resolve_path_entity(model_cls: type[Model], entity_uuid: UUID) -> tuple[Any, int]:
+ """Resolve *entity_uuid* to ``(live_entity, entity_id)`` or raise a
+ typed 404.
+
+ Soft-delete handling is inherited transparently from
+ :func:`superset.versioning.queries.find_active_by_uuid` once it
+ learns to filter out ``deleted_at IS NOT NULL`` rows; at that point
+ soft-deleted paths will also raise here.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.versioning.queries import find_active_by_uuid
+
+ entity = find_active_by_uuid(model_cls, entity_uuid)
+ if entity is None:
+ api_kind = model_cls.__name__
+ exc_cls = NOT_FOUND_EXC.get(api_kind)
+ if exc_cls is None:
+ raise LookupError(
+ f"Activity view does not support model class {api_kind!r}"
+ )
+ raise exc_cls(str(entity_uuid))
+ return entity, entity.id
+
+
+def first_tracked_tx(
+ model_cls: type[Model], entity_id: int, entity_uuid: UUID
+) -> int | None:
+ """Return the earliest Continuum transaction_id of the shadow rows
+ that belong to *this* live entity, matched on ``(id, uuid)``; ``None``
+ when the entity has no tracked history yet.
+
+ Used to lower-bound the self-scope window. Matching on the integer
+ ``id`` alone would inherit a previously hard-deleted entity's history
+ under id reuse (SQLite/MySQL reuse ``max(id)+1``); pinning the uuid
+ too — the same discrimination :func:`mark_first_tracked_saves` uses —
+ scopes the window to the current entity's own transactions.
+ """
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ shadow_tbl = version_class(model_cls).__table__
+ stmt = sa.select(sa.func.min(shadow_tbl.c.transaction_id)).where(
+ shadow_tbl.c.id == entity_id,
+ shadow_tbl.c.uuid == entity_uuid,
+ )
+ return db.session.connection().execute(stmt).scalar()
+
+
+# ---- Phase A: relationship-traversal queries ------------------------------
+
+
+def charts_attached_to_dashboard(dashboard_id: int) -> list[tuple[int, Window]]:
+ """Return ``(slice_id, window)`` for every chart that has ever been on
+ *dashboard_id*, with each association's validity window in
+ transaction-id space.
+
+ Reads from ``dashboard_slices_version`` (Continuum's auto-generated
+ M2M shadow). Rows with ``operation_type = 2`` (DELETE) are excluded
+ so we don't synthesize a phantom window from a detachment row.
+ """
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ from superset.models.dashboard import Dashboard
+
+ metadata = version_class(Dashboard).__table__.metadata
+ m2m_tbl = metadata.tables.get("dashboard_slices_version")
+ if m2m_tbl is None:
+ return []
+
+ rows = (
+ db.session.connection()
+ .execute(
+ sa.select(
+ m2m_tbl.c.slice_id,
+ m2m_tbl.c.transaction_id,
+ m2m_tbl.c.end_transaction_id,
+ ).where(
+ m2m_tbl.c.dashboard_id == dashboard_id,
+ m2m_tbl.c.operation_type != 2,
+ m2m_tbl.c.slice_id.is_not(None),
+ )
+ )
+ .all()
+ )
+ result: list[tuple[int, Window]] = []
+ for row in rows:
+ try:
+ window = Window(row[1], row[2])
+ except ValueError:
+ # A degenerate shadow row (end_tx <= start_tx) must not 500 the
+ # endpoint; skip it and leave a breadcrumb for investigation.
+ logger.warning(
+ "activity: skipping degenerate dashboard_slices_version row "
+ "(dashboard_id=%s, slice_id=%s, tx=%s, end_tx=%s)",
+ dashboard_id,
+ row[0],
+ row[1],
+ row[2],
+ )
+ continue
+ result.append((row[0], window))
+ return result
+
+
+def datasets_used_by_chart(slice_id: int) -> list[tuple[int, Window]]:
+ """Return ``(datasource_id, window)`` for every dataset that *slice_id*
+ has ever pointed at, with each association's validity window.
+
+ Single-slice form, used by ``_resolve_chart_scope`` where there
+ is only one chart to walk. The dashboard-scope path calls
+ :func:`batch_datasets_used_by_charts` instead so the query fires
+ once for all slices on the dashboard, not once per slice.
+
+ Reads from ``slices_version`` (the chart parent shadow). Filters to
+ ``datasource_type = 'table'`` because the activity view only follows
+ the chart → ``SqlaTable`` dependency edge (not legacy/other
+ datasources). Rows with ``operation_type = 2`` are excluded.
+ """
+ return batch_datasets_used_by_charts({slice_id}).get(slice_id, [])
+
+
+def batch_datasets_used_by_charts(
+ slice_ids: set[int],
+) -> dict[int, list[tuple[int, Window]]]:
+ """Batch form of :func:`datasets_used_by_chart`. Returns
+ ``{slice_id: [(dataset_id, window), ...]}`` in a single query so the
+ dashboard-scope walker doesn't fire one query per chart on the
+ dashboard. The previous per-slice shape became O(n_charts) round-
+ trips, which dominated ``get_activity`` latency on dashboards with
+ rich history (profiling showed `resolve_scope`
+ accounting for ~1.9s out of 4s p95).
+ """
+ if not slice_ids:
+ return {}
+
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ from superset.models.slice import Slice
+
+ slices_tbl = version_class(Slice).__table__
+ grouped: dict[int, list[tuple[int, Window]]] = {}
+ # Chunk the IN-clause under SQLite's bind-variable floor (a dashboard can
+ # carry more charts than the floor allows in one statement).
+ rows: list[Any] = []
+ for chunk in chunked_ids(slice_ids):
+ rows.extend(
+ db.session.connection()
+ .execute(
+ sa.select(
+ slices_tbl.c.id,
+ slices_tbl.c.datasource_id,
+ slices_tbl.c.transaction_id,
+ slices_tbl.c.end_transaction_id,
+ ).where(
+ slices_tbl.c.id.in_(chunk),
+ slices_tbl.c.datasource_type == "table",
+ slices_tbl.c.operation_type != 2,
+ slices_tbl.c.datasource_id.is_not(None),
+ )
+ )
+ .mappings()
+ .all()
+ )
+ for row in rows:
+ try:
+ window = Window(row["transaction_id"], row["end_transaction_id"])
+ except ValueError:
+ # A degenerate shadow row (end_tx <= start_tx) must not 500 the
+ # endpoint; skip it and leave a breadcrumb for investigation.
+ logger.warning(
+ "activity: skipping degenerate slices_version row "
+ "(slice_id=%s, datasource_id=%s, tx=%s, end_tx=%s)",
+ row["id"],
+ row["datasource_id"],
+ row["transaction_id"],
+ row["end_transaction_id"],
+ )
+ continue
+ grouped.setdefault(row["id"], []).append((row["datasource_id"], window))
+ return grouped
+
+
+# ---- Phase B: change-record fetch -----------------------------------------
+
+
+def fetch_change_records(
+ entity_window_tuples: list[EntityWindows],
+ since: datetime | None,
+ until: datetime | None,
+) -> tuple[list[dict[str, Any]], bool]:
+ """Fetch all ``version_changes`` rows matching any of the supplied
+ entity-window tuples, joined with ``version_transaction`` for
+ ``issued_at`` and ``user_id``.
+
+ Each tuple is ``(api_kind, entity_id, [(start_tx, end_tx), ...])``;
+ a record matches when ``entity_kind`` equals the table-stored form
+ of *api_kind*, ``entity_id`` matches, and ``transaction_id`` falls
+ inside at least one of the entity's windows. ``since``/``until``
+ further restrict by ``issued_at``.
+
+ Implementation: one SELECT per kind with ``entity_id IN (...)`` and
+ a wide ``transaction_id`` bound (the union of all windows for that
+ kind). Per-window precision is applied in Python afterward. This
+ keeps the SQL shape proportional to the number of *kinds* (≤3) and
+ the bound proportional to the union of windows, not the cross-
+ product of (entity, window) — which previously generated one OR
+ clause per (entity, window) pair and hit SQLite's
+ ``SQLITE_MAX_EXPR_DEPTH`` limit on dashboards with many slices
+ or many historical attachment windows.
+
+ The visibility filter runs after this function (records
+ the requester can't read are silently dropped and must not
+ contribute to ``count``), so the orchestrator paginates in Python
+ over the filtered list — there is no DB-level page ``OFFSET`` here.
+ There IS a per-kind safety ceiling (``_MAX_FETCHED_RECORDS``) that
+ bounds how much history a single request materializes (to at most
+ ``n_kinds * _MAX_FETCHED_RECORDS``); when a kind exhausts it, the
+ second return value is ``True``, the returned stream is clamped to a
+ clean total-order cut (records below the highest per-kind fetch floor
+ are dropped so truncation does not create per-kind holes), and the caller
+ surfaces ``truncated`` on the response.
+
+ Returns ``(records, truncated)``. Records are ordered by
+ ``(issued_at DESC, transaction_id DESC, sequence DESC)`` — the
+ secondary keys break ties for the stable-ordering contract.
+ """
+ if not entity_window_tuples:
+ return [], False
+
+ # Group windows by (table_kind, entity_id) and by table_kind for SQL
+ # narrowing. The fetch is per-kind; the post-filter is per-entity.
+ windows_by_entity: dict[tuple[str, int], list[Window]] = {}
+ ids_by_kind: dict[str, set[int]] = {}
+ for api_kind, entity_id, windows in entity_window_tuples:
+ table_kind = API_KIND_TO_TABLE.get(api_kind)
+ if table_kind is None or not windows:
+ continue
+ ids_by_kind.setdefault(table_kind, set()).add(entity_id)
+ windows_by_entity.setdefault((table_kind, entity_id), []).extend(windows)
+
+ if not ids_by_kind:
+ return [], False
+
+ # Per-kind transaction_id bounds = the union of that kind's windows.
+ # Pushing these into the SQL WHERE ensures the per-statement LIMIT
+ # selects from IN-WINDOW rows. Without it, a related entity whose
+ # association window is far in the past would have the newest ``limit``
+ # (out-of-window) rows fetched and discarded, silently dropping its
+ # in-window records that lie beyond the limit. ``end_tx = None``
+ # (open-ended/current) means no upper bound for that kind.
+ bounds_by_kind: dict[str, tuple[int, int | None]] = {}
+ for (table_kind, _entity_id), windows in windows_by_entity.items():
+ for w in windows:
+ cur = bounds_by_kind.get(table_kind)
+ if cur is None:
+ bounds_by_kind[table_kind] = (w.start_tx, w.end_tx)
+ continue
+ lo = min(cur[0], w.start_tx)
+ hi = None if (cur[1] is None or w.end_tx is None) else max(cur[1], w.end_tx)
+ bounds_by_kind[table_kind] = (lo, hi)
+
+ rows, truncated, truncation_floor = _select_change_rows_for_kinds(
+ ids_by_kind,
+ bounds_by_kind,
+ windows_by_entity,
+ since,
+ until,
+ _MAX_FETCHED_RECORDS,
+ )
+ filtered = rows
+ if truncated and truncation_floor is not None:
+ # Collapse truncation to a clean cut in the same TOTAL order used by
+ # pagination. Below the highest per-kind fetch floor at least one kind
+ # is missing rows, so surfacing other kinds there would present an
+ # incomplete picture. A timestamp-only cut is insufficient because
+ # several transactions/records can share one issued_at instant.
+ filtered = [
+ row for row in filtered if _record_sort_key(row) >= truncation_floor
+ ]
+ # Sort key must be TOTAL so pagination is stable across requests: two
+ # records from different entities can share (issued_at, transaction_id,
+ # sequence), so append (entity_kind, entity_id) to break remaining ties
+ # deterministically. Without these the relative order of tied records
+ # depends on set-iteration order and a record could shift pages.
+ filtered.sort(
+ key=_record_sort_key,
+ reverse=True,
+ )
+ return filtered, truncated
+
+
+def _select_change_rows_for_kinds(
+ ids_by_kind: dict[str, set[int]],
+ bounds_by_kind: dict[str, tuple[int, int | None]],
+ windows_by_entity: dict[tuple[str, int], list[Window]],
+ since: datetime | None,
+ until: datetime | None,
+ limit: int,
+) -> tuple[list[dict[str, Any]], bool, RecordSortKey | None]:
+ """Fetch bounded candidates per entity kind and ID chunk.
+
+ Each SELECT uses ``entity_id IN (...)`` and joins ``version_transaction``
+ + ``ab_user`` so the orchestrator has the columns it needs for
+ decoration.
+
+ Per-kind, not one query: SQLAlchemy's ``tuple_(entity_kind,
+ entity_id).in_(...)`` would collapse the three queries into one,
+ but its SQL emission is not portable across Postgres, MySQL, and
+ SQLite. The per-kind shape is the correct trade-off given
+ Superset's multi-dialect requirement (at most 3 round-trips per
+ request, bounded by the kind taxonomy). Do not "optimise" into a
+ composite-tuple IN clause without verifying the SQL on all three
+ dialects.
+
+ **Init-order dependency.** ``tx_tbl.c.action_kind`` resolves only
+ after ``init_versioning()`` has run — the column is appended onto
+ Continuum's transaction Table by
+ ``superset.versioning.factory.VersionTransactionFactory`` at app
+ start via ``append_column`` + ``add_property``. This helper is
+ safe to call from request-path code because the app is fully
+ initialised by then; calling it from a script that imports the
+ versioning package without going through ``init_versioning()``
+ will raise ``AttributeError`` on the ``action_kind`` attribute
+ access below."""
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import versioning_manager
+
+ from superset import security_manager
+
+ tx_tbl = versioning_manager.transaction_cls.__table__
+ user_tbl = security_manager.user_model.__table__
+ vc = version_changes_table
+ join_tree = vc.join(tx_tbl, vc.c.transaction_id == tx_tbl.c.id).outerjoin(
+ user_tbl, tx_tbl.c.user_id == user_tbl.c.id
+ )
+ select_cols = (
+ vc.c.transaction_id,
+ vc.c.entity_kind,
+ vc.c.entity_id,
+ vc.c.sequence,
+ vc.c.kind,
+ vc.c.operation,
+ vc.c.path,
+ vc.c.from_value,
+ vc.c.to_value,
+ tx_tbl.c.issued_at,
+ tx_tbl.c.user_id,
+ # ``action_kind`` is the high-level avenue (restore / import /
+ # clone / NULL=ordinary save) stamped by the originating
+ # command via the change-record listener. All records sharing a
+ # ``transaction_id`` share the same value. The column is
+ # declared on the Continuum Table by ``VersionTransactionFactory``,
+ # so ``tx_tbl.c.action_kind`` resolves cleanly here. See
+ # the three change-record dimensions.
+ tx_tbl.c.action_kind,
+ user_tbl.c.id.label("changed_by_id"),
+ user_tbl.c.first_name,
+ user_tbl.c.last_name,
+ )
+
+ out: list[dict[str, Any]] = []
+ truncated = False
+ truncation_floors: list[RecordSortKey] = []
+ for table_kind, entity_ids in ids_by_kind.items():
+ # Keep the global newest ``limit + 1`` rows for this kind in a
+ # min-heap. Every id chunk is queried, so an arbitrary early chunk
+ # cannot consume the budget and hide newer rows from a later chunk.
+ # Each chunk stops after its own newest ``limit + 1`` exact-window
+ # matches: anything below that point already has ``limit + 1`` rows
+ # from the same chunk ahead of it and therefore cannot enter the
+ # global top ``limit + 1``.
+ kind_heap: BoundedRecordHeap = []
+ ordinal = 0
+ for chunk in chunked_ids(sorted(entity_ids)):
+ stmt = (
+ sa.select(*select_cols)
+ .select_from(join_tree)
+ .where(
+ vc.c.entity_kind == table_kind,
+ vc.c.entity_id.in_(chunk),
+ )
+ )
+ # Bound by the kind's window union so the LIMIT picks in-window
+ # rows (see fetch_change_records). The per-entity window filter
+ # still runs in Python afterwards for exact membership.
+ tx_lo, tx_hi = bounds_by_kind[table_kind]
+ stmt = stmt.where(vc.c.transaction_id >= tx_lo)
+ if tx_hi is not None:
+ stmt = stmt.where(vc.c.transaction_id < tx_hi)
+ if since is not None:
+ stmt = stmt.where(tx_tbl.c.issued_at >= since)
+ if until is not None:
+ stmt = stmt.where(tx_tbl.c.issued_at < until)
+ # Match fetch_change_records' final Python sort key order.
+ # entity_kind is constant within a per-kind statement.
+ stmt = stmt.order_by(
+ tx_tbl.c.issued_at.desc(),
+ vc.c.transaction_id.desc(),
+ vc.c.sequence.desc(),
+ vc.c.entity_id.desc(),
+ )
+ result = (
+ db.session.connection()
+ .execution_options(stream_results=True)
+ .execute(stmt)
+ .mappings()
+ )
+ ordinal = _merge_result_into_heap(
+ result, kind_heap, windows_by_entity, limit, ordinal
+ )
+
+ if len(kind_heap) > limit:
+ truncated = True
+ # Remove the oldest extra probe row. The oldest retained key is
+ # the complete boundary for this kind.
+ kind_heap.sort(key=lambda entry: entry[0], reverse=True)
+ kind_heap = kind_heap[:limit]
+ truncation_floors.append(kind_heap[-1][0])
+ kind_rows = [entry[2] for entry in kind_heap]
+ out.extend(kind_rows)
+ truncation_floor = max(truncation_floors) if truncation_floors else None
+ return out, truncated, truncation_floor
+
+
+def _record_sort_key(record: dict[str, Any]) -> RecordSortKey:
+ """Return the total newest-first activity ordering key."""
+ return (
+ record["issued_at"],
+ record["transaction_id"],
+ record["sequence"],
+ record["entity_kind"],
+ record["entity_id"],
+ )
+
+
+def _merge_result_into_heap(
+ result: Any,
+ heap: BoundedRecordHeap,
+ windows_by_entity: dict[tuple[str, int], list[Window]],
+ limit: int,
+ ordinal: int,
+) -> int:
+ """Merge one ordered id-chunk result into a bounded per-kind heap."""
+ chunk_matches = 0
+ try:
+ for mapping in result:
+ row = dict(mapping)
+ windows = windows_by_entity.get((row["entity_kind"], row["entity_id"]), [])
+ if not row_within_any_window(row, windows):
+ continue
+ key = _record_sort_key(row)
+ entry = (key, ordinal, row)
+ ordinal += 1
+ if len(heap) < limit + 1:
+ heappush(heap, entry)
+ elif key > heap[0][0]:
+ heapreplace(heap, entry)
+ chunk_matches += 1
+ if chunk_matches >= limit + 1:
+ break
+ finally:
+ result.close()
+ return ordinal
+
+
+# Per-KIND safety ceiling on how many change rows a single activity request
+# will retain for one entity kind (shared across that kind's id-chunks).
+# Bounds application memory for a path entity with very long history or many
+# related entities to <= n_kinds * (_MAX_FETCHED_RECORDS + 1) per request.
+# When a kind exhausts its budget the response is flagged ``truncated`` and
+# the returned stream is clamped to a clean total-order cut.
+_MAX_FETCHED_RECORDS: int = 5000
+
+
+def mark_first_tracked_saves(records: list[dict[str, Any]]) -> None:
+ """Set ``first_tracked_save`` on each record in place: ``True`` when
+ the record's transaction is the entity's FIRST UPDATE (op=1) in its
+ shadow table.
+
+ The first save of an entity that predates versioning replays every
+ params-normalization delta against the retroactive baseline — a
+ legacy chart's first Explore save produced ~74 records in one
+ transaction (version-history UI feedback). The server
+ can't distinguish "normalization" from "the user changed 74 things",
+ but it CAN say "this was the entity's first tracked save"; clients
+ use the marker to collapse such transactions.
+
+ One ``GROUP BY`` query per kind (≤3), chunked like the record fetch.
+ Shadow rows are matched on ``(id, uuid)`` against the live row — a
+ bare ``id`` match would inherit a previously hard-deleted entity's
+ history under id reuse (SQLite/MySQL reuse ``max(id)+1``) and mark
+ the wrong transaction. Consequence: hard-deleted entities (no live
+ row) and NULL-uuid shadow rows never get a ``True`` marker — their
+ records always carry ``first_tracked_save=False``. Mutates *records*
+ in place — same contract as the other decoration passes in
+ :mod:`superset.versioning.activity.render`.
+ """
+ if not records:
+ return
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ ids_by_kind: dict[str, set[int]] = {}
+ for r in records:
+ ids_by_kind.setdefault(r["entity_kind"], set()).add(r["entity_id"])
+
+ first_tx_by_entity: dict[tuple[str, int], int] = {}
+ for table_kind, entity_ids in ids_by_kind.items():
+ model_name = TABLE_KIND_TO_API.get(table_kind)
+ if model_name is None:
+ continue
+ live_model = load_live_model(model_name)
+ live_tbl = live_model.__table__
+ shadow_tbl = version_class(live_model).__table__
+ for chunk in chunked_ids(entity_ids):
+ stmt = (
+ sa.select(
+ shadow_tbl.c.id,
+ sa.func.min(shadow_tbl.c.transaction_id),
+ )
+ .select_from(
+ shadow_tbl.join(
+ live_tbl,
+ sa.and_(
+ shadow_tbl.c.id == live_tbl.c.id,
+ shadow_tbl.c.uuid == live_tbl.c.uuid,
+ ),
+ )
+ )
+ .where(
+ shadow_tbl.c.operation_type == 1,
+ shadow_tbl.c.id.in_(chunk),
+ )
+ .group_by(shadow_tbl.c.id)
+ )
+ for entity_id, min_tx in db.session.connection().execute(stmt):
+ first_tx_by_entity[(table_kind, entity_id)] = min_tx
+
+ for r in records:
+ r["first_tracked_save"] = (
+ first_tx_by_entity.get((r["entity_kind"], r["entity_id"]))
+ == r["transaction_id"]
+ )
+
+
+# ---- Name denormalization -------------------------------------------------
+
+
+def _resolve_names_for_kind(
+ api_kind: str, pairs: set[tuple[int, int]]
+) -> dict[tuple[int, int], str]:
+ """For one entity kind, return ``{(entity_id, target_tx): name}`` from
+ the shadow row valid at *target_tx* (validity-strategy predicate).
+ Empty mapping when the kind has no name column registered.
+ """
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ if api_kind not in NAME_COLUMN or not pairs:
+ return {}
+
+ model_name, name_col = NAME_COLUMN[api_kind]
+ model_cls = load_live_model(model_name)
+ shadow_tbl = version_class(model_cls).__table__
+ ids = {eid for eid, _ in pairs}
+ # Bound the scan to the transaction range the page-set actually needs.
+ # A row valid at some target_tx must start at/before the newest target
+ # and stay open past the oldest one, so rows outside
+ # ``[min_target_tx, max_target_tx]`` can never win the validity match.
+ # Without this bound the query loads every historical version row of
+ # every referenced entity — an entity with thousands of versions would
+ # defeat the memory ceiling the change-record fetch enforces.
+ target_txs = {target_tx for _, target_tx in pairs}
+ min_tx, max_tx = min(target_txs), max(target_txs)
+ per_entity: dict[int, list[tuple[int, int | None, Any]]] = {}
+ # Chunk the IN-clause to stay under SQLite's bind-variable floor (the
+ # same reason _select_change_rows_for_kinds chunks).
+ for chunk in chunked_ids(ids):
+ rows = (
+ db.session.connection()
+ .execute(
+ sa.select(
+ shadow_tbl.c.id,
+ shadow_tbl.c.transaction_id,
+ shadow_tbl.c.end_transaction_id,
+ shadow_tbl.c[name_col],
+ ).where(
+ shadow_tbl.c.id.in_(chunk),
+ shadow_tbl.c.transaction_id <= max_tx,
+ sa.or_(
+ shadow_tbl.c.end_transaction_id.is_(None),
+ shadow_tbl.c.end_transaction_id > min_tx,
+ ),
+ )
+ )
+ .all()
+ )
+ for row in rows:
+ per_entity.setdefault(row[0], []).append((row[1], row[2], row[3]))
+
+ resolved: dict[tuple[int, int], str] = {}
+ for entity_id, target_tx in pairs:
+ for start_tx, end_tx, name in per_entity.get(entity_id, []):
+ if start_tx <= target_tx and (end_tx is None or end_tx > target_tx):
+ # Coerce a NULL name (e.g. a DELETE shadow row winning the
+ # validity match) to "" so entity_name is never None.
+ resolved[(entity_id, target_tx)] = name if name is not None else ""
+ break
+ return resolved
+
+
+def _resolve_uuids_for_kind(
+ api_kind: str, pairs: set[tuple[int, int]]
+) -> dict[tuple[int, int], UUID]:
+ """Resolve the entity UUID valid at each target transaction."""
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ if api_kind not in NAME_COLUMN or not pairs:
+ return {}
+
+ model_cls = load_live_model(NAME_COLUMN[api_kind][0])
+ shadow_tbl = version_class(model_cls).__table__
+ ids = {entity_id for entity_id, _ in pairs}
+ target_txs = {target_tx for _, target_tx in pairs}
+ min_tx, max_tx = min(target_txs), max(target_txs)
+ per_entity: dict[int, list[tuple[int, int | None, UUID | None]]] = {}
+ for chunk in chunked_ids(ids):
+ rows = (
+ db.session.connection()
+ .execute(
+ sa.select(
+ shadow_tbl.c.id,
+ shadow_tbl.c.transaction_id,
+ shadow_tbl.c.end_transaction_id,
+ shadow_tbl.c.uuid,
+ ).where(
+ shadow_tbl.c.id.in_(chunk),
+ shadow_tbl.c.transaction_id <= max_tx,
+ sa.or_(
+ shadow_tbl.c.end_transaction_id.is_(None),
+ shadow_tbl.c.end_transaction_id > min_tx,
+ ),
+ )
+ )
+ .all()
+ )
+ for row in rows:
+ per_entity.setdefault(row[0], []).append((row[1], row[2], row[3]))
+
+ resolved: dict[tuple[int, int], UUID] = {}
+ for entity_id, target_tx in pairs:
+ for start_tx, end_tx, entity_uuid in per_entity.get(entity_id, []):
+ if (
+ entity_uuid is not None
+ and start_tx <= target_tx
+ and (end_tx is None or end_tx > target_tx)
+ ):
+ resolved[(entity_id, target_tx)] = entity_uuid
+ break
+ return resolved
+
+
+def resolve_historical_entity_uuids(
+ records: list[dict[str, Any]],
+) -> dict[tuple[str, int, int], UUID]:
+ """Return UUIDs keyed by API kind, entity id, and record transaction."""
+ needed_by_kind: dict[str, set[tuple[int, int]]] = {}
+ for record in records:
+ api_kind = TABLE_KIND_TO_API.get(record["entity_kind"])
+ if api_kind is None:
+ continue
+ needed_by_kind.setdefault(api_kind, set()).add(
+ (record["entity_id"], record["transaction_id"])
+ )
+
+ resolved: dict[tuple[str, int, int], UUID] = {}
+ for api_kind, pairs in needed_by_kind.items():
+ for (entity_id, target_tx), entity_uuid in _resolve_uuids_for_kind(
+ api_kind, pairs
+ ).items():
+ resolved[(api_kind, entity_id, target_tx)] = entity_uuid
+ return resolved
+
+
+def apply_entity_name_denormalization(records: list[dict[str, Any]]) -> None:
+ """Resolve each record's ``entity_name`` from the shadow row valid at
+ its ``transaction_id``. Adds an ``entity_name`` key to every record
+ in place; returns ``None``.
+
+ The lookup is per (table-stored ``entity_kind``, ``entity_id``,
+ ``transaction_id``) triple. One ``IN``-clause query per kind keeps
+ round-trips bounded by the number of distinct kinds (≤3) regardless
+ of result-set size. The in-place mutation avoids re-allocating
+ thousands of dicts on hot dashboards; the name + return signature
+ make the side effect explicit instead of pretending to be a pure
+ projection.
+ """
+ if not records:
+ return
+
+ needed_by_kind: dict[str, set[tuple[int, int]]] = {}
+ for record in records:
+ api_kind = TABLE_KIND_TO_API.get(record["entity_kind"])
+ if api_kind is None or api_kind not in NAME_COLUMN:
+ continue
+ needed_by_kind.setdefault(api_kind, set()).add(
+ (record["entity_id"], record["transaction_id"])
+ )
+
+ resolved: dict[tuple[str, int, int], str] = {}
+ for api_kind, pairs in needed_by_kind.items():
+ for (entity_id, target_tx), name in _resolve_names_for_kind(
+ api_kind, pairs
+ ).items():
+ resolved[(api_kind, entity_id, target_tx)] = name
+
+ for record in records:
+ api_kind_for_record = TABLE_KIND_TO_API.get(record["entity_kind"], "")
+ key = (api_kind_for_record, record["entity_id"], record["transaction_id"])
+ record["entity_name"] = resolved.get(key, "")
+
+
+# ---- Live-row existence + soft-delete state -------------------------------
+
+
+def check_entity_tombstones(
+ distinct_entities: set[tuple[str, int]],
+) -> dict[tuple[str, int], dict[str, Any]]:
+ """For each ``(api_kind, entity_id)``, report ``deleted`` (no live
+ row) and ``deletion_state`` (``"soft_deleted"`` iff the live row has
+ a non-null ``deleted_at``, else ``None``).
+
+ The ``deleted_at`` column is probed for at runtime: when the model
+ classes don't have one, entities are reported as never soft-deleted
+ (``deletion_state=None``); when a ``deleted_at`` column exists, this
+ helper picks it up automatically.
+ """
+ result: dict[tuple[str, int], dict[str, Any]] = {}
+ if not distinct_entities:
+ return result
+
+ by_kind: dict[str, list[int]] = {}
+ for api_kind, entity_id in distinct_entities:
+ by_kind.setdefault(api_kind, []).append(entity_id)
+
+ # ``no_autoflush`` mirrors the defensive posture of the listener-
+ # side reads. Today's callers run from request-path code with no
+ # pending writes; a future caller that probes tombstones before a
+ # flush would otherwise trigger autoflush mid-read.
+ with db.session.no_autoflush:
+ for api_kind, entity_ids in by_kind.items():
+ for entity_id, state in _tombstone_states_for_kind(
+ api_kind, entity_ids
+ ).items():
+ result[(api_kind, entity_id)] = state
+ return result
+
+
+_TOMBSTONE: dict[str, Any] = {"deleted": True, "deletion_state": None}
+
+
+def _tombstone_states_for_kind(
+ api_kind: str, entity_ids: list[int]
+) -> dict[int, dict[str, Any]]:
+ """Resolve ``{entity_id: {deleted, deletion_state}}`` for one kind.
+
+ Kinds outside the change-record taxonomy report as tombstoned. For a
+ known kind, an id with no live row is tombstoned; a live row with a
+ non-null ``deleted_at`` (when the column exists) is ``soft_deleted``.
+ """
+ if api_kind not in NAME_COLUMN:
+ return {entity_id: dict(_TOMBSTONE) for entity_id in entity_ids}
+
+ model_cls = load_live_model(NAME_COLUMN[api_kind][0])
+ live_tbl = model_cls.__table__
+ has_deleted_at = "deleted_at" in live_tbl.c
+ cols = [live_tbl.c.id] + ([live_tbl.c.deleted_at] if has_deleted_at else [])
+
+ live: dict[int, Any] = {}
+ # Chunk the IN-clause to stay under SQLite's bind-variable floor.
+ for chunk in chunked_ids(entity_ids):
+ for row in (
+ db.session.connection()
+ .execute(sa.select(*cols).where(live_tbl.c.id.in_(chunk)))
+ .all()
+ ):
+ live[row[0]] = row[1] if has_deleted_at else None
+
+ states: dict[int, dict[str, Any]] = {}
+ for entity_id in entity_ids:
+ if entity_id not in live:
+ states[entity_id] = dict(_TOMBSTONE)
+ else:
+ states[entity_id] = {
+ "deleted": False,
+ "deletion_state": "soft_deleted" if live[entity_id] else None,
+ }
+ return states
diff --git a/superset/versioning/activity/render.py b/superset/versioning/activity/render.py
new file mode 100644
index 00000000000..51b6811d4cc
--- /dev/null
+++ b/superset/versioning/activity/render.py
@@ -0,0 +1,285 @@
+# 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.
+"""Decoration: turn raw change-records into the ActivityRecord DTO.
+
+After fetching + filtering, each record needs the synthesized fields
+the API contract documents — ``entity_kind`` translated to the user-
+facing form, ``entity_uuid``, ``entity_deleted`` /
+``entity_deletion_state``, ``source`` (self vs. related),
+``summary`` (the headline), ``impact`` (chart-count for
+dashboard→dataset records), ``version_uuid``, ``changed_by``.
+
+This module collects all those decorations:
+
+* :func:`apply_record_decoration` — orchestrates the per-page additions in
+ one pass: pulls tombstones + uuids + impact counts in batches, then
+ walks records adding the synthesized fields and stripping the
+ internal-only columns the API contract doesn't expose.
+* :func:`_lookup_entity_uuids` plus the historical UUID resolver — identify
+ the live entity and the incarnation valid at each record transaction.
+* :func:`_build_summary` — pure projection of (api_kind, record kind,
+ entity_name) onto the headline string.
+* :func:`_changed_by_dict` — projects the user columns onto the
+ ``changed_by`` DTO shape.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from uuid import UUID
+
+import sqlalchemy as sa
+
+from superset.extensions import db
+from superset.versioning.activity.impact import (
+ batch_chart_counts,
+ collect_impact_pairs,
+ impact_for_record,
+)
+from superset.versioning.activity.kinds import (
+ API_KIND_LABEL,
+ chunked_ids,
+ load_live_model,
+ NAME_COLUMN,
+ TABLE_KIND_TO_API,
+ USER_FACING_KIND,
+)
+from superset.versioning.activity.queries import (
+ check_entity_tombstones,
+ resolve_historical_entity_uuids,
+)
+from superset.versioning.queries import derive_version_uuid
+
+_SUMMARY_VERBS: dict[str, str] = {
+ # The kind taxonomy mapped to past-tense verbs for the
+ # "<entity_label> <verb>: <entity_name>" headline. "field" is
+ # the fallback for scalar changes that don't map to a named verb.
+ "filter": "filter changed",
+ "metric": "metric changed",
+ "dimension": "dimension changed",
+ "column": "column changed",
+ "chart": "chart changed",
+ "time_range": "time range changed",
+ "color_palette": "palette changed",
+ "restore": "restored",
+ "field": "updated",
+}
+
+
+def apply_record_decoration(
+ records: list[dict[str, Any]],
+ path_kind: str,
+ path_id: int,
+) -> None:
+ """Add the synthesized ActivityRecord fields to each record in place:
+ ``entity_kind`` (translated to API form), ``entity_uuid``,
+ ``entity_deleted``, ``entity_deletion_state``, ``source``,
+ ``summary``, ``impact``, ``version_uuid``, ``changed_by``.
+
+ Mutates *records* in place; returns ``None``. Records are expected
+ to already carry ``entity_name`` from
+ :func:`apply_entity_name_denormalization`. The in-place mutation
+ avoids re-allocating thousands of dicts on hot dashboards; the
+ name + return signature make the side effect explicit instead of
+ pretending to be a pure projection.
+ """
+ if not records:
+ return
+
+ distinct: set[tuple[str, int]] = {
+ (
+ TABLE_KIND_TO_API.get(r["entity_kind"], ""),
+ r["entity_id"],
+ )
+ for r in records
+ if TABLE_KIND_TO_API.get(r["entity_kind"])
+ }
+ tombstones = check_entity_tombstones(distinct)
+ live_uuids = _lookup_entity_uuids(distinct, tombstones)
+ historical_uuids = resolve_historical_entity_uuids(records)
+ # Pre-compute impact counts for the whole page in one batch query
+ # instead of one COUNT per related record (was N+1).
+ impact_counts = batch_chart_counts(
+ path_id, collect_impact_pairs(records, path_kind)
+ )
+
+ for record in records:
+ api_kind = TABLE_KIND_TO_API.get(record["entity_kind"], "")
+ entity_id = record["entity_id"]
+ tombstone = tombstones.get(
+ (api_kind, entity_id), {"deleted": True, "deletion_state": None}
+ )
+ live_uuid = live_uuids.get((api_kind, entity_id))
+ historical_uuid = historical_uuids.get(
+ (api_kind, entity_id, record["transaction_id"])
+ )
+ reused_identity = (
+ live_uuid is not None
+ and historical_uuid is not None
+ and live_uuid != historical_uuid
+ )
+ entity_uuid = historical_uuid or live_uuid
+ if tombstone["deleted"] or reused_identity:
+ entity_uuid = None
+ if reused_identity:
+ tombstone = {"deleted": True, "deletion_state": None}
+ is_self = api_kind == path_kind and entity_id == path_id
+
+ # Emit the user-facing form ("dashboard"/"chart"/"dataset") on the
+ # wire; the internal class-name (api_kind) is kept above for the
+ # remaining decoration steps that key off model_cls.__name__.
+ record["entity_kind"] = USER_FACING_KIND.get(api_kind, api_kind)
+ record["entity_uuid"] = str(entity_uuid) if entity_uuid else None
+ record["entity_deleted"] = tombstone["deleted"]
+ record["entity_deletion_state"] = tombstone["deletion_state"]
+ record["source"] = "self" if is_self else "related"
+ record["version_uuid"] = (
+ str(derive_version_uuid(entity_uuid, record["transaction_id"]))
+ if entity_uuid
+ else None
+ )
+ record["changed_by"] = _changed_by_dict(record)
+
+ if is_self:
+ # Self records are left summary-less (the panel renders
+ # them from kind/path/values) — EXCEPT synthetic ``__meta__``
+ # headlines, whose entire payload IS the summary and whose
+ # primary surface is the entity's own stream ("restored to
+ # version N" must render on include=self).
+ record["summary"] = (
+ _build_summary(api_kind, record)
+ if record.get("kind") == "__meta__"
+ else ""
+ )
+ record["impact"] = None
+ else:
+ record["summary"] = _build_summary(api_kind, record)
+ record["impact"] = impact_for_record(record, path_kind, impact_counts)
+ if record["entity_deleted"]:
+ # Security: a tombstoned related entity has no live row, so
+ # the visibility filter cannot access-gate it (there is
+ # nothing to apply the FAB access filter to). Deletion must
+ # not WIDEN what a requester entitled only to the path entity
+ # can see, so redact everything that would identify the
+ # deleted related entity or its editors: its name, the
+ # synthesized headline, the editor identity, and the raw diff
+ # CONTENT (filter values, column names, SQL/adhoc
+ # expressions). The record still appears — kind, operation,
+ # and timestamps remain, rendered as a generic
+ # "(deleted) <kind>" marker — so the stream stays honest
+ # about WHEN something changed without disclosing WHAT, WHO,
+ # or WHICH entity. Self-path tombstones are untouched: the
+ # endpoint already gated them via ``raise_for_access`` on the
+ # path entity.
+ label = API_KIND_LABEL.get(api_kind, api_kind)
+ record["entity_name"] = ""
+ record["summary"] = f"(deleted) {label}"
+ record["changed_by"] = None
+ record["from_value"] = None
+ record["to_value"] = None
+ record["path"] = None
+
+ # Strip the internal-only columns the API contract doesn't expose.
+ for key in (
+ "entity_id",
+ "sequence",
+ "user_id",
+ "changed_by_id",
+ "first_name",
+ "last_name",
+ ):
+ record.pop(key, None)
+
+
+def _lookup_entity_uuids(
+ distinct: set[tuple[str, int]],
+ tombstones: dict[tuple[str, int], dict[str, Any]],
+) -> dict[tuple[str, int], UUID | None]:
+ """Batch-fetch live ``uuid`` per ``(api_kind, entity_id)``. Tombstoned
+ entities are skipped (their ``entity_uuid`` is null).
+ """
+ result: dict[tuple[str, int], UUID | None] = {}
+ by_kind: dict[str, list[int]] = {}
+ for api_kind, entity_id in distinct:
+ if tombstones.get((api_kind, entity_id), {}).get("deleted"):
+ continue
+ by_kind.setdefault(api_kind, []).append(entity_id)
+
+ # ``no_autoflush`` mirrors the defensive posture of the baseline +
+ # change-record listeners: this helper reads from live tables to
+ # resolve uuids, and a future caller that resolves an entity before
+ # the parent flush would otherwise trigger autoflush mid-read.
+ # Today's call sites run from request-path code with no pending
+ # session state, so the cost of the guard is zero.
+ with db.session.no_autoflush:
+ for api_kind, entity_ids in by_kind.items():
+ if api_kind not in NAME_COLUMN:
+ continue
+ model_cls = load_live_model(NAME_COLUMN[api_kind][0])
+ live_tbl = model_cls.__table__
+ # Chunk the IN-clause to stay under SQLite's bind-variable floor
+ # (a wide dashboard can have more related entities than the floor).
+ for chunk in chunked_ids(entity_ids):
+ rows = (
+ db.session.connection()
+ .execute(
+ sa.select(live_tbl.c.id, live_tbl.c.uuid).where(
+ live_tbl.c.id.in_(chunk)
+ )
+ )
+ .all()
+ )
+ for row in rows:
+ result[(api_kind, row[0])] = row[1]
+ return result
+
+
+def _build_summary(api_kind: str, record: dict[str, Any]) -> str:
+ """Build the headline for a related record:
+ ``"<Kind label> <verb>: <entity_name>"``."""
+ label = API_KIND_LABEL.get(api_kind, api_kind)
+ # Synthetic ``__meta__`` headlines carry their payload in to_value
+ # and their verb on the transaction's ``action_kind`` (path stays
+ # pure navigation). The restore variant names the version it
+ # restored to ("Restored to X from [date]" is not
+ # renderable from field diffs).
+ if record.get("kind") == "__meta__":
+ name = record.get("entity_name") or ""
+ if record.get("action_kind") == "restore":
+ to_value = record.get("to_value") or {}
+ version_number = to_value.get("version_number")
+ if version_number is not None:
+ headline = f"{label} restored to version {version_number}"
+ return f"{headline}: {name}" if name else headline
+ return f"{label} updated: {name}" if name else f"{label} updated"
+ verb = _SUMMARY_VERBS.get(record.get("kind", ""), "updated")
+ name = record.get("entity_name") or ""
+ return f"{label} {verb}: {name}" if name else f"{label} {verb}"
+
+
+def _changed_by_dict(record: dict[str, Any]) -> dict[str, Any] | None:
+ """Project the user columns onto the ``changed_by`` shape, or
+ ``None`` when no Flask user was attached to the save (CLI / Celery)
+ or when the user has since been deleted from ``ab_user``.
+ """
+ if record.get("changed_by_id") is None:
+ return None
+ return {
+ "id": record["changed_by_id"],
+ "first_name": record.get("first_name"),
+ "last_name": record.get("last_name"),
+ }
diff --git a/superset/versioning/activity/scope.py b/superset/versioning/activity/scope.py
new file mode 100644
index 00000000000..bc1d7912b5a
--- /dev/null
+++ b/superset/versioning/activity/scope.py
@@ -0,0 +1,138 @@
+# 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.
+"""Scope resolution — turn a path entity into the related-entity walk.
+
+Composes :mod:`~superset.versioning.activity.queries` (Phase A
+relationship walks) and :mod:`~superset.versioning.activity.windows`
+(pure interval arithmetic) into the
+``list[EntityWindows]`` scope that
+:func:`~superset.versioning.activity.queries.fetch_change_records`
+consumes.
+
+The functions here read the DB (via the Phase A helpers in
+:mod:`~superset.versioning.activity.queries`); the pure window-
+arithmetic functions previously colocated here now live in
+:mod:`~superset.versioning.activity.windows` so the package no longer
+needs a lazy import to dodge a ``scope ↔ queries`` cycle.
+"""
+
+from __future__ import annotations
+
+from superset.versioning.activity.kinds import EntityWindows, Window
+from superset.versioning.activity.queries import (
+ batch_datasets_used_by_charts,
+ charts_attached_to_dashboard,
+ datasets_used_by_chart,
+)
+from superset.versioning.activity.windows import (
+ intersect_windows,
+ merge_entity_windows,
+)
+
+
+def resolve_scope(
+ path_kind: str,
+ path_id: int,
+ include: str,
+ self_start_tx: int | None = None,
+) -> list[EntityWindows]:
+ """Build the ``[(api_kind, entity_id, [windows])]`` list that
+ :func:`~superset.versioning.activity.queries.fetch_change_records`
+ consumes, branching by *path_kind* and *include* mode.
+
+ *self_start_tx* lower-bounds the self window at the path entity's first
+ tracked transaction (see
+ :func:`~superset.versioning.activity.queries.first_tracked_tx`). This
+ scopes the self stream to the current entity's own history: matching
+ self records on the bare integer id would otherwise inherit a
+ hard-deleted predecessor's change records under id reuse
+ (SQLite/MySQL reuse ``max(id)+1``). ``None`` means the entity has no
+ tracked history yet, so the self stream contributes nothing.
+ """
+ want_self: bool = include in ("all", "self")
+ want_related: bool = include in ("all", "related")
+
+ scope: list[EntityWindows] = []
+ if want_self and self_start_tx is not None:
+ scope.append((path_kind, path_id, [Window(self_start_tx, None)]))
+ if want_related and self_start_tx is not None:
+ scope.extend(_resolve_related_scope(path_kind, path_id, self_start_tx))
+ return scope
+
+
+def _resolve_related_scope(
+ path_kind: str, path_id: int, self_start_tx: int
+) -> list[EntityWindows]:
+ """Walk the dependency edges from the path entity to its related
+ entities. Datasets have no transitive layer in V2.
+
+ The path entity's incarnation boundary clips every related window so a
+ reused integer id cannot inherit a hard-deleted predecessor's dependency
+ history.
+ """
+ if path_kind == "Dashboard":
+ related: list[EntityWindows] = _resolve_dashboard_scope(path_id)
+ elif path_kind == "Slice":
+ related = _resolve_chart_scope(path_id)
+ else:
+ return []
+
+ incarnation = Window(self_start_tx, None)
+ clipped: list[EntityWindows] = []
+ for api_kind, entity_id, windows in related:
+ overlaps = [
+ overlap
+ for window in windows
+ if (overlap := intersect_windows(incarnation, window)) is not None
+ ]
+ if overlaps:
+ clipped.append((api_kind, entity_id, overlaps))
+ return merge_entity_windows(clipped)
+
+
+def _resolve_dashboard_scope(dashboard_id: int) -> list[EntityWindows]:
+ """Charts on the dashboard during their attachment window, plus
+ datasets each chart pointed at during the intersection of (chart-
+ attachment, chart-on-dataset)."""
+ scope: list[EntityWindows] = []
+ chart_windows: dict[int, list[Window]] = {}
+ for slice_id, window in charts_attached_to_dashboard(dashboard_id):
+ chart_windows.setdefault(slice_id, []).append(window)
+
+ # One query for the dataset-history of every chart on the dashboard,
+ # not one query per chart. The per-slice form was O(n_charts) round-
+ # trips which dominated p95 on rich dashboards.
+ dataset_windows_by_slice = batch_datasets_used_by_charts(set(chart_windows))
+
+ for slice_id, attachment_windows in chart_windows.items():
+ scope.append(("Slice", slice_id, list(attachment_windows)))
+ dataset_windows = dataset_windows_by_slice.get(slice_id, [])
+ for attachment in attachment_windows:
+ for dataset_id, chart_dataset_window in dataset_windows:
+ if (
+ intersect := intersect_windows(attachment, chart_dataset_window)
+ ) is not None:
+ scope.append(("SqlaTable", dataset_id, [intersect]))
+ return merge_entity_windows(scope)
+
+
+def _resolve_chart_scope(slice_id: int) -> list[EntityWindows]:
+ """Datasets the chart pointed at over its full history."""
+ scope: list[EntityWindows] = []
+ for dataset_id, window in datasets_used_by_chart(slice_id):
+ scope.append(("SqlaTable", dataset_id, [window]))
+ return merge_entity_windows(scope)
diff --git a/superset/versioning/activity/visibility.py b/superset/versioning/activity/visibility.py
new file mode 100644
index 00000000000..2f1dca9d53a
--- /dev/null
+++ b/superset/versioning/activity/visibility.py
@@ -0,0 +1,206 @@
+# 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.
+"""Silent visibility filter for activity-view records.
+
+Drops records whose source entity the requester can't read. Silent in
+the sense that dropped records contribute no count and no placeholder
+to the response — the user sees only what they're entitled to see, and
+the response shape can't be used to infer the existence of entities
+they're gated out of.
+
+Visibility is resolved SQL-side via each resource's existing FAB
+access filter (``DashboardAccessFilter`` / ``ChartFilter`` /
+``DatasourceFilter``). Two SQL queries per kind (one for live ids, one
+for the access-filtered subset) replace the N-call
+``security_manager.can_access_<kind>(entity)`` loop that dominated
+latency on dashboard-scope responses with many related entities
+(sqlalchemy-review W-NEW-1).
+
+**Inline imports.** ``_resolve_visibility`` defers the FAB-filter
+imports (``DashboardAccessFilter`` / ``ChartFilter`` /
+``DatasourceFilter`` and ``SQLAInterface``) until call time. Same
+init-order rationale as :mod:`superset.versioning.baseline` —
+``versioning`` packages are imported from ``init_versioning()``
+before all model mappers are configured, and the filter classes pull
+in their resource's model graph (Chart → Dataset → Database for
+``ChartFilter``, etc.); a module-top import would trip mapper
+resolution before Continuum's ``make_versioned()`` has finished.
+
+**Integration shape.** The activity-view consumes FAB's access-filter
+classes (``DashboardAccessFilter`` / ``ChartFilter`` /
+``DatasourceFilter``) directly rather than translating them or
+re-implementing the predicate. That keeps the activity stream's
+visibility posture identical to the list endpoints' — operator-
+controlled and stable — at the cost of coupling to FAB's exact
+filter shape. Future entities added to the activity surface must
+extend the dispatch table in ``_resolve_visibility`` to include
+their access-filter class.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from superset.extensions import db
+from superset.versioning.activity.kinds import (
+ chunked_ids,
+ load_live_model,
+ NAME_COLUMN,
+ TABLE_KIND_TO_API,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def filter_records_by_visibility(
+ records: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """Drop records whose source entity the requester can't read.
+
+ The filter is silent: dropped records contribute no count
+ and no placeholder. Tombstoned entities (no live row) pass through
+ — the decorator step marks them ``entity_deleted: true`` and the
+ payload exposes no navigable ``entity_uuid``, so there's nothing
+ sensitive left to gate.
+
+ Visibility is resolved SQL-side via each resource's existing access
+ filter, which reads the requesting user from Flask-Login internally
+ (no explicit user parameter threads through here). If a CLI/Celery
+ bypass becomes necessary in the future, add it then with a real call
+ site.
+ """
+ if not records:
+ return records
+
+ distinct: set[tuple[str, int]] = {
+ (
+ TABLE_KIND_TO_API.get(r["entity_kind"], r["entity_kind"]),
+ r["entity_id"],
+ )
+ for r in records
+ }
+ visible = _resolve_visibility(distinct)
+ return [
+ r
+ for r in records
+ if visible.get(
+ (
+ TABLE_KIND_TO_API.get(r["entity_kind"], r["entity_kind"]),
+ r["entity_id"],
+ ),
+ True, # tombstone / unknown kind → pass through
+ )
+ ]
+
+
+def _resolve_visibility(
+ distinct_entities: set[tuple[str, int]],
+) -> dict[tuple[str, int], bool]:
+ """Return ``{(api_kind, entity_id): can_read}`` for the live row of
+ each entity. Missing live rows (tombstoned) map to ``True`` — the
+ decorator handles the deleted-state messaging separately.
+
+ Visibility is computed SQL-side via each resource's existing access
+ filter (``DashboardAccessFilter`` / ``ChartFilter`` /
+ ``DatasourceFilter``). These are the same filters FAB's
+ ``ModelRestApi`` applies to ``base_filters`` on list endpoints, so
+ the activity-view visibility check matches the rest of the read
+ surface byte-for-byte. Two queries per kind (one for live ids, one
+ for the access-filtered subset) replace the N-call
+ ``security_manager.can_access_<kind>(entity)`` loop that dominated
+ latency on dashboard-scope activity responses with many related
+ entities (sqlalchemy-review W-NEW-1).
+ """
+ # pylint: disable=import-outside-toplevel
+ from flask_appbuilder.models.sqla.interface import SQLAInterface
+
+ from superset.charts.filters import ChartFilter
+ from superset.dashboards.filters import DashboardAccessFilter
+ from superset.views.base import DatasourceFilter
+
+ access_filter_classes: dict[str, type] = {
+ "Dashboard": DashboardAccessFilter,
+ "Slice": ChartFilter,
+ "SqlaTable": DatasourceFilter,
+ }
+
+ by_kind: dict[str, list[int]] = {}
+ for api_kind, entity_id in distinct_entities:
+ by_kind.setdefault(api_kind, []).append(entity_id)
+
+ visible: dict[tuple[str, int], bool] = {}
+ for api_kind, entity_ids in by_kind.items():
+ if api_kind in NAME_COLUMN and api_kind not in access_filter_classes:
+ # The kind is in the change-records taxonomy but is missing
+ # an access-filter wiring — almost certainly a future-entity
+ # addition that updated ``TABLE_KIND_TO_API`` but forgot
+ # the visibility dispatch. Fail closed: the activity stream
+ # must not silently disclose change records for an entity
+ # whose access predicate is unimplemented. Warn so the gap
+ # surfaces in CI / staging logs before production.
+ logger.warning(
+ "activity visibility: no access filter wired for kind %r; "
+ "denying %d records",
+ api_kind,
+ len(entity_ids),
+ )
+ for entity_id in entity_ids:
+ visible[(api_kind, entity_id)] = False
+ continue
+ if api_kind not in NAME_COLUMN:
+ # Kind isn't in the change-records taxonomy at all — not
+ # something the activity-view emits today. Pass through so
+ # the decorator can mark it as a tombstone if appropriate.
+ for entity_id in entity_ids:
+ visible[(api_kind, entity_id)] = True
+ continue
+ model_cls = load_live_model(NAME_COLUMN[api_kind][0])
+ access_filter = access_filter_classes[api_kind]("id", SQLAInterface(model_cls))
+
+ # Chunk the candidate ids to stay under SQLite's bind-variable floor
+ # (a dashboard built from a large chart library can exceed it).
+ live_ids: set[int] = set()
+ visible_ids: set[int] = set()
+ for chunk in chunked_ids(entity_ids):
+ # Live ids — what exists at all. Used to decide tombstone vs
+ # not-visible: an id missing from this set is tombstoned and
+ # passes through (True); an id in this set but absent from the
+ # access-filtered set is denied (False).
+ live_ids.update(
+ row[0]
+ for row in db.session.query(model_cls.id)
+ .filter(model_cls.id.in_(chunk))
+ .all()
+ )
+ # Apply the SQL-side access filter to a query restricted to the
+ # candidate ids. Same predicate FAB uses for list endpoints, so
+ # results are consistent with the rest of the read surface.
+ visible_ids.update(
+ row[0]
+ for row in access_filter.apply(
+ db.session.query(model_cls.id).filter(model_cls.id.in_(chunk)),
+ value=None,
+ ).all()
+ )
+
+ for entity_id in entity_ids:
+ if entity_id not in live_ids:
+ visible[(api_kind, entity_id)] = True
+ else:
+ visible[(api_kind, entity_id)] = entity_id in visible_ids
+ return visible
diff --git a/superset/versioning/activity/windows.py b/superset/versioning/activity/windows.py
new file mode 100644
index 00000000000..b024636e8ff
--- /dev/null
+++ b/superset/versioning/activity/windows.py
@@ -0,0 +1,108 @@
+# 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.
+"""Pure window arithmetic on half-open ``[start_tx, end_tx)`` intervals.
+
+Extracted from the DB-touching scope resolution so that:
+
+* :mod:`scope` (DB-touching) can import this module at module-top.
+* :mod:`queries.fetch_change_records` can import
+ :func:`row_within_any_window` at module-top instead of through a
+ lazy import that previously dodged a ``scope ↔ queries`` cycle.
+
+Everything here is pure Python — no DB, no Flask. ``end_tx = None``
+means "open-ended (current)" and behaves like positive infinity.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from superset.versioning.activity.kinds import EntityWindows, Window
+
+
+def intersect_windows(outer: Window, inner: Window) -> Window | None:
+ """Intersect two half-open ``[start_tx, end_tx)`` windows.
+
+ Returns the clipped overlap, or ``None`` when they are disjoint.
+ ``end_tx = None`` means "open ended (current)" and acts like
+ positive infinity. Thin wrapper over :meth:`Window.intersect` —
+ kept as a free function so callers and tests don't have to migrate
+ to method form in lockstep with the dataclass promotion.
+ """
+ return outer.intersect(inner)
+
+
+def row_within_any_window(row: dict[str, Any], windows: list[Window]) -> bool:
+ """``True`` iff ``row['transaction_id']`` falls inside at least one
+ of *windows*. Half-open interval semantics match
+ :func:`intersect_windows`."""
+ if not windows:
+ return False
+ tx_id: int = row["transaction_id"]
+ return any(w.contains(tx_id) for w in windows)
+
+
+def merge_entity_windows(scope: list[EntityWindows]) -> list[EntityWindows]:
+ """Collapse repeated ``(api_kind, entity_id)`` entries by unioning
+ their window lists, and collapse overlapping/touching windows
+ within each entity into one.
+
+ The OR-clause in
+ :func:`~superset.versioning.activity.queries.fetch_change_records`
+ generates one branch per (kind, id, window) tuple. Without the
+ within-entity union, a chart that's been attached-and-detached
+ many times (or that repeated fixture loads have populated the M2M
+ shadow for) yields a separate clause per redundant window — at
+ ~10 entities × ~50 windows the SQL hits SQLite's
+ ``SQLITE_MAX_EXPR_DEPTH`` (1000). Merging here keeps the clause
+ count proportional to the number of *distinct* validity intervals,
+ not the number of shadow rows.
+ """
+ merged: dict[tuple[str, int], list[Window]] = {}
+ for api_kind, entity_id, windows in scope:
+ merged.setdefault((api_kind, entity_id), []).extend(windows)
+ return [
+ (api_kind, entity_id, union_windows(windows))
+ for (api_kind, entity_id), windows in merged.items()
+ ]
+
+
+def union_windows(windows: list[Window]) -> list[Window]:
+ """Sort + merge overlapping/touching half-open intervals.
+
+ Pure function — no DB. Touching ``[a, b)`` and ``[b, c)`` merge into
+ ``[a, c)``. ``end_tx = None`` (open-ended) absorbs everything to its
+ right. Returns a minimal disjoint cover of the input set.
+ """
+ if not windows:
+ return []
+ sorted_windows: list[Window] = sorted(windows, key=lambda w: w.start_tx)
+ out: list[Window] = [sorted_windows[0]]
+ for current in sorted_windows[1:]:
+ prev = out[-1]
+ if not prev.merges_with(current):
+ out.append(current)
+ continue
+ if prev.end_tx is None:
+ # Prior window is open-ended; it absorbs everything past.
+ continue
+ # Overlapping or touching — extend the prior window.
+ new_end: int | None = (
+ None if current.end_tx is None else max(prev.end_tx, current.end_tx)
+ )
+ out[-1] = Window(prev.start_tx, new_end)
+ return out
diff --git a/superset/versioning/api_helpers.py b/superset/versioning/api_helpers.py
index b5f239214d9..705bb2f46a1 100644
--- a/superset/versioning/api_helpers.py
+++ b/superset/versioning/api_helpers.py
@@ -14,18 +14,19 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""Shared handlers for the ``/versions/`` REST endpoints.
+"""Shared handlers for the ``/versions/`` and ``/activity/`` REST endpoints.
Each ``ChartRestApi`` / ``DashboardRestApi`` / ``DatasetRestApi`` carries
the same read endpoint methods — ``list_versions`` and ``get_version`` —
-whose bodies are byte-for-byte identical apart from the model class and
-the ``security_manager.raise_for_access`` kwarg. Extracting the bodies
-here lets each per-resource method collapse to a single delegation call,
-while the OpenAPI docstring + FAB decorators stay at the method site
-where they belong.
-
-(The restore endpoint ships in a later PR; only the read endpoints are
-wired here.)
+plus the ``activity`` endpoint on each resource. The bodies are
+byte-for-byte identical apart from the model class and the
+``security_manager.raise_for_access`` kwarg. Extracting the bodies here
+lets each per-resource method collapse to a single delegation call, while
+the OpenAPI docstring + FAB decorators stay at the method site where they
+belong.
+
+(The restore endpoint ships in a later PR; only the read + activity
+endpoints are wired here.)
"""
from __future__ import annotations
@@ -127,34 +128,82 @@ def current_entity_etag_uuid(
return str(version_uuid) if version_uuid else None
-def _resolve_entity(
- api: Any,
- model_cls: type[Model],
- uuid_str: str,
- access_kwarg: str,
-) -> tuple[Any, UUID] | Response:
- """Parse the path UUID, look up the live entity, run the read-access
- gate.
-
- Returns ``(entity, entity_uuid)`` on success or a pre-built
- ``Response`` (400 / 403 / 404) that the caller should return
- directly. The split shape keeps the call site terse and lets the
- three handler functions share the preflight without each repeating
- the try / except dance.
+# Maps the versioned model class name to the keyword argument
+# ``security_manager.raise_for_access`` expects for the per-resource
+# gate. Slice → ``chart=``, Dashboard → ``dashboard=``, SqlaTable →
+# ``datasource=``. Centralised here so /versions/ and /activity/
+# endpoints share one source of truth for the dispatch.
+_RAISE_FOR_ACCESS_KWARG: dict[str, str] = {
+ "Slice": "chart",
+ "Dashboard": "dashboard",
+ "SqlaTable": "datasource",
+}
+
+
+class PathEntityResponseError(Exception):
+ """Carry a pre-built error response from endpoint path resolution.
+
+ Endpoints catch it and return
+ the carried response directly. The shape exists so the
+ UUID-parse + find-by-uuid + read-access check can live in one
+ place across the ``/versions/`` and ``/activity/`` endpoint
+ families."""
+
+ def __init__(self, response: Any) -> None:
+ super().__init__("PathEntityResponseError")
+ self.response = response
+
+
+def resolve_endpoint_path_entity(
+ api: Any, model_cls: type[Model], uuid_str: str
+) -> tuple[Any, UUID]:
+ """Run path-entity preflight for a versions or activity endpoint.
+
+ 1. Parse *uuid_str* into a UUID (or raise → 400).
+ 2. Look up the live entity via ``VersionDAO.find_active_by_uuid``
+ (or raise → 404).
+ 3. Run ``security_manager.raise_for_access`` with the resource-typed
+ kwarg (or raise → 403).
+
+ Returns ``(entity, entity_uuid)`` on success — the parsed UUID is
+ threaded out so callers don't re-parse the path-string. Raises
+ :class:`PathEntityResponseError` carrying the appropriate error
+ Response on any failure; the endpoint method should::
+
+ try:
+ entity, entity_uuid = resolve_endpoint_path_entity(
+ self, Dashboard, uuid_str
+ )
+ except PathEntityResponseError as exc:
+ return exc.response
+
+ *api* is the FAB ``ModelRestApi`` instance — we call
+ ``api.response_400`` / ``api.response_403`` / ``api.response_404``
+ on it. Pass ``self`` from the endpoint method.
"""
try:
entity_uuid = UUID(uuid_str)
- except ValueError:
- return api.response_400(message="Invalid UUID")
+ except ValueError as exc:
+ raise PathEntityResponseError(api.response_400(message="Invalid UUID")) from exc
entity = VersionDAO.find_active_by_uuid(model_cls, entity_uuid)
if entity is None:
- return api.response_404()
-
+ raise PathEntityResponseError(api.response_404())
+
+ # Direct ``[…]`` would leak the unknown model name into a generic 500
+ # via the unhandled ``KeyError`` exception text. The three resource
+ # families wired today cover every key; a future entity added to the
+ # versioning surface without updating this dispatch table should fail
+ # closed (the test suite picks it up) rather than silently disclose.
+ kwarg = _RAISE_FOR_ACCESS_KWARG.get(model_cls.__name__)
+ if kwarg is None:
+ raise LookupError(
+ f"No raise_for_access kwarg registered for {model_cls.__name__!r}"
+ )
try:
- security_manager.raise_for_access(**{access_kwarg: entity})
- except SupersetSecurityException:
- return api.response_403()
+ security_manager.raise_for_access(**{kwarg: entity})
+ except SupersetSecurityException as exc:
+ raise PathEntityResponseError(api.response_403()) from exc
return entity, entity_uuid
@@ -163,13 +212,12 @@ def list_versions_endpoint(
api: Any,
model_cls: type[Model],
uuid_str: str,
- access_kwarg: str,
) -> Response:
"""Body of ``GET /api/v1/{resource}/<uuid>/versions/``."""
- resolved = _resolve_entity(api, model_cls, uuid_str, access_kwarg)
- if isinstance(resolved, Response):
- return resolved
- entity, entity_uuid = resolved
+ try:
+ entity, entity_uuid = resolve_endpoint_path_entity(api, model_cls, uuid_str)
+ except PathEntityResponseError as exc:
+ return exc.response
versions = VersionDAO.list_versions(model_cls, entity_uuid, entity=entity)
if versions is None:
@@ -188,13 +236,12 @@ def get_version_endpoint(
model_cls: type[Model],
uuid_str: str,
version_uuid_str: str,
- access_kwarg: str,
) -> Response:
"""Body of ``GET /api/v1/{resource}/<uuid>/versions/<version_uuid>/``."""
- resolved = _resolve_entity(api, model_cls, uuid_str, access_kwarg)
- if isinstance(resolved, Response):
- return resolved
- entity, entity_uuid = resolved
+ try:
+ entity, entity_uuid = resolve_endpoint_path_entity(api, model_cls, uuid_str)
+ except PathEntityResponseError as exc:
+ return exc.response
try:
version_uuid = UUID(version_uuid_str)
diff --git a/superset/versioning/changes/listener.py b/superset/versioning/changes/listener.py
index d8875eae9f6..e02f662dcbf 100644
--- a/superset/versioning/changes/listener.py
+++ b/superset/versioning/changes/listener.py
@@ -169,6 +169,29 @@ def build_action_headline(
# is correctly deduped.
_REGISTERED_SENTINEL = "_versioning_change_listener_registered"
+#: Metric namespace for swallowed capture-path failures. The capture
+#: listeners fail open (a versioning bug must never break a user's save),
+#: so the read path (``activity/orchestrator``) is richly instrumented but
+#: the write path historically logged-and-swallowed with no counter. Each
+#: ``_incr_capture_error(stage)`` emits ``<prefix>.<stage>.error`` so a
+#: systematic capture regression is alertable rather than log-grep-only.
+_CAPTURE_METRIC_PREFIX: str = "superset.versioning.capture"
+
+
+def _incr_capture_error(stage: str) -> None:
+ """Emit a counter for a swallowed capture-path failure at *stage*.
+
+ Best-effort: metrics emission must never itself break a user's save,
+ so it is wrapped in the same fail-open posture as the call site.
+ """
+ # pylint: disable=import-outside-toplevel
+ try:
+ from superset.extensions import stats_logger_manager
+
+ stats_logger_manager.instance.incr(f"{_CAPTURE_METRIC_PREFIX}.{stage}.error")
+ except Exception: # pylint: disable=broad-except
+ logger.exception("version_changes: failed to emit capture-error metric")
+
def _capture_dirty_entity_initial_state(
session: Session,
@@ -258,6 +281,7 @@ def _append_child_records_to_buffer(
del buffer[key]
except Exception: # pylint: disable=broad-except
logger.exception("version_changes: child-diff failed for tx %s", tx_id)
+ _incr_capture_error("child_diff")
def _current_transaction_id(session: Session) -> int | None:
@@ -345,6 +369,7 @@ def _stamp_action_kind_on_transaction(session: Session, tx_id: int) -> None:
action_kind,
tx_id,
)
+ _incr_capture_error("action_kind_stamp")
def _persist_buffered_records(
@@ -379,6 +404,7 @@ def _persist_buffered_records(
tx_id,
len(buffer),
)
+ _incr_capture_error("bulk_insert")
def register_change_record_listener() -> None: # noqa: C901
diff --git a/superset/versioning/diff.py b/superset/versioning/diff.py
index 5509d9f791e..326ba447fc1 100644
--- a/superset/versioning/diff.py
+++ b/superset/versioning/diff.py
@@ -896,9 +896,11 @@ def diff_dashboard_layout(
payloads carry old + new meta
* id in both, equal → no record
- The verb (add/remove/move/edit) is carried in each record's
- ``operation`` field; ``path`` is the pure navigation address to the
- node and carries no verb, matching the ``ChangeRecord`` contract.
+ The verb lives in each record's ``operation`` field
+ (``add`` / ``remove`` / ``move`` / ``edit``); ``path`` locates the
+ component as ``[<component-id>]`` (``[<component-id>, <leaf_key>, …]``
+ for an ``edit`` that recurses into ``meta``). Paths no longer carry
+ the verb — see :func:`_layout_chart_uuids_by_verb`.
``ROOT_ID`` / ``GRID_ID`` / ``HEADER_ID`` are suppressed (see
:data:`_LAYOUT_SUPPRESSED_IDS`).
diff --git a/superset/versioning/schemas.py b/superset/versioning/schemas.py
index b66efdf61db..e5ccc2ef269 100644
--- a/superset/versioning/schemas.py
+++ b/superset/versioning/schemas.py
@@ -23,7 +23,9 @@ avoid triplicated definitions.
from __future__ import annotations
-from marshmallow import fields, Schema
+from marshmallow import fields, Schema, validate
+
+from superset.versioning.changes import ACTION_KINDS
class VersionChangedBySchema(Schema):
@@ -115,8 +117,8 @@ class VersionListItemSchema(Schema):
"description": (
"One of 'baseline', 'update', or 'delete', derived from the "
"Continuum integer constant. Restore is not a distinct "
- "operation_type: a restore surfaces as an ordinary 'update' "
- "transaction."
+ "operation_type: a restore surfaces as 'update' carrying "
+ "``action_kind='restore'`` (see ACTIVITY_ACTION_KINDS)."
)
},
)
@@ -150,3 +152,327 @@ class VersionListResponseSchema(Schema):
result = fields.List(fields.Nested(VersionListItemSchema))
count = fields.Integer()
+
+
+# ---- Cross-entity activity view ------------------------------------------
+
+#: Allowed values for ``ActivityRecordSchema.entity_kind``. User-facing
+#: lowercase strings; the activity layer's internal kind dispatch keys off
+#: ``model_cls.__name__`` (``Dashboard`` / ``Slice`` / ``SqlaTable``) and
+#: translates to these labels at the JSON boundary in
+#: :func:`superset.versioning.activity.apply_record_decoration`.
+ACTIVITY_ENTITY_KINDS: tuple[str, ...] = ("dashboard", "chart", "dataset")
+
+#: Allowed values for ``ActivityRecordSchema.source``.
+ACTIVITY_SOURCES: tuple[str, ...] = ("self", "related")
+
+#: Allowed values for ``ActivityRecordSchema.entity_deletion_state``.
+#: Hard-delete is communicated separately via ``entity_deleted=true``;
+#: the remaining state is the soft-delete sentinel.
+ACTIVITY_DELETION_STATES: tuple[str, ...] = ("soft_deleted",)
+
+#: Allowed values for ``ActivityRecordSchema.kind`` — mirrors the
+#: change-record taxonomy. ``"field"`` is the
+#: fallback for scalar changes without a more specific category.
+#:
+#: ``"restore"`` (previously the synthetic kind for restore events) is
+#: removed: restores now produce regular field-level records plus
+#: ``version_transaction.action_kind="restore"`` (see ACTIVITY_ACTION_KINDS).
+ACTIVITY_CHANGE_KINDS: tuple[str, ...] = (
+ "filter",
+ "metric",
+ "dimension",
+ "column",
+ "chart",
+ "row",
+ "tab",
+ "tabs",
+ "header",
+ "markdown",
+ "divider",
+ "time_range",
+ "color_palette",
+ "field",
+ # Synthetic headline records emitted by commands via the listener's
+ # ACTION_META_KEY (the ``__meta__`` path convention): machine
+ # namespace, clearly non-content. The canonical case is restore,
+ # whose record's ``to_value`` carries the restored-to
+ # ``version_uuid`` / ``version_number``.
+ "__meta__",
+)
+
+#: Allowed values for ``ActivityRecordSchema.operation`` — the per-record
+#: verb. ``move`` only fires for layout records; ``add`` / ``remove`` /
+#: ``edit`` apply across every emit site.
+ACTIVITY_CHANGE_OPERATIONS: tuple[str, ...] = (
+ "add",
+ "remove",
+ "move",
+ "edit",
+ # Summary verb for a collapsed field: when one field's per-leaf
+ # records exceed ``MAX_RECORDS_PER_FIELD`` the diff engine emits a
+ # single ``update`` record standing in for the whole group (see
+ # ``superset.versioning.diff.cap_records``).
+ "update",
+ # Synthetic ``__meta__`` headline records announce an action (e.g. a
+ # restore) rather than mutating a field — the field-verb vocabulary
+ # would be dishonest for them. Source of the value:
+ # superset.versioning.changes.OPERATION_ANNOUNCE.
+ "announce",
+)
+
+#: Allowed values for ``ActivityRecordSchema.action_kind`` — the
+#: transaction-level avenue. ``null`` (omitted from the enum, signalled
+#: by ``allow_none``) means "ordinary save". Sourced from
+#: :data:`superset.versioning.changes.ACTION_KINDS` so a future
+#: addition (e.g. ``"thumbnail_warm"``) only has to update that
+#: constant; the schema picks it up automatically.
+ACTIVITY_ACTION_KINDS: tuple[str, ...] = tuple(sorted(ACTION_KINDS))
+
+
+class ActivityChangedBySchema(Schema):
+ """User attribution for an activity record.
+
+ The activity-view payload exposes only the display fields
+ (``id`` + given/family name); ``username`` is omitted by design (see
+ the ActivityRecord DTO). ``null`` when the saving user
+ has been deleted from ``ab_user`` (the saving user row is gone
+ clarification).
+ """
+
+ id = fields.Integer()
+ first_name = fields.String()
+ last_name = fields.String()
+
+
+class ActivityImpactSchema(Schema):
+ """Dependent-count summary attached to ``source='related'`` records.
+
+ Synthesized server-side at the time of the activity query — it counts
+ siblings affected by the same upstream change at the same transaction
+ (e.g., how many charts on the requested dashboard pointed at the
+ dataset whose edit this record represents).
+ """
+
+ charts = fields.Integer(
+ metadata={
+ "description": (
+ "Number of sibling charts on the path entity affected by "
+ "the same related-record change at this transaction."
+ )
+ },
+ )
+
+
+class ActivityRecordSchema(Schema):
+ """One change record in the activity stream.
+
+ One record per atomic field-level change. Fields mirror
+ the ``ActivityRecord`` DTO — see the schema for source
+ and required/optional details.
+ """
+
+ version_uuid = fields.String(
+ metadata={
+ "description": (
+ "Stable UUIDv5 identifier for the source version "
+ "(``derive_version_uuid(entity_uuid, transaction_id)``). "
+ "Identical to what ``/versions/<version_uuid>/`` would "
+ "return for the same change."
+ )
+ },
+ )
+ entity_kind = fields.String(
+ validate=validate.OneOf(ACTIVITY_ENTITY_KINDS),
+ metadata={
+ "description": (
+ "User-facing kind of the source entity: one of "
+ '``"dashboard"`` / ``"chart"`` / ``"dataset"``.'
+ )
+ },
+ )
+ entity_uuid = fields.String(
+ allow_none=True,
+ metadata={
+ "description": (
+ "UUID of the source entity; ``null`` only when "
+ "``entity_deleted: true`` (the entity has been hard-deleted "
+ "since the change was recorded)."
+ )
+ },
+ )
+ entity_name = fields.String(
+ metadata={
+ "description": (
+ "Name of the source entity *at the time of the change* — "
+ "denormalized from the validity-strategy shadow row. "
+ "Survives entity rename / delete."
+ )
+ },
+ )
+ entity_deleted = fields.Boolean(
+ metadata={
+ "description": (
+ "True iff the source entity is hard-deleted "
+ "(no live row by ``entity_id``). False for live and "
+ "soft-deleted entities."
+ )
+ },
+ )
+ entity_deletion_state = fields.String(
+ allow_none=True,
+ validate=validate.OneOf(ACTIVITY_DELETION_STATES),
+ metadata={
+ "description": (
+ "Present when the source entity has non-null ``deleted_at`` "
+ "Absent or ``null`` otherwise."
+ )
+ },
+ )
+ source = fields.String(
+ validate=validate.OneOf(ACTIVITY_SOURCES),
+ metadata={
+ "description": (
+ '``"self"`` if ``(entity_kind, entity_id)`` matches the '
+ 'path entity; else ``"related"``. Drives the frontend\'s '
+ "no-group-under-save rendering rule."
+ )
+ },
+ )
+ transaction_id = fields.Integer(
+ metadata={"description": "Stable secondary ordering key; never reused."},
+ )
+ issued_at = fields.DateTime(
+ metadata={"description": "UTC timestamp; primary ordering key (DESC)."},
+ )
+ changed_by = fields.Nested(
+ ActivityChangedBySchema,
+ allow_none=True,
+ metadata={
+ "description": (
+ "User who produced the change, or ``null`` when the saving "
+ "user no longer exists in ``ab_user``."
+ )
+ },
+ )
+ kind = fields.String(
+ validate=validate.OneOf(ACTIVITY_CHANGE_KINDS),
+ metadata={
+ "description": (
+ "Content category — what kind of thing changed. "
+ "``field`` is the fallback for scalar changes without a "
+ "more specific category. Per-record."
+ )
+ },
+ )
+ operation = fields.String(
+ validate=validate.OneOf(ACTIVITY_CHANGE_OPERATIONS),
+ metadata={
+ "description": (
+ "Per-record verb: ``add`` / ``remove`` / ``move`` / "
+ "``edit``. Explicit instead of inferred from "
+ "``from_value`` / ``to_value`` null-tests. ``move`` only "
+ "fires for layout records."
+ )
+ },
+ )
+ action_kind = fields.String(
+ validate=validate.OneOf(ACTIVITY_ACTION_KINDS),
+ allow_none=True,
+ metadata={
+ "description": (
+ "Transaction-level avenue that produced this record's "
+ "batch: ``restore`` / ``import`` / ``clone``. ``null`` "
+ "for ordinary saves. All records sharing a "
+ "``transaction_id`` share the same action_kind. The "
+ "schema's third ``*_kind`` column (entity_kind / kind / "
+ "action_kind), at transaction scope."
+ )
+ },
+ )
+ path = fields.List(
+ fields.String(),
+ allow_none=True,
+ metadata={
+ "description": (
+ "Pure navigation address — no verb or kind embedded. "
+ "Examples: ``['slice_name']``, ``['params', "
+ "'adhoc_filters', 'country']``, ``['CHART-x']`` for a "
+ "layout add/remove/move, ``['HEADER-y', 'text']`` for a "
+ "layout edit leaf. The verb lives in ``operation``, the "
+ "element type in ``kind``."
+ )
+ },
+ )
+ from_value = fields.Raw(
+ allow_none=True,
+ metadata={"description": "Prior value; ``null`` = didn't exist."},
+ )
+ to_value = fields.Raw(
+ allow_none=True,
+ metadata={"description": "New value; ``null`` = removed."},
+ )
+ summary = fields.String(
+ metadata={
+ "description": (
+ 'Synthesized headline for ``source: "related"`` records — '
+ 'e.g., ``"Dataset updated: Sales Transactions"``. '
+ 'Empty string for ``source: "self"`` records, except '
+ "``__meta__`` self records (e.g. restore announcements), "
+ "which carry their own headline."
+ )
+ },
+ )
+ impact = fields.Nested(
+ ActivityImpactSchema,
+ allow_none=True,
+ metadata={
+ "description": (
+ 'Optional dependent-count for ``source: "related"`` '
+ 'records — e.g., ``{"charts": 4}`` for a dataset edit '
+ "that affected 4 charts on the path dashboard at the "
+ 'change\'s transaction. Absent for ``source: "self"`` '
+ "records and for related records without dependents."
+ )
+ },
+ )
+ first_tracked_save = fields.Boolean(
+ metadata={
+ "description": (
+ "True when this record's transaction is the entity's "
+ "FIRST tracked save (first UPDATE after the retroactive "
+ "baseline). Such transactions can carry dozens of "
+ "params-normalization records for entities that predate "
+ "versioning; clients use the marker to collapse them "
+ "rather than render each delta as a user edit. Matched "
+ "against the LIVE row's (id, uuid), so it is always "
+ "false for hard-deleted entities (no live row) and for "
+ "shadow rows predating the entity's current uuid."
+ )
+ },
+ )
+
+
+class ActivityResponseSchema(Schema):
+ """Envelope for activity-view responses."""
+
+ result = fields.List(fields.Nested(ActivityRecordSchema))
+ count = fields.Integer(
+ metadata={
+ "description": (
+ "Total record count across all pages (the filtered + "
+ "denormalized stream), not just the current page. When "
+ "``truncated`` is true this is a floor (the count within "
+ "the fetched window), not the absolute total."
+ )
+ },
+ )
+ truncated = fields.Boolean(
+ metadata={
+ "description": (
+ "True when the request hit the per-request fetch ceiling "
+ "and older records exist beyond the returned window. "
+ "Narrow the time range (``since``/``until``) to see them."
+ )
+ },
+ )
diff --git a/tests/integration_tests/versioning/activity_view_tests.py b/tests/integration_tests/versioning/activity_view_tests.py
new file mode 100644
index 00000000000..23f47813e32
--- /dev/null
+++ b/tests/integration_tests/versioning/activity_view_tests.py
@@ -0,0 +1,1256 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for the cross-entity activity-view API (sc-107283).
+
+US1 — dashboard activity stream: ``GET /api/v1/dashboard/<uuid>/activity/``.
+Tests for US2 (chart activity) and US3 (dataset activity) come in later
+phases.
+
+Per spec T053 / sc-103156 T062, every test that mutates a fixture entity
+wraps the test body in ``try``/``finally`` with
+``metadata_db.session.rollback()`` in the ``finally``. The rationale is
+documented in the spec — Continuum captures dirty mappers during
+autoflush, so leaving an instrumented attribute dirty pollutes
+downstream tests via the shadow tables.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+from superset.connectors.sqla.models import SqlaTable
+from superset.extensions import db
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.utils import json as _json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import (
+ ADMIN_USERNAME,
+ ALPHA_USERNAME,
+ GAMMA_USERNAME,
+)
+from tests.integration_tests.fixtures.birth_names_dashboard import ( # noqa: F401
+ load_birth_names_dashboard_with_slices,
+ load_birth_names_data,
+)
+
+
+def _get_birth_names_dataset() -> SqlaTable:
+ return (
+ db.session.query(SqlaTable)
+ .filter(SqlaTable.table_name == "birth_names")
+ .first()
+ )
+
+
+def _persist_fixture_state() -> None:
+ """Force the fixture's pending INSERTs to commit so subsequent edits
+ produce *new* version rows instead of being batched into the
+ creation transaction. Mirrors the same helper in
+ ``tests/integration_tests/dashboards/version_history_tests.py``.
+ """
+ db.session.commit()
+
+
+def _get_birth_names_dashboard() -> Dashboard:
+ return (
+ db.session.query(Dashboard)
+ .filter(Dashboard.dashboard_title == "USA Births Names")
+ .first()
+ )
+
+
+class TestDashboardActivityView(SupersetTestCase):
+ """T017–T026 — ``GET /api/v1/dashboard/<uuid>/activity/`` (US1)."""
+
+ @pytest.fixture(autouse=True)
+ def _load_data( # noqa: PT004, F811
+ self,
+ load_birth_names_dashboard_with_slices: Any, # noqa: F811
+ ) -> None:
+ pass
+
+ def _activity(self, dashboard_uuid: str, **query: Any) -> Any:
+ return self.client.get(
+ f"/api/v1/dashboard/{dashboard_uuid}/activity/",
+ query_string=query,
+ )
+
+ # ---- 4xx boundary cases ----
+
+ def test_activity_returns_404_for_unknown_uuid(self) -> None:
+ """AV-009: unknown path entity → 404."""
+ self.login(ADMIN_USERNAME)
+ rv = self._activity("00000000-0000-0000-0000-000000000000")
+ assert rv.status_code == 404
+
+ def test_activity_returns_400_for_invalid_uuid(self) -> None:
+ """A malformed UUID is rejected by the endpoint, not by Werkzeug."""
+ self.login(ADMIN_USERNAME)
+ rv = self._activity("not-a-uuid")
+ assert rv.status_code == 400
+
+ def test_activity_returns_400_for_invalid_include(self) -> None:
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dashboard.uuid), include="sibling")
+ assert rv.status_code == 400
+
+ def test_activity_returns_400_for_invalid_since(self) -> None:
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dashboard.uuid), since="yesterday")
+ assert rv.status_code == 400
+
+ def test_activity_allows_read_non_owner(self) -> None:
+ """Activity is a read endpoint: a non-owner with read access (Alpha,
+ which carries broad read + datasource access) can read a dashboard's
+ activity stream — ``raise_for_access(dashboard=)`` does not reject —
+ so the endpoint returns 200. Visibility of *related* rows is filtered
+ separately, inside the activity layer."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+
+ self.login(ALPHA_USERNAME)
+ rv = self._activity(dashboard_uuid)
+ assert rv.status_code == 200
+
+ def test_visibility_filter_silently_drops_inaccessible_related(self) -> None:
+ """AV-008 security control: a related record whose entity the caller
+ cannot read is *silently* dropped — absent from the result, no
+ placeholder, no contribution to count. Exercises the real
+ enforcement point (``filter_records_by_visibility`` →
+ ``DashboardAccessFilter``) with a restricted Gamma principal.
+
+ Setup uses two dashboards (no datasource needed): one owned by
+ Gamma (readable), and an admin-owned one Gamma may not read.
+ """
+ from superset import security_manager
+ from superset.subjects.utils import get_user_subject
+ from superset.versioning.activity.visibility import (
+ filter_records_by_visibility,
+ )
+
+ admin = security_manager.find_user(ADMIN_USERNAME)
+ gamma = security_manager.find_user(GAMMA_USERNAME)
+ # Access control is subject-based (``editors``) since the Subject
+ # work replaced ``owners``; grant read via each user's Subject.
+ visible = Dashboard(
+ dashboard_title=f"vis-probe-owned {uuid4().hex[:8]}",
+ slug=f"vis-owned-{uuid4().hex[:8]}",
+ published=False,
+ editors=[get_user_subject(gamma.id)],
+ )
+ hidden = Dashboard(
+ dashboard_title=f"vis-probe-hidden {uuid4().hex[:8]}",
+ slug=f"vis-hidden-{uuid4().hex[:8]}",
+ published=False,
+ editors=[get_user_subject(admin.id)],
+ )
+ db.session.add_all([visible, hidden])
+ db.session.commit()
+ visible_id, hidden_id = visible.id, hidden.id
+ try:
+ records = [
+ {"entity_kind": "dashboard", "entity_id": visible_id},
+ {"entity_kind": "dashboard", "entity_id": hidden_id},
+ ]
+ self.login(GAMMA_USERNAME)
+ filtered = filter_records_by_visibility(records)
+ kept_ids = {r["entity_id"] for r in filtered}
+
+ assert visible_id in kept_ids, (
+ "gamma-owned dashboard must stay visible to Gamma"
+ )
+ assert hidden_id not in kept_ids, (
+ "unpublished admin-owned dashboard must be dropped for Gamma"
+ )
+ # Silent: the dropped record leaves nothing behind (no placeholder).
+ assert len(filtered) == 1
+ finally:
+ db.session.rollback()
+ for did in (visible_id, hidden_id):
+ obj = db.session.query(Dashboard).filter(Dashboard.id == did).first()
+ if obj is not None:
+ db.session.delete(obj)
+ db.session.commit()
+
+ # ---- 200 happy paths ----
+
+ def test_activity_returns_200_with_envelope_shape(self) -> None:
+ """Smoke test: the endpoint returns the documented envelope shape
+ (``result`` list + ``count`` integer) even when the dashboard has
+ no activity yet."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ assert "result" in body
+ assert "count" in body
+ assert isinstance(body["result"], list)
+ assert isinstance(body["count"], int)
+
+ def test_activity_includes_chart_edit_as_related(self) -> None:
+ """T018 / AS-1 of US1: editing a chart on the dashboard surfaces
+ the chart-edit record with ``entity_kind=Slice`` and
+ ``source=related``."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ chart_on_dashboard = next(iter(dashboard.slices), None)
+ assert chart_on_dashboard is not None
+ chart_id = chart_on_dashboard.id
+ original_name = chart_on_dashboard.slice_name
+
+ try:
+ chart_on_dashboard.slice_name = f"{original_name} (edited)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ related = [
+ r
+ for r in body["result"]
+ if r["entity_kind"] == "chart" and r["source"] == "related"
+ ]
+ assert related, (
+ "Expected at least one Slice/related record from the chart "
+ "edit; got: "
+ f"{[(r['entity_kind'], r['source']) for r in body['result']]}"
+ )
+ # Spot-check the carry-through of denormalized fields
+ sample = related[0]
+ assert sample["entity_uuid"] is not None
+ assert "transaction_id" in sample
+ assert "issued_at" in sample
+ finally:
+ db.session.rollback()
+ chart = db.session.query(Slice).filter(Slice.id == chart_id).one()
+ chart.slice_name = original_name
+ db.session.commit()
+
+ def test_activity_include_self_excludes_related(self) -> None:
+ """T023 / AV-016: ``?include=self`` filters out related records."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ chart_on_dashboard = next(iter(dashboard.slices), None)
+ assert chart_on_dashboard is not None
+ chart_id = chart_on_dashboard.id
+ original_name = chart_on_dashboard.slice_name
+
+ try:
+ chart_on_dashboard.slice_name = f"{original_name} (edited self)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid, include="self")
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ for record in body["result"]:
+ assert record["source"] == "self", (
+ f"include=self leaked a non-self record: {record}"
+ )
+ assert record["entity_kind"] == "dashboard"
+ finally:
+ db.session.rollback()
+ chart = db.session.query(Slice).filter(Slice.id == chart_id).one()
+ chart.slice_name = original_name
+ db.session.commit()
+
+ def test_activity_include_related_excludes_self(self) -> None:
+ """T024 / AV-016: ``?include=related`` returns only related records."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ original_title = dashboard.dashboard_title
+ dashboard_id = dashboard.id
+ chart_id: int | None = None
+ chart_original_name: str | None = None
+
+ try:
+ # Edit the dashboard's own field so we have a self record to
+ # filter out, and edit a chart on it so we have a related
+ # record to keep.
+ dashboard.dashboard_title = f"{original_title} (edited dash)"
+ db.session.commit()
+ chart_on_dashboard = next(iter(dashboard.slices), None)
+ assert chart_on_dashboard is not None
+ chart_id = chart_on_dashboard.id
+ chart_original_name = chart_on_dashboard.slice_name
+ chart_on_dashboard.slice_name = f"{chart_original_name} (edited chart)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid, include="related")
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ for record in body["result"]:
+ assert record["source"] == "related", (
+ f"include=related leaked a self record: {record}"
+ )
+ assert record["entity_kind"] != "dashboard"
+ finally:
+ db.session.rollback()
+ dashboard = (
+ db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+ )
+ dashboard.dashboard_title = original_title
+ if chart_id is not None and chart_original_name is not None:
+ chart = db.session.query(Slice).filter(Slice.id == chart_id).one()
+ chart.slice_name = chart_original_name
+ db.session.commit()
+
+ def test_activity_pagination_clamps_oversized_page_size(self) -> None:
+ """``?page_size=500`` is silently clamped to the contract max
+ (200) rather than rejected with 400."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dashboard.uuid), page_size="500")
+ assert rv.status_code == 200
+
+ def test_activity_ordering_is_stable_by_issued_at_then_transaction_id(self) -> None:
+ """T040 / AV-006: records are ordered ``(issued_at DESC,
+ transaction_id DESC)``. When two records share ``issued_at`` the
+ tie-break is ``transaction_id`` — never random. We verify this by
+ asserting the result list is monotonically non-increasing on the
+ composite key, which would only hold under deterministic
+ ordering."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dashboard.uuid))
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ records = body["result"]
+ # Each pair of adjacent records must satisfy (prev >= cur) on the
+ # composite (issued_at, transaction_id) — DESC ordering.
+ # ``records[1:]`` is intentionally one element shorter than
+ # ``records``; strict=False is the correct semantic for an
+ # adjacent-pair iteration.
+ for prev, cur in zip(records, records[1:], strict=False):
+ assert (prev["issued_at"], prev["transaction_id"]) >= (
+ cur["issued_at"],
+ cur["transaction_id"],
+ ), (
+ f"Ordering broke at adjacent pair: "
+ f"prev=({prev['issued_at']}, {prev['transaction_id']}) "
+ f"cur=({cur['issued_at']}, {cur['transaction_id']})"
+ )
+
+ def test_activity_page_size_caps_returned_records_at_200(self) -> None:
+ """T041: ``?page_size=500`` must return *at most* 200 records.
+ Pairs with the no-400 check above: that test confirms the
+ oversized request is accepted, this test confirms the response
+ is bounded as the contract guarantees (AV-019 / spec
+ ActivityResponseSchema documentation)."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dashboard.uuid), page_size="500")
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ assert len(body["result"]) <= 200, (
+ f"page_size=500 returned {len(body['result'])} records; "
+ "cap is 200 per the OpenAPI schema"
+ )
+
+ def test_activity_marks_hard_deleted_chart_with_tombstone(self) -> None:
+ """T042 / D-15: when a chart was on the dashboard and has since
+ been hard-deleted, the chart's historical change records still
+ surface in the dashboard's activity stream, marked with
+ ``entity_deleted: true`` and ``entity_uuid: null``. Because a
+ tombstoned related entity has no live row to access-gate, its
+ identifying metadata is redacted: ``entity_name`` is blanked,
+ ``summary`` collapses to a generic "(deleted) <kind>" marker, and
+ ``changed_by`` (plus the diff values) are dropped — the record
+ still marks WHEN a change happened without disclosing WHAT, WHO,
+ or WHICH entity to a requester entitled only to the dashboard.
+
+ Hard-delete pattern: edit the chart (creates a Slice change
+ record), commit, then ``db.session.delete(chart); commit``.
+ Continuum end-stamps the M2M row but does not cascade-delete
+ the shadow rows, so the history is still reachable. The
+ activity-view's tombstone check (``_check_entity_tombstones``)
+ detects the missing live row and stamps the record."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ chart_to_delete = (
+ db.session.query(Slice).filter(Slice.slice_name == "Girls").first()
+ )
+ assert chart_to_delete is not None
+ original_name = chart_to_delete.slice_name
+
+ try:
+ # Step 1: generate a chart-edit change record for "Girls".
+ chart_to_delete.slice_name = f"{original_name} (pre-delete edit)"
+ db.session.commit()
+
+ # Step 2: hard-delete the chart. The fixture's _cleanup will
+ # tolerate this — its `Slice.id.in_(slice_ids)` filter
+ # silently skips the missing row.
+ db.session.delete(chart_to_delete)
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ tombstoned = [
+ r
+ for r in body["result"]
+ if r["entity_kind"] == "chart" and r["entity_deleted"] is True
+ ]
+ seen = [
+ (r["entity_kind"], r["entity_deleted"]) for r in body["result"][:10]
+ ]
+ assert tombstoned, (
+ "Expected ≥1 tombstoned Slice record after the chart was "
+ f"hard-deleted; got entity_deleted values: {seen}"
+ )
+ sample = tombstoned[0]
+ got_uuid = sample["entity_uuid"]
+ assert got_uuid is None, (
+ f"Hard-deleted entity should have null entity_uuid; got {got_uuid!r}"
+ )
+ # A tombstoned related entity cannot be access-gated, so its
+ # identifying metadata is redacted rather than recovered.
+ assert sample["entity_name"] == "", (
+ f"deleted entity_name should be redacted to ''; got {sample!r}"
+ )
+ assert sample["summary"].startswith("(deleted)"), (
+ "deleted record should carry a generic '(deleted) <kind>' "
+ f"headline; got {sample!r}"
+ )
+ assert sample["changed_by"] is None, (
+ f"deleted record should redact changed_by; got {sample!r}"
+ )
+ finally:
+ db.session.rollback()
+
+ def test_check_entity_tombstones_handles_multiple_kinds(self) -> None:
+ """Regression for the v4 indent slip in ``check_entity_tombstones``:
+ when called with ``distinct_entities`` spanning multiple kinds,
+ every kind must get its tombstone-state result, not just the
+ one iterated last.
+
+ Pre-fix, the per-entity result-population block sat outside the
+ ``for api_kind in by_kind.items():`` loop, so all but the
+ last-iterated kind silently fell through to the call-site
+ default ``{"deleted": True}`` in ``render.apply_record_decoration``
+ — live entities were rendered as tombstoned in the API response.
+ The previous tombstone test exercised only one kind, so dict
+ iteration order made the bug invisible.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.versioning.activity.queries import check_entity_tombstones
+
+ _persist_fixture_state()
+ chart = db.session.query(Slice).filter(Slice.slice_name == "Girls").first()
+ dataset = _get_birth_names_dataset()
+ assert chart is not None
+ assert dataset is not None
+
+ distinct = {("Slice", chart.id), ("SqlaTable", dataset.id)}
+ result = check_entity_tombstones(distinct)
+
+ assert ("Slice", chart.id) in result, (
+ "Multi-kind call must populate every kind; got keys: "
+ f"{sorted(result.keys())}"
+ )
+ assert ("SqlaTable", dataset.id) in result
+ assert result[("Slice", chart.id)] == {
+ "deleted": False,
+ "deletion_state": None,
+ }, f"Live chart should report deleted=False; got {result[('Slice', chart.id)]}"
+ assert result[("SqlaTable", dataset.id)] == {
+ "deleted": False,
+ "deletion_state": None,
+ }, (
+ f"Live dataset should report deleted=False; "
+ f"got {result[('SqlaTable', dataset.id)]}"
+ )
+
+ @pytest.mark.skip(
+ reason="Depends on the retention prune (_prune_old_versions_impl), which "
+ "was extracted to sc-111099-version-history-retention. This test "
+ "exercises activity-view + retention together and runs once both PRs "
+ "merge; un-skip then."
+ )
+ def test_activity_excludes_records_after_retention_prune(self) -> None:
+ """T051 / AV-010: retention bounds the activity feed. After
+ ``_prune_old_versions_impl`` drops shadow / change-record rows
+ whose ``version_transaction.issued_at`` is older than the
+ retention cutoff, the activity stream stops surfacing them.
+
+ Test pattern: capture the highest ``version_transaction.id``
+ before our edits, edit a chart (creating a new transaction),
+ backdate that transaction's ``issued_at`` past the retention
+ cutoff, run the prune, and assert the chart-edit no longer
+ appears in the activity stream."""
+ # pylint: disable=import-outside-toplevel
+ from datetime import datetime, timedelta
+
+ import sqlalchemy as sa
+ from sqlalchemy_continuum import versioning_manager
+
+ from superset.tasks.version_history_retention import (
+ _prune_old_versions_impl,
+ )
+
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ chart = db.session.query(Slice).filter(Slice.slice_name == "Boys").first()
+ assert chart is not None
+ chart_id = chart.id
+ original_name = chart.slice_name
+
+ tx_table = versioning_manager.transaction_cls.__table__
+
+ # Capture pre-edit max tx_id so we can identify the rows produced
+ # by THIS test (and not backdate anything else).
+ max_tx_before = (
+ db.session.connection()
+ .execute(sa.select(sa.func.max(tx_table.c.id)))
+ .scalar()
+ or 0
+ )
+
+ try:
+ chart.slice_name = f"{original_name} (retention test)"
+ db.session.commit()
+
+ # Backdate the new transactions to before the 30-day cutoff.
+ old_timestamp = datetime.utcnow() - timedelta(days=60)
+ db.session.connection().execute(
+ sa.update(tx_table)
+ .where(tx_table.c.id > max_tx_before)
+ .values(issued_at=old_timestamp)
+ )
+ db.session.commit()
+
+ # Snapshot the activity-record count BEFORE the prune. With
+ # ?page_size=200 + the highest possible page coverage, the
+ # count field is the post-visibility filtered total.
+ self.login(ADMIN_USERNAME)
+ rv_before = self._activity(dashboard_uuid, page_size="200")
+ assert rv_before.status_code == 200
+ count_before = _json.loads(rv_before.data.decode("utf-8"))["count"]
+
+ # Run the prune. The backdated tx rows are now > 30 days old
+ # and should be deleted. AV-010 requires the prune to remove
+ # at least the backdated transaction(s) we created.
+ stats = _prune_old_versions_impl(retention_days=30)
+ assert stats.get("pruned_transactions", 0) >= 1, (
+ f"Prune should have removed our backdated tx; stats={stats}"
+ )
+
+ # After the prune, the activity endpoint still works and the
+ # filtered count has DROPPED — change records joined to the
+ # pruned transactions are no longer in the result set (the
+ # join in _fetch_change_records drops them).
+ rv_after = self._activity(dashboard_uuid, page_size="200")
+ assert rv_after.status_code == 200
+ count_after = _json.loads(rv_after.data.decode("utf-8"))["count"]
+ assert count_after < count_before, (
+ f"Activity count should decrease after prune; "
+ f"before={count_before} after={count_after}"
+ )
+ finally:
+ db.session.rollback()
+ chart = db.session.query(Slice).filter(Slice.id == chart_id).one()
+ chart.slice_name = original_name
+ db.session.commit()
+
+ def test_activity_pagination_is_deterministic_and_disjoint(self) -> None:
+ """T039 / SC-AV-002 (pragmatic interpretation): two consecutive
+ requests for the same page return identical results, and
+ consecutive pages do not overlap.
+
+ The spec's stricter "no skip/duplicate under concurrent writes"
+ is unprovable with offset pagination — new top-inserted records
+ shift every later page by one. Cursor pagination would solve
+ this and is deferred per plan §D-10. Under THIS pagination
+ scheme, the testable guarantees are: (a) the same request fired
+ twice produces the same page (request determinism), and (b)
+ page N and page N+1 share no record under the same request
+ round. Both come from the stable
+ ``(issued_at DESC, transaction_id DESC, sequence DESC)`` sort.
+ """
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ self.login(ADMIN_USERNAME)
+
+ rv1a = self._activity(dashboard_uuid, page="0", page_size="25")
+ rv1b = self._activity(dashboard_uuid, page="0", page_size="25")
+ rv2 = self._activity(dashboard_uuid, page="1", page_size="25")
+ assert rv1a.status_code == 200
+ assert rv1b.status_code == 200
+ assert rv2.status_code == 200
+
+ page0_first = _json.loads(rv1a.data.decode("utf-8"))["result"]
+ page0_second = _json.loads(rv1b.data.decode("utf-8"))["result"]
+ page1 = _json.loads(rv2.data.decode("utf-8"))["result"]
+
+ # (a) Request determinism: same page twice → same records in same
+ # order. Use (entity_kind, entity_id_internal_proxy, tx, seq)
+ # fingerprint — entity_uuid + transaction_id is sufficient
+ # since entity_id isn't in the API contract.
+ fingerprint = lambda r: ( # noqa: E731
+ r["entity_kind"],
+ r["entity_uuid"],
+ r["transaction_id"],
+ r["kind"],
+ tuple(r["path"]) if r["path"] else (),
+ )
+ assert [fingerprint(r) for r in page0_first] == [
+ fingerprint(r) for r in page0_second
+ ], "page=0 fired twice returned different records"
+
+ # (b) Page 0 and page 1 are disjoint under one request round.
+ page0_keys = {fingerprint(r) for r in page0_first}
+ page1_keys = {fingerprint(r) for r in page1}
+ overlap = page0_keys & page1_keys
+ assert not overlap, f"page=0 and page=1 returned overlapping records: {overlap}"
+
+ @pytest.mark.skip(
+ reason="Restore endpoint ships in a later PR; re-enable when restore "
+ "lands. The activity layer's restore-event rendering is unit-tested."
+ )
+ def test_activity_surfaces_dashboard_restore_event(self) -> None:
+ """T044 / AV-015: restoring a dashboard to a prior version surfaces
+ a synthetic ``kind='__meta__'`` headline record (path
+ ``['__meta__', 'restore']``, ``to_value`` carrying the restored-to
+ version_uuid) in the dashboard's own activity stream
+ (``source='self'``). The headline is emitted by the restore
+ command via the listener's ACTION_META_KEY (PR #40988 feedback);
+ the activity layer passes it through without special-casing.
+
+ Uses a fresh dashboard: the shared fixture dashboard accumulates
+ membership history on a persistent DB, so its restore transaction
+ can carry more records than one page — burying the headline
+ (sequence 0 sorts last under the stream's sequence-DESC order).
+ """
+ _persist_fixture_state()
+ dashboard = Dashboard(
+ dashboard_title=f"restore probe {uuid4().hex[:8]}", published=False
+ )
+ db.session.add(dashboard)
+ db.session.commit()
+ dashboard_uuid = str(dashboard.uuid)
+ dashboard_id = dashboard.id
+ original_title = dashboard.dashboard_title
+
+ try:
+ # Two edits → at least two restorable prior versions.
+ dashboard.dashboard_title = f"{original_title} v1"
+ db.session.commit()
+ dashboard.dashboard_title = f"{original_title} v2"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ # Find a prior version to restore to (version_number 0 is the
+ # baseline; we restore to whichever earlier version the list
+ # endpoint surfaces).
+ versions_rv = self.client.get(
+ f"/api/v1/dashboard/{dashboard_uuid}/versions/"
+ )
+ assert versions_rv.status_code == 200, versions_rv.data
+ versions = _json.loads(versions_rv.data.decode("utf-8"))["result"]
+ assert len(versions) >= 2, f"expected ≥2 versions, got {versions}"
+ target_version_uuid = versions[0]["version_uuid"] # earliest
+
+ # Restore. The endpoint commits; finally clean up below.
+ restore_rv = self.client.post(
+ f"/api/v1/dashboard/{dashboard_uuid}"
+ f"/versions/{target_version_uuid}/restore"
+ )
+ assert restore_rv.status_code == 200, restore_rv.data
+
+ # Activity stream should now show the restore headline on the
+ # dashboard itself.
+ rv = self._activity(dashboard_uuid, include="self")
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ restore_records = [
+ r
+ for r in body["result"]
+ if r["kind"] == "__meta__"
+ and r["path"] == ["__meta__"]
+ and r["entity_kind"] == "dashboard"
+ ]
+ assert restore_records, (
+ "Expected a __meta__ restore headline record; "
+ f"got kinds: {[r['kind'] for r in body['result'][:10]]}"
+ )
+ assert restore_records[0]["to_value"]["version_uuid"] == target_version_uuid
+ # The headline is the one self record whose summary renders:
+ # "restored to version N" must be visible on include=self.
+ assert "restored to version" in restore_records[0]["summary"]
+ finally:
+ db.session.rollback()
+ dashboard = (
+ db.session.query(Dashboard)
+ .filter(Dashboard.id == dashboard_id)
+ .one_or_none()
+ )
+ if dashboard is not None:
+ db.session.delete(dashboard)
+ db.session.commit()
+
+ def test_activity_marks_first_tracked_save(self) -> None:
+ """Every record carries ``first_tracked_save``: True only on the
+ entity's FIRST tracked save. Clients collapse such transactions —
+ a legacy chart's first Explore save can replay ~74 params-
+ normalization deltas against the retroactive baseline
+ (PR #40988 feedback).
+
+ Uses a fresh dashboard so the entity's history is fully
+ controlled by this test (the shared fixture dashboard's first
+ save belongs to whichever suite ran first on a persistent DB).
+ """
+ _persist_fixture_state()
+ dashboard = Dashboard(
+ dashboard_title=f"fts probe {uuid4().hex[:8]}", published=False
+ )
+ db.session.add(dashboard)
+ db.session.commit() # op=0 INSERT baseline — no change records
+ dashboard_uuid = str(dashboard.uuid)
+ dashboard_id = dashboard.id
+
+ try:
+ dashboard.dashboard_title = f"{dashboard.dashboard_title} v1"
+ db.session.commit() # first tracked save
+ dashboard.dashboard_title = f"{dashboard.dashboard_title} v2"
+ db.session.commit() # second save
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid, include="self")
+ assert rv.status_code == 200
+ records = _json.loads(rv.data.decode("utf-8"))["result"]
+ assert len(records) >= 2
+ assert all("first_tracked_save" in r for r in records), (
+ "every record must carry the first_tracked_save marker"
+ )
+ # Newest-first ordering: the latest save (v2) is never the
+ # entity's first tracked save.
+ assert records[0]["first_tracked_save"] is False
+ # The v1 save's transaction IS flagged. Assert by transaction
+ # rather than stream position: under id reuse on a persistent
+ # test DB the stream can also carry a previously-deleted
+ # entity's records for the same integer id (the marker itself
+ # is uuid-aware and immune; the stream's positional tail is
+ # not).
+ flagged_txs = {
+ r["transaction_id"] for r in records if r["first_tracked_save"]
+ }
+ assert flagged_txs, "no record flagged as the first tracked save"
+ newest_tx = records[0]["transaction_id"]
+ assert newest_tx not in flagged_txs
+ finally:
+ db.session.rollback()
+ dashboard = (
+ db.session.query(Dashboard)
+ .filter(Dashboard.id == dashboard_id)
+ .one_or_none()
+ )
+ if dashboard is not None:
+ db.session.delete(dashboard)
+ db.session.commit()
+
+ def test_activity_q_filters_server_side(self) -> None:
+ """``?q=`` searches the FULL history server-side, pre-pagination
+ (PR #40988: the panel's client-side search only covered loaded
+ pages); ``count`` reflects the matches."""
+ _persist_fixture_state()
+ dashboard = _get_birth_names_dashboard()
+ assert dashboard is not None
+ dashboard_uuid = str(dashboard.uuid)
+ dashboard_id = dashboard.id
+ original_title = dashboard.dashboard_title
+ needle = f"qprobe{uuid4().hex[:6]}"
+
+ try:
+ dashboard.dashboard_title = f"{original_title} {needle}"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dashboard_uuid, q=needle)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ assert body["count"] >= 1
+ assert all(needle in _json.dumps(r).lower() for r in body["result"]), (
+ f"non-matching record returned for q={needle!r}"
+ )
+
+ # A needle that matches nothing returns an empty, zero-count
+ # envelope — not an error.
+ rv_none = self._activity(dashboard_uuid, q="zz-no-such-needle-zz")
+ body_none = _json.loads(rv_none.data.decode("utf-8"))
+ assert body_none == {"result": [], "count": 0, "truncated": False}
+ finally:
+ db.session.rollback()
+ dashboard = (
+ db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+ )
+ dashboard.dashboard_title = original_title
+ db.session.commit()
+
+
+class TestChartActivityView(SupersetTestCase):
+ """T028–T032 — ``GET /api/v1/chart/<uuid>/activity/`` (US2).
+
+ Chart activity = chart's own edits + datasets the chart pointed at
+ during association. **No** dashboard records — even when the chart
+ is on a dashboard, sibling-traversal is excluded per the spec's
+ Relationship Traversal section (T032).
+ """
+
+ @pytest.fixture(autouse=True)
+ def _load_data(self, load_birth_names_dashboard_with_slices): # noqa: PT004, F811
+ pass
+
+ def _activity(self, chart_uuid: str, **query: Any) -> Any:
+ return self.client.get(
+ f"/api/v1/chart/{chart_uuid}/activity/",
+ query_string=query,
+ )
+
+ def _get_birth_names_chart(self) -> Slice:
+ return db.session.query(Slice).filter(Slice.slice_name == "Girls").first()
+
+ # ---- 4xx boundary cases ----
+
+ def test_chart_activity_returns_404_for_unknown_uuid(self) -> None:
+ self.login(ADMIN_USERNAME)
+ rv = self._activity("00000000-0000-0000-0000-000000000000")
+ assert rv.status_code == 404
+
+ def test_chart_activity_returns_400_for_invalid_uuid(self) -> None:
+ self.login(ADMIN_USERNAME)
+ rv = self._activity("not-a-uuid")
+ assert rv.status_code == 400
+
+ def test_chart_activity_returns_400_for_invalid_include(self) -> None:
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ assert chart is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(chart.uuid), include="upstream")
+ assert rv.status_code == 400
+
+ def test_chart_activity_allows_read_non_owner(self) -> None:
+ """Same shape as the dashboard endpoint: a read-access non-owner
+ (Alpha) can read a chart's activity, so ``raise_for_access(chart=)``
+ does not reject and the endpoint returns 200."""
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ assert chart is not None
+ self.login(ALPHA_USERNAME)
+ rv = self._activity(str(chart.uuid))
+ assert rv.status_code == 200
+
+ # ---- 200 happy paths ----
+
+ def test_chart_activity_returns_200_with_envelope_shape(self) -> None:
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ assert chart is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(chart.uuid))
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ assert isinstance(body["result"], list)
+ assert isinstance(body["count"], int)
+
+ def test_chart_activity_self_edit_appears_as_self_record(self) -> None:
+ """Editing the chart itself surfaces a ``source=self``,
+ ``entity_kind=Slice`` record."""
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ assert chart is not None
+ chart_id = chart.id
+ chart_uuid = str(chart.uuid)
+ original_name = chart.slice_name
+
+ try:
+ chart.slice_name = f"{original_name} (edited self)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(chart_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ self_records = [
+ r
+ for r in body["result"]
+ if r["entity_kind"] == "chart" and r["source"] == "self"
+ ]
+ got = [(r["entity_kind"], r["source"]) for r in body["result"]]
+ assert self_records, (
+ f"Expected ≥1 Slice/self record from the chart edit; got: {got}"
+ )
+ finally:
+ db.session.rollback()
+ chart = db.session.query(Slice).filter(Slice.id == chart_id).one()
+ chart.slice_name = original_name
+ db.session.commit()
+
+ def test_chart_activity_includes_dataset_edit_as_related(self) -> None:
+ """T030 / AS-1 of US2: editing the chart's dataset surfaces a
+ ``source=related``, ``entity_kind=SqlaTable`` record."""
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ dataset = _get_birth_names_dataset()
+ assert chart is not None
+ assert dataset is not None
+ chart_uuid = str(chart.uuid)
+ dataset_id = dataset.id
+ original_description = dataset.description
+
+ try:
+ dataset.description = "edited for activity-view test"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(chart_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ related = [
+ r
+ for r in body["result"]
+ if r["entity_kind"] == "dataset" and r["source"] == "related"
+ ]
+ assert related, (
+ "Expected at least one SqlaTable/related record from the "
+ "dataset edit; got: "
+ f"{[(r['entity_kind'], r['source']) for r in body['result']]}"
+ )
+ finally:
+ db.session.rollback()
+ dataset = (
+ db.session.query(SqlaTable).filter(SqlaTable.id == dataset_id).one()
+ )
+ dataset.description = original_description
+ db.session.commit()
+
+ def test_chart_activity_excludes_sibling_dashboards(self) -> None:
+ """T032: Even when the chart is on a dashboard, dashboard edits
+ do NOT appear in the chart's activity. Per the spec's Relationship
+ Traversal section: charts don't see "sideways" to the dashboards
+ they happen to be on."""
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ dashboard = _get_birth_names_dashboard()
+ assert chart is not None
+ assert dashboard is not None
+ chart_uuid = str(chart.uuid)
+ dashboard_id = dashboard.id
+ original_title = dashboard.dashboard_title
+
+ try:
+ # Mutate the dashboard the chart is on — that edit MUST NOT
+ # appear in the chart's activity stream.
+ dashboard.dashboard_title = f"{original_title} (edited sibling)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(chart_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ for record in body["result"]:
+ assert record["entity_kind"] != "dashboard", (
+ f"Dashboard edit leaked into chart's activity stream: {record}"
+ )
+ finally:
+ db.session.rollback()
+ dashboard = (
+ db.session.query(Dashboard).filter(Dashboard.id == dashboard_id).one()
+ )
+ dashboard.dashboard_title = original_title
+ db.session.commit()
+
+ def test_chart_activity_include_self_excludes_related(self) -> None:
+ """``?include=self`` filters out the dataset records."""
+ _persist_fixture_state()
+ chart = self._get_birth_names_chart()
+ dataset = _get_birth_names_dataset()
+ assert chart is not None
+ assert dataset is not None
+ chart_uuid = str(chart.uuid)
+ dataset_id = dataset.id
+ original_description = dataset.description
+
+ try:
+ dataset.description = "edited (self filter test)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(chart_uuid, include="self")
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ for record in body["result"]:
+ assert record["source"] == "self"
+ assert record["entity_kind"] == "chart"
+ finally:
+ db.session.rollback()
+ dataset = (
+ db.session.query(SqlaTable).filter(SqlaTable.id == dataset_id).one()
+ )
+ dataset.description = original_description
+ db.session.commit()
+
+
+class TestDatasetActivityView(SupersetTestCase):
+ """T033–T036 — ``GET /api/v1/dataset/<uuid>/activity/`` (US3).
+
+ Dataset activity = dataset's own edits only. **No** transitive layer
+ in V2 (AV-004) — even when charts use the dataset, those chart edits
+ do NOT appear here. ``?include=related`` and ``?include=all``
+ collapse to the same self-only stream as ``?include=self``.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _load_data(self, load_birth_names_dashboard_with_slices): # noqa: PT004, F811
+ pass
+
+ def _activity(self, dataset_uuid: str, **query: Any) -> Any:
+ return self.client.get(
+ f"/api/v1/dataset/{dataset_uuid}/activity/",
+ query_string=query,
+ )
+
+ # ---- 4xx boundary cases ----
+
+ def test_dataset_activity_returns_404_for_unknown_uuid(self) -> None:
+ self.login(ADMIN_USERNAME)
+ rv = self._activity("00000000-0000-0000-0000-000000000000")
+ assert rv.status_code == 404
+
+ def test_dataset_activity_returns_400_for_invalid_uuid(self) -> None:
+ self.login(ADMIN_USERNAME)
+ rv = self._activity("not-a-uuid")
+ assert rv.status_code == 400
+
+ def test_dataset_activity_returns_400_for_invalid_include(self) -> None:
+ _persist_fixture_state()
+ dataset = _get_birth_names_dataset()
+ assert dataset is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dataset.uuid), include="upstream")
+ assert rv.status_code == 400
+
+ def test_dataset_activity_allows_read_non_owner(self) -> None:
+ """A read-access non-owner (Alpha) can read a dataset's activity
+ stream, so the read endpoint returns 200."""
+ _persist_fixture_state()
+ dataset = _get_birth_names_dataset()
+ assert dataset is not None
+ self.login(ALPHA_USERNAME)
+ rv = self._activity(str(dataset.uuid))
+ assert rv.status_code == 200
+
+ # ---- 200 happy paths ----
+
+ def test_dataset_activity_returns_200_with_envelope_shape(self) -> None:
+ _persist_fixture_state()
+ dataset = _get_birth_names_dataset()
+ assert dataset is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dataset.uuid))
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ assert isinstance(body["result"], list)
+ assert isinstance(body["count"], int)
+
+ def test_dataset_activity_includes_dataset_self_edits(self) -> None:
+ """T036: the dataset's own scalar edits appear as ``source=self``,
+ ``entity_kind=SqlaTable``."""
+ _persist_fixture_state()
+ dataset = _get_birth_names_dataset()
+ assert dataset is not None
+ dataset_id = dataset.id
+ dataset_uuid = str(dataset.uuid)
+ original_description = dataset.description
+
+ try:
+ dataset.description = "edited self for dataset activity"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dataset_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ self_records = [
+ r
+ for r in body["result"]
+ if r["entity_kind"] == "dataset" and r["source"] == "self"
+ ]
+ got = [(r["entity_kind"], r["source"]) for r in body["result"]]
+ assert self_records, (
+ f"Expected ≥1 SqlaTable/self record from the dataset edit; got: {got}"
+ )
+ finally:
+ db.session.rollback()
+ dataset = (
+ db.session.query(SqlaTable).filter(SqlaTable.id == dataset_id).one()
+ )
+ dataset.description = original_description
+ db.session.commit()
+
+ def test_dataset_activity_excludes_chart_edits(self) -> None:
+ """T035 / AS-1 / AV-004: When a chart that uses the dataset is
+ edited, that edit does NOT appear in the dataset's activity stream.
+ Datasets are read-only upstream in V2."""
+ _persist_fixture_state()
+ dataset = _get_birth_names_dataset()
+ chart = db.session.query(Slice).filter(Slice.slice_name == "Girls").first()
+ assert dataset is not None
+ assert chart is not None
+ dataset_uuid = str(dataset.uuid)
+ chart_id = chart.id
+ chart_original_name = chart.slice_name
+
+ try:
+ # Edit the chart — generates a Slice change record. The
+ # dataset's activity MUST NOT surface it.
+ chart.slice_name = f"{chart_original_name} (edited from dataset test)"
+ db.session.commit()
+
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(dataset_uuid)
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ for record in body["result"]:
+ assert record["entity_kind"] == "dataset", (
+ "Non-dataset record leaked into dataset's activity "
+ f"stream: {record}"
+ )
+ assert record["source"] == "self", (
+ f"Dataset activity contains a related record: {record}"
+ )
+ finally:
+ db.session.rollback()
+ chart = db.session.query(Slice).filter(Slice.id == chart_id).one()
+ chart.slice_name = chart_original_name
+ db.session.commit()
+
+ def test_dataset_activity_related_only_returns_empty(self) -> None:
+ """AV-004: datasets have no transitive layer. ``?include=related``
+ returns an empty result list because there are no related entities
+ to draw from."""
+ _persist_fixture_state()
+ dataset = _get_birth_names_dataset()
+ assert dataset is not None
+ self.login(ADMIN_USERNAME)
+ rv = self._activity(str(dataset.uuid), include="related")
+ assert rv.status_code == 200
+ body = _json.loads(rv.data.decode("utf-8"))
+ assert body["result"] == []
+ assert body["count"] == 0
+
+
+class TestActivityOpenApiSpec(SupersetTestCase):
+ """T049 — confirm the three ``/activity/`` endpoints are surfaced by
+ FAB-generated OpenAPI at ``/api/v1/_openapi``.
+
+ ``base_api_tests.py::TestOpenApiSpec::test_open_api_spec`` already
+ validates the full spec's YAML correctness on every CI run. This
+ class adds activity-specific assertions: the paths exist, are
+ documented with the expected query parameters, and reference an
+ ``ActivityResponse``-shaped 200 response.
+ """
+
+ def _spec(self) -> dict[str, Any]:
+ self.login(ADMIN_USERNAME)
+ rv = self.client.get("/api/v1/_openapi")
+ assert rv.status_code == 200, rv.status_code
+ return _json.loads(rv.data.decode("utf-8"))
+
+ def test_three_activity_paths_appear_in_openapi(self) -> None:
+ """One path per endpoint family. Paths are keyed by the URL
+ template, not the method name, so the FAB-generated keys are
+ the ``/<uuid_str>/activity/`` route templates."""
+ spec = self._spec()
+ paths = spec.get("paths", {})
+ # FAB templates the path-arg as ``{uuid_str}`` in the OpenAPI dict.
+ expected = {
+ "/api/v1/dashboard/{uuid_str}/activity/",
+ "/api/v1/chart/{uuid_str}/activity/",
+ "/api/v1/dataset/{uuid_str}/activity/",
+ }
+ missing = expected - paths.keys()
+ assert not missing, f"missing activity paths in OpenAPI: {missing}"
+
+ def test_activity_endpoints_document_query_params(self) -> None:
+ """Each endpoint declares since / until / include / page /
+ page_size as query parameters. Spot-check on the dashboard
+ endpoint — the YAML docstring is the same shape across all
+ three so this assertion is sufficient."""
+ spec = self._spec()
+ op = spec["paths"]["/api/v1/dashboard/{uuid_str}/activity/"]["get"]
+ params = {p["name"]: p for p in op.get("parameters", [])}
+ for expected in ("since", "until", "include", "page", "page_size"):
+ assert expected in params, (
+ f"query param {expected!r} missing from dashboard /activity/"
+ )
+ # include enum is the published contract — verify it's correct.
+ include_param = params["include"]
+ assert include_param["in"] == "query"
+ assert set(include_param["schema"]["enum"]) == {"self", "related", "all"}
+
+ def test_activity_endpoints_declare_200_response(self) -> None:
+ """Each endpoint declares a 200 response. The exact schema
+ reference depends on how FAB resolves ``schema: ActivityResponseSchema``
+ in the YAML docstring; here we just confirm the 200 + the 4xx
+ error responses are all present."""
+ spec = self._spec()
+ op = spec["paths"]["/api/v1/dashboard/{uuid_str}/activity/"]["get"]
+ responses = op.get("responses", {})
+ for code in ("200", "400", "401", "403", "404"):
+ assert code in responses, (
+ f"response code {code} missing on dashboard /activity/"
+ )
diff --git a/tests/integration_tests/versioning/change_records_tests.py b/tests/integration_tests/versioning/change_records_tests.py
new file mode 100644
index 00000000000..56a9bee44f6
--- /dev/null
+++ b/tests/integration_tests/versioning/change_records_tests.py
@@ -0,0 +1,718 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Integration tests for ``version_changes`` capture (T052, partial).
+
+Covers in this file:
+ (a) saving a chart with three field changes produces three rows
+ (f) baseline / INSERT transactions produce zero records *for that entity*
+ + unchanged-save / dashboard / params-classification cases
+
+Deferred:
+ (b) ``GET /versions/`` response includes ``changes`` array — lands with
+ T050 (API integration).
+ (c) FK cascade — exercisable in principle (the migration declares
+ ``ON DELETE CASCADE``) but can't be isolated in a unit-style test
+ because ``version_transaction`` is referenced by non-cascading FKs
+ from slices_version / dashboards_version / etc. Covered instead
+ by (d) below once it lands, and by the structural declaration in
+ T046's migration.
+ (d) retention prune drops change records alongside the pruned
+ version — will land when T049 extends ``VersionDAO.prune_versions``
+ to include ``version_changes`` alongside the shadow-row delete.
+ (e) ``kind`` index query plan on Postgres — deferred to T053 perf
+ validation.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+from typing import Any
+from uuid import uuid4
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy_continuum import version_class
+
+from superset.extensions import db
+from superset.models.dashboard import Dashboard
+from superset.models.slice import Slice
+from superset.utils import json as _json
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.fixtures.birth_names_dashboard import ( # noqa: F401
+ load_birth_names_dashboard_with_slices,
+ load_birth_names_data,
+)
+
+_VERSION_CHANGES = sa.table(
+ "version_changes",
+ sa.column("id"),
+ sa.column("transaction_id"),
+ sa.column("entity_kind"),
+ sa.column("entity_id"),
+ sa.column("sequence"),
+ sa.column("kind"),
+ sa.column("operation"),
+ sa.column("path"),
+ sa.column("from_value"),
+ sa.column("to_value"),
+)
+
+_VERSION_TRANSACTION = sa.table(
+ "version_transaction",
+ sa.column("id"),
+ sa.column("issued_at"),
+ sa.column("user_id"),
+ sa.column("action_kind"),
+)
+
+
+def _action_kind_for(tx_id: int) -> str | None:
+ """Read the ``action_kind`` column from the version_transaction row."""
+ return (
+ db.session.connection()
+ .execute(
+ sa.select(_VERSION_TRANSACTION.c.action_kind).where(
+ _VERSION_TRANSACTION.c.id == tx_id
+ )
+ )
+ .scalar()
+ )
+
+
+def _change_rows_for(
+ tx_id: int,
+ *,
+ entity_kind: str | None = None,
+ entity_id: int | None = None,
+) -> list[dict[str, Any]]:
+ """Raw fetch of ``version_changes`` rows for a tx + optional entity filter."""
+ query = sa.select(_VERSION_CHANGES).where(
+ _VERSION_CHANGES.c.transaction_id == tx_id
+ )
+ if entity_kind is not None:
+ query = query.where(_VERSION_CHANGES.c.entity_kind == entity_kind)
+ if entity_id is not None:
+ query = query.where(_VERSION_CHANGES.c.entity_id == entity_id)
+ query = query.order_by(_VERSION_CHANGES.c.sequence.asc())
+ result = db.session.connection().execute(query)
+ return [dict(row._mapping) for row in result]
+
+
+def _persist_fixture_state() -> None:
+ """Commit fixture INSERTs so the baseline row exists before the test edits.
+
+ Without this, the test's first commit batches the fixture's pending
+ INSERTs with the test's UPDATE into a single Continuum transaction
+ and no diff records are emitted (no pre-state).
+ """
+ db.session.commit()
+
+
+class TestChartChangeRecords(SupersetTestCase):
+ """Change-record capture for chart (Slice) saves."""
+
+ @pytest.fixture(autouse=True)
+ def _load_data( # noqa: F811, PT004
+ self,
+ load_birth_names_dashboard_with_slices: Any, # noqa: F811
+ ) -> None:
+ pass
+
+ def test_single_scalar_edit_produces_one_change_record(self) -> None:
+ """(a) — one field changed, one ``version_changes`` row."""
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+ chart.slice_name = f"{chart.slice_name[:64]}_renamed"
+ db.session.commit()
+
+ # The save produces one new version row (the UPDATE). Fetch its tx_id.
+ ver_cls = version_class(Slice)
+ update_tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+
+ rows = _change_rows_for(update_tx_id, entity_kind="chart", entity_id=chart.id)
+ assert len(rows) == 1
+ assert rows[0]["kind"] == "field"
+ path = (
+ _json.loads(rows[0]["path"])
+ if isinstance(rows[0]["path"], str)
+ else rows[0]["path"]
+ )
+ assert path == ["slice_name"]
+ assert rows[0]["sequence"] == 0
+
+ def test_last_saved_at_is_excluded_as_audit_noise(self) -> None:
+ """``last_saved_at`` / ``last_saved_by_fk`` are save-side-effect
+ fields stamped by ``UpdateChartCommand`` and must not produce
+ change records — same category as ``changed_on``.
+
+ Saving a chart with ONLY a ``last_saved_at`` bump must produce
+ zero ``version_changes`` rows for that transaction. (Continuum
+ still records the shadow row; we just don't want to noise up
+ the per-edit diff log.)
+ """
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+ chart.last_saved_at = datetime.now() + timedelta(seconds=1)
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ latest_tx = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ )
+ # If the save produced no version row at all (no actual model
+ # change beyond the audit field), nothing to assert. If it did,
+ # there must be no ``last_saved_at`` row in version_changes.
+ if latest_tx is None:
+ return
+ rows = _change_rows_for(
+ latest_tx.transaction_id, entity_kind="chart", entity_id=chart.id
+ )
+ paths = [
+ _json.loads(r["path"]) if isinstance(r["path"], str) else r["path"]
+ for r in rows
+ ]
+ assert ["last_saved_at"] not in paths
+ assert ["last_saved_by_fk"] not in paths
+
+ def test_three_scalar_edits_produce_three_records_in_sequence(self) -> None:
+ """(a) — three fields changed, three rows, ``sequence`` 0..2."""
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+ # Derive from CURRENT values so every run guarantees a real
+ # change even against a persistent test DB where prior runs
+ # have already mutated the chart.
+ chart.slice_name = f"{chart.slice_name[:60]}_x"
+ chart.description = f"{chart.description or ''}_x"
+ chart.cache_timeout = (chart.cache_timeout or 0) + 1
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ update_tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ rows = _change_rows_for(update_tx_id, entity_kind="chart", entity_id=chart.id)
+ assert len(rows) == 3
+ assert [r["sequence"] for r in rows] == [0, 1, 2]
+ # Sorted by field name (diff engine emits in sorted field order)
+ paths = [
+ _json.loads(r["path"]) if isinstance(r["path"], str) else r["path"]
+ for r in rows
+ ]
+ assert paths == [["cache_timeout"], ["description"], ["slice_name"]]
+
+ def test_params_filter_add_produces_filter_kind_record(self) -> None:
+ """(a) — params classification still flows through the listener.
+
+ Adds an adhoc_filter with a per-run-unique natural key
+ (``subject``): the filter differ keys on ``subject``, so a
+ STABLE subject is only "new" on the first run against a
+ persistent DB — every later run re-appends an already-present
+ key and the keyed diff emits nothing. Whatever was in
+ ``adhoc_filters`` before stays; we only want to confirm at
+ least one ``kind='filter'`` record is emitted.
+ """
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+ unique_subject = f"col_{chart.id}_{uuid4().hex[:8]}"
+ params = _json.loads(chart.params or "{}")
+ existing = params.get("adhoc_filters", []) or []
+ params["adhoc_filters"] = [
+ *existing,
+ {
+ "subject": unique_subject,
+ "operator": "==",
+ "comparator": "x",
+ "expressionType": "SIMPLE",
+ },
+ ]
+ chart.params = _json.dumps(params)
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ update_tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ rows = _change_rows_for(update_tx_id, entity_kind="chart", entity_id=chart.id)
+ filter_rows = [r for r in rows if r["kind"] == "filter"]
+ assert len(filter_rows) >= 1, (
+ f"expected at least one filter record, got rows: {rows}"
+ )
+
+ def test_unchanged_save_produces_zero_change_records(self) -> None:
+ """An edit that sets fields to identical values emits nothing."""
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ ver_cls = version_class(Slice)
+ # Capture the latest tx_id BEFORE this test's save so we can
+ # distinguish "the no-op save produced nothing new" (the intent)
+ # from "prior tests left tx rows with records on them" (noise).
+ pre_save_tx_row = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ )
+ pre_save_tx_id = pre_save_tx_row.transaction_id if pre_save_tx_row else 0
+
+ # Touch the object (mark dirty) but assign the same value.
+ current_name = chart.slice_name
+ chart.slice_name = current_name
+ db.session.commit()
+
+ post_save_tx_row = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .filter(ver_cls.transaction_id > pre_save_tx_id)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ )
+ # Either no new tx at all (nothing dirty, best case), or a new
+ # tx with zero change records for this chart.
+ if post_save_tx_row is not None:
+ assert (
+ _change_rows_for(
+ post_save_tx_row.transaction_id,
+ entity_kind="chart",
+ entity_id=chart.id,
+ )
+ == []
+ )
+
+ def test_perm_only_rewrite_produces_no_version(self) -> None:
+ """Bulk permission maintenance rewrites perm / schema_perm /
+ catalog_perm across many entities; the perm-string class is
+ derived security state, not user content, and is excluded from
+ ``__versioned__``. A commit touching ONLY those columns must
+ produce no shadow row at all — not even an empty transaction.
+ Regression for the phantom "Chart updated" flood the
+ version-history UI surfaced (PR #40988: one user save + 10
+ perm-rewrite ride-alongs rendered as 10 phantom rows).
+ """
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+ ver_cls = version_class(Slice)
+ original_name = chart.slice_name
+ original_perms = (chart.perm, chart.schema_perm, chart.catalog_perm)
+
+ try:
+ # Seed a baseline first: a real content edit guarantees the chart
+ # already has shadow rows, so the perm-only edit below can't be the
+ # event that triggers the *synthetic baseline* (which would
+ # otherwise create a shadow row and confound this assertion — the
+ # test must isolate "perm-only edit" from "first-ever version").
+ # This matters because the suite clears version tables between
+ # tests, so the chart may start with zero shadow rows.
+ chart.slice_name = f"{original_name} (baseline-seed)"
+ db.session.commit()
+
+ pre_save_tx_row = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ )
+ assert pre_save_tx_row is not None, "content edit should have versioned"
+ pre_save_tx_id = pre_save_tx_row.transaction_id
+
+ chart.perm = f"[seed].[perm_rewrite {uuid4().hex[:8]}]"
+ chart.schema_perm = f"[seed].[schema {uuid4().hex[:8]}]"
+ chart.catalog_perm = f"[seed].[catalog {uuid4().hex[:8]}]"
+ db.session.commit()
+
+ post_save_tx_row = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.transaction_id > pre_save_tx_id)
+ .first()
+ )
+ assert post_save_tx_row is None, (
+ "perm-only rewrite created a shadow row "
+ f"(tx {post_save_tx_row.transaction_id}); the perm-string "
+ "class must be excluded from versioning"
+ )
+ finally:
+ # Perm strings are security-routing state consulted by
+ # datasource-access checks; leaving random probe values on a
+ # persistent test DB breaks unrelated permission tests.
+ db.session.rollback()
+ chart = db.session.query(Slice).filter(Slice.id == chart.id).one()
+ chart.slice_name = original_name
+ chart.perm, chart.schema_perm, chart.catalog_perm = original_perms
+ db.session.commit()
+
+
+class TestDashboardChangeRecords(SupersetTestCase):
+ """Same flow for dashboards — all scalar fields land in ``kind='field'``."""
+
+ @pytest.fixture(autouse=True)
+ def _load_data(self, load_birth_names_dashboard_with_slices): # noqa: F811, PT004
+ pass
+
+ def test_dashboard_title_edit_produces_field_record(self) -> None:
+ _persist_fixture_state()
+
+ dashboard = db.session.query(Dashboard).first()
+ assert dashboard is not None
+ dashboard.dashboard_title = f"{dashboard.dashboard_title}_rev"
+ db.session.commit()
+
+ ver_cls = version_class(Dashboard)
+ update_tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == dashboard.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ rows = _change_rows_for(
+ update_tx_id, entity_kind="dashboard", entity_id=dashboard.id
+ )
+ assert len(rows) >= 1
+ field_rows = [r for r in rows if r["kind"] == "field"]
+ paths = [
+ _json.loads(r["path"]) if isinstance(r["path"], str) else r["path"]
+ for r in field_rows
+ ]
+ assert ["dashboard_title"] in paths
+
+
+class TestDatasetChildChangeRecords(SupersetTestCase):
+ """T048b — column and metric diff records for dataset saves.
+
+ Two snapshots must exist for any child diff to emit: the prior
+ save's and the current one. The fixture ``load_birth_names_data``
+ has already created the dataset before these tests run; their
+ first commit produces snapshot #1. The test's edit produces
+ snapshot #2, and the listener diffs the two.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _load_data(self, load_birth_names_dashboard_with_slices): # noqa: F811, PT004
+ pass
+
+ def test_column_description_change_produces_column_record(self) -> None:
+ # pylint: disable=import-outside-toplevel
+ from sqlalchemy_continuum import version_class
+
+ from superset.connectors.sqla.models import SqlaTable
+
+ _persist_fixture_state()
+
+ dataset = (
+ db.session.query(SqlaTable)
+ .filter(SqlaTable.table_name == "birth_names")
+ .first()
+ )
+ assert dataset is not None
+ assert dataset.columns, "birth_names fixture should produce columns"
+ # First save establishes snapshot #1 (the pre-edit state).
+ # Scalar + child diffs won't emit anything yet because there's
+ # no prior snapshot to diff against.
+ dataset.description = f"{dataset.description or ''}_v1"
+ db.session.commit()
+ # Second save: edit a column AND touch a dataset scalar so
+ # the parent SqlaTable ends up in session.dirty. In real
+ # flows DatasetDAO.update_columns() marks the parent via its
+ # individual session.add / session.delete calls (T011); the
+ # direct-ORM test here needs an explicit parent touch.
+ column = dataset.columns[0]
+ column.description = f"{column.description or ''}_edited"
+ dataset.description = f"{dataset.description}_v2"
+ db.session.commit()
+
+ ver_cls = version_class(SqlaTable)
+ latest_tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == dataset.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ rows = _change_rows_for(
+ latest_tx_id, entity_kind="dataset", entity_id=dataset.id
+ )
+ column_rows = [r for r in rows if r["kind"] == "column"]
+ assert len(column_rows) >= 1, (
+ f"expected at least one kind='column' record, got {rows}"
+ )
+
+
+class TestBaselineProducesZeroChangeRecords(SupersetTestCase):
+ """(f) — operation_type=0 (baseline / INSERT) transactions emit no records."""
+
+ @pytest.fixture(autouse=True)
+ def _load_data(self, load_birth_names_dashboard_with_slices): # noqa: F811, PT004
+ pass
+
+ def test_baseline_transaction_has_no_change_records_for_this_entity(
+ self,
+ ) -> None:
+ """(f) — baseline tx produces zero records *for that entity*.
+
+ A single transaction can touch multiple entities (fixture loads,
+ import pipelines). A tx that's a baseline for this chart might
+ still legitimately carry update records for some *other* entity
+ that shared the flush. The spec's M4 clarification means:
+ records filtered to this entity's (tx, entity_kind, entity_id)
+ are empty for its baseline tx.
+ """
+ _persist_fixture_state()
+
+ chart = db.session.query(Slice).first()
+ chart.slice_name = f"{chart.slice_name[:64]}_force_baseline"
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ rows_by_tx = (
+ db.session.query(ver_cls.transaction_id, ver_cls.operation_type)
+ .filter(ver_cls.id == chart.id)
+ .order_by(ver_cls.transaction_id.asc())
+ .all()
+ )
+ baseline_tx_ids = [tx for tx, op in rows_by_tx if op == 0]
+ assert baseline_tx_ids, "expected at least one baseline version row"
+
+ for tx_id in baseline_tx_ids:
+ records_for_this_chart = _change_rows_for(
+ tx_id, entity_kind="chart", entity_id=chart.id
+ )
+ assert records_for_this_chart == [], (
+ f"baseline tx {tx_id} unexpectedly has change records for "
+ f"chart id={chart.id}: {records_for_this_chart}"
+ )
+
+
+class TestTransactionActionKindPropagation(SupersetTestCase):
+ """Confirm ``version_transaction.action_kind`` is stamped when a
+ command declares one via ``session.info["_versioning_action_kind"]``,
+ and stays ``NULL`` on ordinary saves."""
+
+ @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
+ def test_ordinary_save_has_null_action_kind(self) -> None:
+ """No command sets the key → version_transaction.action_kind
+ is NULL for a normal user-initiated save."""
+ from superset.versioning.changes import ACTION_KIND_KEY
+
+ _persist_fixture_state()
+ # Sanity: the key shouldn't already be on the session.
+ assert ACTION_KIND_KEY not in db.session.info
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+ chart.slice_name = f"{chart.slice_name[:60]}_baseline"
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ assert _action_kind_for(tx_id) is None
+
+ @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
+ def test_session_info_action_kind_propagates_to_transaction(self) -> None:
+ """The listener reads ``session.info[ACTION_KIND_KEY]`` and
+ stamps it on the version_transaction row. Exercises the wiring
+ directly so we don't need a full end-to-end command run for the
+ propagation test (the per-command tests below cover the
+ calling side)."""
+ from superset.versioning.changes import ACTION_KIND_KEY
+
+ _persist_fixture_state()
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+
+ db.session.info[ACTION_KIND_KEY] = "restore"
+ chart.slice_name = f"{chart.slice_name[:60]}_trig"
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ assert _action_kind_for(tx_id) == "restore"
+
+ # And: the key is popped — next save resets to NULL action_kind.
+ assert ACTION_KIND_KEY not in db.session.info
+
+ @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
+ def test_action_kind_pops_so_next_save_is_clean(self) -> None:
+ """After the listener stamps the action_kind, subsequent saves
+ on the same session must not carry it forward."""
+ from superset.versioning.changes import ACTION_KIND_KEY
+
+ _persist_fixture_state()
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+
+ # First save with action_kind.
+ db.session.info[ACTION_KIND_KEY] = "import"
+ chart.slice_name = f"{chart.slice_name[:60]}_a"
+ db.session.commit()
+
+ # Second save without setting the key.
+ chart.slice_name = f"{chart.slice_name[:60]}_b"
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ # Get the two most-recent edit tx_ids.
+ rows = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .limit(2)
+ .all()
+ )
+ assert len(rows) == 2
+ second_tx, first_tx = rows[0].transaction_id, rows[1].transaction_id
+
+ assert _action_kind_for(first_tx) == "import"
+ assert _action_kind_for(second_tx) is None
+
+ @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
+ def test_action_kind_dropped_on_rollback(self) -> None:
+ """When a command sets ACTION_KIND_KEY and then an exception
+ fires before any flush stamps it (e.g. validation error after
+ the key is set), the value must not leak into the next save on
+ the same session. Regression for sqlalchemy-review C3."""
+ from superset.versioning.changes import ACTION_KIND_KEY
+
+ _persist_fixture_state()
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+
+ # Declare an action_kind, then force a rollback before the
+ # listener's flush stamps it.
+ db.session.info[ACTION_KIND_KEY] = "restore"
+ db.session.rollback()
+
+ # The after_rollback listener must have popped the key.
+ assert ACTION_KIND_KEY not in db.session.info
+
+ # And: a normal save now records NULL action_kind, not "restore".
+ chart.slice_name = f"{chart.slice_name[:60]}_postrollback"
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+ assert _action_kind_for(tx_id) is None
+
+ @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices")
+ def test_action_kind_survives_multiple_flushes_in_one_transaction(self) -> None:
+ """A restore/import can flush more than once before commit (an
+ explicit ``flush()`` or an autoflush from a mid-commit query). The
+ listener stamps ``action_kind`` *eagerly* on the first firing and
+ then dedups later firings of the same Continuum tx via the
+ ``_PROCESSED_TXS_KEY`` guard.
+
+ This pins the eager-stamp + dedup interaction: across two flushes
+ in a single transaction the action_kind lands exactly once on the
+ one tx that carries the change records, the key is popped (so it
+ can't leak to the next save), and the second flush does not
+ re-emit records (which would trip the UNIQUE(transaction_id,
+ entity_kind, entity_id, sequence) constraint). Regression for the
+ amin-review finding on stamp-before-short-circuit ordering.
+ """
+ from superset.versioning.changes import ACTION_KIND_KEY
+
+ _persist_fixture_state()
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+
+ # One transaction, two flushes: declare the action_kind, edit +
+ # flush (first after_flush firing stamps and persists), then edit
+ # again + commit (second firing for the same tx must short-circuit).
+ db.session.info[ACTION_KIND_KEY] = "restore"
+ chart.slice_name = f"{chart.slice_name[:60]}_f1"
+ db.session.flush()
+ chart.slice_name = f"{chart.slice_name[:60]}_f2"
+ db.session.commit()
+
+ ver_cls = version_class(Slice)
+ tx_id = (
+ db.session.query(ver_cls.transaction_id)
+ .filter(ver_cls.id == chart.id)
+ .filter(ver_cls.operation_type == 1)
+ .order_by(ver_cls.transaction_id.desc())
+ .first()
+ .transaction_id
+ )
+
+ # Stamped exactly once on the records-bearing tx, and popped.
+ assert _action_kind_for(tx_id) == "restore"
+ assert ACTION_KIND_KEY not in db.session.info
+ # Records exist for the tx and the dedup guard prevented a
+ # duplicate-sequence re-emit on the second flush.
+ rows = _change_rows_for(tx_id, entity_kind="chart", entity_id=chart.id)
+ assert rows, "expected change records on the multi-flush transaction"
+ sequences = [r["sequence"] for r in rows]
+ assert len(sequences) == len(set(sequences)), (
+ f"duplicate sequences on tx {tx_id}: {sequences}"
+ )
diff --git a/tests/integration_tests/versioning/perf_validation_tests.py b/tests/integration_tests/versioning/perf_validation_tests.py
new file mode 100644
index 00000000000..1fdd8e5531c
--- /dev/null
+++ b/tests/integration_tests/versioning/perf_validation_tests.py
@@ -0,0 +1,423 @@
+# 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.
+"""T044 — Performance validation for entity version history.
+
+Skipped by default. Run on demand:
+
+ SUPERSET_PERF_VALIDATION=1 pytest \
+ tests/integration_tests/versioning/perf_validation_tests.py -v -s
+
+Measures the three success criteria defined in the spec:
+
+ * SC-002: version list endpoint responds in under 1 second
+ * SC-004: save path p95 overhead under 50 ms with Continuum tracking
+ on vs. off (FR-014)
+
+(SC-003, the restore-endpoint benchmark, lands with the restore endpoint
+in a later PR.)
+
+The test prints a summary table suitable for pasting into the PR
+description. It also asserts each target so regressions fail loudly
+when the harness is re-run.
+"""
+
+from __future__ import annotations
+
+import os
+import statistics
+import time
+from typing import Any
+
+import pytest
+import sqlalchemy as sa
+from sqlalchemy_continuum import version_class, versioning_manager
+
+from superset.extensions import db
+from superset.models.slice import Slice
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.constants import ADMIN_USERNAME
+from tests.integration_tests.fixtures.birth_names_dashboard import ( # noqa: F401
+ load_birth_names_dashboard_with_slices,
+ load_birth_names_data,
+)
+
+SKIP_REASON = "Performance validation is manual. Set SUPERSET_PERF_VALIDATION=1 to run."
+
+# Thresholds from spec.md §Success Criteria.
+LIST_ENDPOINT_MAX_MS = 1000 # SC-002
+SAVE_OVERHEAD_P95_MAX_MS = 50 # SC-004
+
+# Activity-view thresholds (sc-107283 §Success Criteria).
+ACTIVITY_ENDPOINT_P95_MAX_MS = 1500 # SC-AV-001
+
+
+def _save_chart_once(chart: Slice, suffix: str) -> None:
+ """One ORM-level save path, mimicking what ChartDAO.update does."""
+ chart.slice_name = f"{chart.slice_name[:64]}_{suffix}"
+ db.session.commit()
+
+
+def _timings_ms(seconds: list[float]) -> dict[str, float]:
+ ms = sorted(s * 1000.0 for s in seconds)
+ return {
+ "p50": statistics.median(ms),
+ "p95": ms[int(len(ms) * 0.95) - 1] if len(ms) >= 20 else max(ms),
+ "max": max(ms),
+ "n": len(ms),
+ }
+
+
+@pytest.mark.skipif(
+ not os.environ.get("SUPERSET_PERF_VALIDATION"),
+ reason=SKIP_REASON,
+)
+class PerfValidationTests(SupersetTestCase):
+ """Runs only when SUPERSET_PERF_VALIDATION=1 is set."""
+
+ @pytest.fixture(autouse=True)
+ def _load_data(self, load_birth_names_dashboard_with_slices: Any) -> None: # noqa: F811, PT004
+ pass
+
+ def _seed_chart_with_n_versions(self, n: int) -> Slice:
+ """Save a chart N times to produce N version rows."""
+ chart = db.session.query(Slice).first()
+ assert chart is not None, "birth_names fixture should provide charts"
+
+ for i in range(n):
+ _save_chart_once(chart, f"v{i}")
+ db.session.commit()
+ return chart
+
+ def test_sc002_list_endpoint_under_1s(self) -> None:
+ """SC-002: list endpoint responds in under 1 second."""
+ self.login(ADMIN_USERNAME)
+
+ # Generate enough versions to exercise the retention-capped state.
+ chart = self._seed_chart_with_n_versions(24)
+ chart_uuid = str(chart.uuid)
+ url = f"/api/v1/chart/{chart_uuid}/versions/"
+
+ # Warm up the endpoint once (JIT caching, mapper configuration, etc.)
+ self.client.get(url)
+
+ timings: list[float] = []
+ for _ in range(10):
+ t0 = time.perf_counter()
+ response = self.client.get(url)
+ timings.append(time.perf_counter() - t0)
+ assert response.status_code == 200
+
+ stats = _timings_ms(timings)
+ print(
+ f"\n[SC-002] GET /versions/ (24 versions) "
+ f"p50={stats['p50']:.1f}ms p95={stats['p95']:.1f}ms "
+ f"max={stats['max']:.1f}ms n={stats['n']}"
+ )
+ assert stats["p95"] < LIST_ENDPOINT_MAX_MS, (
+ f"SC-002 failed: list endpoint p95 {stats['p95']:.1f}ms "
+ f">= {LIST_ENDPOINT_MAX_MS}ms"
+ )
+
+ # SC-003 (restore endpoint under 3s) intentionally omitted here: the
+ # version-restore route (POST /<uuid>/versions/<version_uuid>/restore)
+ # ships in a later PR, so there is nothing to time at this point in the
+ # stack. Re-add this benchmark alongside the restore endpoint.
+
+ def test_sc004_save_overhead_under_50ms(self) -> None:
+ """SC-004: save path p95 overhead under 50ms (FR-014).
+
+ Toggling Continuum on and off mid-process corrupts its internal
+ ``units_of_work`` state and is not a reliable measurement. Instead
+ this test directly measures the wall-clock time spent inside the
+ four session-level listeners Continuum attaches to
+ ``sa.orm.session.Session`` — ``before_flush``, ``after_flush``,
+ ``after_commit``, ``after_rollback`` — plus Superset's own
+ baseline / snapshot / retention-prune listeners (attached to
+ ``db.session``). The cumulative listener time per save is the
+ marginal overhead version capture adds over a save with
+ versioning removed entirely, because without these listeners
+ the ORM would not execute any of that code.
+
+ The approach:
+ 1. Wrap each known listener with a timing proxy that adds its
+ wall-clock time to a per-save accumulator.
+ 2. Save the same chart N times, recording each save's
+ accumulator value.
+ 3. Compute p50 / p95 of the per-save overhead.
+
+ The pass/fail gate uses full save latency, which includes both
+ Continuum's class-level listeners and Superset's listeners attached
+ to ``db.session``. The wrapped Continuum listeners remain a useful
+ diagnostic component without letting unmeasured listeners create a
+ false pass.
+ """
+ self.login(ADMIN_USERNAME)
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+
+ # Per-save accumulator incremented by the wrapped listeners.
+ acc: list[float] = [0.0]
+
+ def wrap_listener(original: Any) -> Any:
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ t0 = time.perf_counter()
+ try:
+ return original(*args, **kwargs)
+ finally:
+ acc[0] += time.perf_counter() - t0
+
+ wrapper.__wrapped__ = original # type: ignore[attr-defined]
+ return wrapper
+
+ # Instrument Continuum's four session listeners by detaching the
+ # bound method, wrapping, and re-attaching under a single-use
+ # listener handle we can cleanly remove on teardown.
+ session_target = sa.orm.session.Session
+ attached: list[tuple[str, Any]] = []
+ for event_name, listener in list(versioning_manager.session_listeners.items()):
+ sa.event.remove(session_target, event_name, listener)
+ wrapped = wrap_listener(listener)
+ sa.event.listen(session_target, event_name, wrapped)
+ attached.append((event_name, wrapped))
+
+ iterations: int = 100
+ warmup: int = 5
+ try:
+ # Warmup (first baseline INSERT, JIT, cache warming).
+ for i in range(warmup):
+ _save_chart_once(chart, f"warm_{i}")
+ acc[0] = 0.0
+
+ total_timings: list[float] = []
+ overhead_timings: list[float] = []
+ for i in range(iterations):
+ acc[0] = 0.0
+ t0 = time.perf_counter()
+ _save_chart_once(chart, f"run_{i}")
+ total_timings.append(time.perf_counter() - t0)
+ overhead_timings.append(acc[0])
+ finally:
+ for event_name, wrapped in attached:
+ sa.event.remove(session_target, event_name, wrapped)
+ sa.event.listen(
+ session_target,
+ event_name,
+ wrapped.__wrapped__,
+ )
+
+ total = _timings_ms(total_timings)
+ overhead = _timings_ms(overhead_timings)
+
+ ver_cls = version_class(Slice)
+ produced = db.session.query(ver_cls).filter(ver_cls.id == chart.id).count()
+ print(
+ f"\n[SC-004] save iterations={iterations} chart_id={chart.id} "
+ f"version_rows_produced={produced}"
+ )
+ print(
+ f"[SC-004] full save: "
+ f"p50={total['p50']:.2f}ms p95={total['p95']:.2f}ms "
+ f"max={total['max']:.2f}ms"
+ )
+ print(
+ f"[SC-004] version-cap overhead: "
+ f"p50={overhead['p50']:.2f}ms p95={overhead['p95']:.2f}ms "
+ f"max={overhead['max']:.2f}ms"
+ )
+
+ assert total["p95"] < SAVE_OVERHEAD_P95_MAX_MS, (
+ f"SC-004 failed: full save p95 "
+ f"{total['p95']:.2f}ms >= {SAVE_OVERHEAD_P95_MAX_MS}ms"
+ )
+
+ # ---- T045: Activity-view perf validation -----------------------------
+
+ def _seed_activity_history(self) -> str:
+ """Generate dense history on the birth_names dashboard so the
+ activity endpoint has something realistic to read.
+
+ T045's spec target is "25 charts × 3 dataset windows each". The
+ birth_names fixture has ~12 charts on a single dataset (no
+ multi-dataset support without a bespoke fixture). We approximate
+ the load by: (a) editing many charts on the dashboard, (b)
+ editing the dataset's description several times, (c) editing the
+ dashboard's own title once. That yields ~30+ change records
+ spanning all three entity kinds — enough to exercise the
+ decoration, visibility, and impact-batch paths without needing a
+ multi-dataset fixture builder. Returns the dashboard UUID.
+
+ **Why this commits without rollback** (unlike the test bodies in
+ ``activity_view_tests.py``): the whole point of a perf seed is
+ that the rows it produces have actually been persisted, so the
+ endpoint hit that follows reads a realistic state of the
+ ``version_changes`` / shadow tables. T053's
+ ``try/finally``+``rollback`` convention is for tests that
+ assert on *which records were captured*; here the seed IS the
+ setup, not the unit under test. The fixture's session-scoped
+ ``_cleanup`` removes the dashboard / slices at session teardown,
+ which is when the shadow rows age out too.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.connectors.sqla.models import SqlaTable
+ from superset.models.dashboard import Dashboard
+
+ dashboard = (
+ db.session.query(Dashboard)
+ .filter(Dashboard.dashboard_title.like("USA Births%"))
+ .first()
+ )
+ dataset: SqlaTable | None = (
+ db.session.query(SqlaTable)
+ .filter(SqlaTable.table_name == "birth_names")
+ .first()
+ )
+ assert dashboard is not None
+ assert dataset is not None
+ dashboard_uuid = str(dashboard.uuid)
+
+ # Many chart edits — most of the activity volume.
+ for chart in dashboard.slices[:12]:
+ chart.slice_name = f"{chart.slice_name[:48]}_perf"
+ db.session.commit()
+
+ # A handful of dataset edits — exercises the impact-batch path
+ # (Dashboard path + SqlaTable related).
+ for i in range(5):
+ dataset.description = f"perf seed iteration {i}"
+ db.session.commit()
+
+ # One dashboard self-edit.
+ dashboard.dashboard_title = f"{dashboard.dashboard_title}_perf"
+ db.session.commit()
+
+ return dashboard_uuid
+
+ def test_av_sc001_activity_endpoint_p95_under_1500ms(self) -> None:
+ """SC-AV-001: dashboard activity endpoint p95 < 1500ms across 50
+ invocations against a realistic history."""
+ self.login(ADMIN_USERNAME)
+
+ dashboard_uuid = self._seed_activity_history()
+ url = f"/api/v1/dashboard/{dashboard_uuid}/activity/"
+
+ # Warmup — JIT, mapper config, identity-map population.
+ for _ in range(3):
+ self.client.get(url)
+
+ timings: list[float] = []
+ for _ in range(50):
+ t0 = time.perf_counter()
+ response = self.client.get(url)
+ timings.append(time.perf_counter() - t0)
+ assert response.status_code == 200
+
+ stats = _timings_ms(timings)
+ body = response.get_json()
+ print(
+ f"\n[AV-SC-001] GET /dashboard/<uuid>/activity/ "
+ f"records_returned={len(body['result'])} count={body['count']}"
+ )
+ print(
+ f"[AV-SC-001] p50={stats['p50']:.1f}ms "
+ f"p95={stats['p95']:.1f}ms max={stats['max']:.1f}ms "
+ f"n={stats['n']}"
+ )
+ assert stats["p95"] < ACTIVITY_ENDPOINT_P95_MAX_MS, (
+ f"AV-SC-001 failed: activity endpoint p95 {stats['p95']:.1f}ms "
+ f">= {ACTIVITY_ENDPOINT_P95_MAX_MS}ms — profile the query "
+ f"plan and consider the T046 index migration (see "
+ f"specs/sc-107283/data-model.md §Possible additive indexes)"
+ )
+
+ def test_av_sc003_save_path_p95_unaffected_by_activity_view(self) -> None:
+ """AV-SC-003: the activity-view feature is read-only. Save path
+ p95 must remain within sc-103156's SC-004 budget (50ms version-
+ capture overhead) even with the activity tables in place.
+
+ We re-measure the same overhead SC-004 measures, with the
+ activity-view branch's code in scope, to catch any accidental
+ regression from a save-path coupling.
+ """
+ self.login(ADMIN_USERNAME)
+ # Seed some history so the M2M shadow + version_changes have
+ # enough rows that any pathological save-time read against them
+ # would surface.
+ self._seed_activity_history()
+
+ chart = db.session.query(Slice).first()
+ assert chart is not None
+
+ acc: list[float] = [0.0]
+
+ def wrap_listener(original: Any) -> Any:
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ t0 = time.perf_counter()
+ try:
+ return original(*args, **kwargs)
+ finally:
+ acc[0] += time.perf_counter() - t0
+
+ wrapper.__wrapped__ = original # type: ignore[attr-defined]
+ return wrapper
+
+ session_target = sa.orm.session.Session
+ attached: list[tuple[str, Any]] = []
+ for event_name, listener in list(versioning_manager.session_listeners.items()):
+ sa.event.remove(session_target, event_name, listener)
+ wrapped = wrap_listener(listener)
+ sa.event.listen(session_target, event_name, wrapped)
+ attached.append((event_name, wrapped))
+
+ iterations: int = 50
+ warmup: int = 3
+ try:
+ for i in range(warmup):
+ _save_chart_once(chart, f"av_warm_{i}")
+ acc[0] = 0.0
+
+ total_timings: list[float] = []
+ overhead_timings: list[float] = []
+ for i in range(iterations):
+ acc[0] = 0.0
+ t0: float = time.perf_counter()
+ _save_chart_once(chart, f"av_run_{i}")
+ total_timings.append(time.perf_counter() - t0)
+ overhead_timings.append(acc[0])
+ finally:
+ for event_name, wrapped in attached:
+ sa.event.remove(session_target, event_name, wrapped)
+ sa.event.listen(
+ session_target,
+ event_name,
+ wrapped.__wrapped__,
+ )
+
+ total: dict[str, float] = _timings_ms(total_timings)
+ overhead: dict[str, float] = _timings_ms(overhead_timings)
+ print(
+ f"\n[AV-SC-003] full save with activity-view in scope: "
+ f"p50={total['p50']:.2f}ms p95={total['p95']:.2f}ms "
+ f"max={total['max']:.2f}ms; "
+ f"Continuum component p95={overhead['p95']:.2f}ms"
+ )
+ assert total["p95"] < SAVE_OVERHEAD_P95_MAX_MS, (
+ f"AV-SC-003 failed: full save p95 "
+ f"{total['p95']:.2f}ms >= {SAVE_OVERHEAD_P95_MAX_MS}ms — "
+ f"the activity-view branch has regressed sc-103156's SC-004 "
+ f"budget; check for a new save-path read coupling."
+ )
diff --git a/tests/unit_tests/versioning/test_activity.py b/tests/unit_tests/versioning/test_activity.py
new file mode 100644
index 00000000000..01c87a39837
--- /dev/null
+++ b/tests/unit_tests/versioning/test_activity.py
@@ -0,0 +1,827 @@
+# 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 ``superset.versioning.activity`` pure helpers (sc-107283).
+
+No app context, no DB, no Flask. Covers the helpers that can be exercised
+in isolation: window intersection, scope resolution branching, entity-
+window merging, AV-012 summary headlines, ``changed_by`` projection,
+read-predicate fall-through, and the no-impact paths of
+``_compute_impact``. The DB-touching helpers
+(``charts_attached_to_dashboard``, ``datasets_used_by_chart``,
+``fetch_change_records``, ``apply_entity_name_denormalization``,
+``check_entity_tombstones``, ``_lookup_entity_uuids``) are exercised
+by the integration suite in
+``tests/integration_tests/versioning/activity_view_tests.py``.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from unittest.mock import patch
+from uuid import uuid4
+
+import pytest
+
+from superset.versioning.activity import (
+ ActivityParamsError,
+ EntityWindows,
+ parse_activity_query_params,
+ Window,
+)
+from superset.versioning.activity.impact import (
+ collect_impact_pairs,
+ impact_for_record,
+)
+from superset.versioning.activity.kinds import API_KIND_TO_TABLE, TABLE_KIND_TO_API
+from superset.versioning.activity.orchestrator import (
+ _DEFAULT_PAGE_SIZE,
+ _emit_request_shape_attributes,
+ _MAX_PAGE_SIZE,
+)
+from superset.versioning.activity.queries import (
+ _merge_result_into_heap,
+ _record_sort_key,
+ BoundedRecordHeap,
+)
+from superset.versioning.activity.render import (
+ _build_summary,
+ _changed_by_dict,
+ apply_record_decoration,
+)
+from superset.versioning.activity.scope import resolve_scope
+from superset.versioning.activity.windows import (
+ intersect_windows,
+ merge_entity_windows,
+ row_within_any_window,
+ union_windows,
+)
+
+# ---- intersect_windows ---------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "outer, inner, expected",
+ [
+ # Inner fully inside outer
+ (Window(10, 20), Window(15, 18), Window(15, 18)),
+ # Left overlap — clipped on the left
+ (Window(10, 20), Window(5, 15), Window(10, 15)),
+ # Right overlap — clipped on the right
+ (Window(10, 20), Window(15, 25), Window(15, 20)),
+ # Outer fully inside inner
+ (Window(10, 20), Window(5, 25), Window(10, 20)),
+ # Touching at end → half-open semantics yield disjoint
+ (Window(10, 20), Window(20, 30), None),
+ # Disjoint to the right
+ (Window(10, 20), Window(25, 30), None),
+ # Disjoint to the left
+ (Window(10, 20), Window(0, 5), None),
+ # Open-ended outer (end_tx=None means +∞)
+ (Window(10, None), Window(5, 25), Window(10, 25)),
+ # Open-ended inner
+ (Window(10, 20), Window(5, None), Window(10, 20)),
+ # Both open-ended
+ (Window(10, None), Window(5, None), Window(10, None)),
+ # Identical
+ (Window(10, 20), Window(10, 20), Window(10, 20)),
+ ],
+)
+def test_intersect_windows(
+ outer: Window, inner: Window, expected: Window | None
+) -> None:
+ assert intersect_windows(outer, inner) == expected
+
+
+# ---- resolve_scope -------------------------------------------------------
+
+
+def test_resolve_scope_self_only_for_dashboard() -> None:
+ """``include='self'`` yields exactly one tuple, bounded at the entity's
+ first tracked transaction."""
+ assert resolve_scope("Dashboard", 42, "self", 0) == [
+ ("Dashboard", 42, [Window(0, None)]),
+ ]
+
+
+def test_resolve_scope_self_window_bounded_at_first_tracked_tx() -> None:
+ """The self window starts at ``self_start_tx`` (the entity's first
+ tracked transaction), not 0 — so a reused integer id can't inherit a
+ hard-deleted predecessor's history."""
+ assert resolve_scope("Dashboard", 42, "self", 17) == [
+ ("Dashboard", 42, [Window(17, None)]),
+ ]
+
+
+def test_resolve_scope_self_empty_when_no_tracked_history() -> None:
+ """``self_start_tx=None`` (no shadow rows for this id+uuid yet) yields
+ no self window, so a reused id surfaces nothing from its predecessor."""
+ assert resolve_scope("Dashboard", 42, "self", None) == []
+ assert resolve_scope("Dashboard", 42, "self") == []
+
+
+def test_resolve_scope_related_empty_when_no_tracked_incarnation() -> None:
+ """A fresh entity reusing an integer id inherits no related history."""
+ with patch(
+ "superset.versioning.activity.scope._resolve_dashboard_scope"
+ ) as resolve_related:
+ assert resolve_scope("Dashboard", 42, "related", None) == []
+ resolve_related.assert_not_called()
+
+
+def test_resolve_scope_clips_related_windows_to_current_incarnation() -> None:
+ """Dependency windows from a reused path id start at its own first tx."""
+ with patch(
+ "superset.versioning.activity.scope._resolve_dashboard_scope",
+ return_value=[
+ ("Slice", 7, [Window(5, 15), Window(20, None)]),
+ ("SqlaTable", 9, [Window(1, 8)]),
+ ],
+ ):
+ assert resolve_scope("Dashboard", 42, "related", 10) == [
+ ("Slice", 7, [Window(10, 15), Window(20, None)]),
+ ]
+
+
+def test_resolve_scope_self_only_for_chart() -> None:
+ assert resolve_scope("Slice", 7, "self", 0) == [("Slice", 7, [Window(0, None)])]
+
+
+def test_resolve_scope_self_only_for_dataset() -> None:
+ assert resolve_scope("SqlaTable", 9, "self", 0) == [
+ ("SqlaTable", 9, [Window(0, None)]),
+ ]
+
+
+def test_dataset_has_no_related_scope() -> None:
+ """AV-004: datasets are not transitive recipients of activity in V2."""
+ assert resolve_scope("SqlaTable", 9, "related") == []
+
+
+def test_dataset_all_returns_only_self() -> None:
+ """For datasets, ``include='all'`` == ``include='self'`` (AV-004)."""
+ assert resolve_scope("SqlaTable", 9, "all", 0) == [
+ ("SqlaTable", 9, [Window(0, None)]),
+ ]
+
+
+def test_decoration_redacts_record_from_reused_entity_id() -> None:
+ """A historical UUID mismatch identifies a deleted predecessor."""
+ live_uuid = uuid4()
+ historical_uuid = uuid4()
+ record = {
+ "entity_kind": "chart",
+ "entity_id": 7,
+ "transaction_id": 20,
+ "sequence": 0,
+ "kind": "field",
+ "operation": "update",
+ "action_kind": None,
+ "path": "slice_name",
+ "from_value": "predecessor",
+ "to_value": "renamed",
+ "entity_name": "Old chart",
+ "changed_by_id": 1,
+ "first_name": "Ada",
+ "last_name": "Lovelace",
+ "user_id": 1,
+ }
+ with (
+ patch(
+ "superset.versioning.activity.render.check_entity_tombstones",
+ return_value={("Slice", 7): {"deleted": False, "deletion_state": None}},
+ ),
+ patch(
+ "superset.versioning.activity.render._lookup_entity_uuids",
+ return_value={("Slice", 7): live_uuid},
+ ),
+ patch(
+ "superset.versioning.activity.render.resolve_historical_entity_uuids",
+ return_value={("Slice", 7, 20): historical_uuid},
+ ),
+ patch(
+ "superset.versioning.activity.render.batch_chart_counts", return_value={}
+ ),
+ ):
+ apply_record_decoration([record], "Dashboard", 1)
+
+ assert record["entity_deleted"] is True
+ assert record["entity_uuid"] is None
+ assert record["version_uuid"] is None
+ assert record["entity_name"] == ""
+ assert record["from_value"] is None
+ assert record["to_value"] is None
+
+
+def test_bounded_heap_merges_newer_rows_from_later_id_chunks() -> None:
+ """A full early chunk cannot hide newer records from a later chunk."""
+
+ class Result(list[dict[str, Any]]):
+ closed = False
+
+ def close(self) -> None:
+ self.closed = True
+
+ def row(transaction_id: int, entity_id: int) -> dict[str, Any]:
+ return {
+ "issued_at": datetime(2026, 1, 1, 0, 0, transaction_id),
+ "transaction_id": transaction_id,
+ "sequence": 0,
+ "entity_kind": "chart",
+ "entity_id": entity_id,
+ }
+
+ windows = {
+ ("chart", 1): [Window(0, None)],
+ ("chart", 501): [Window(0, None)],
+ }
+ heap: BoundedRecordHeap = []
+ first = Result([row(2, 1), row(1, 1)])
+ second = Result([row(4, 501), row(3, 501)])
+
+ ordinal = _merge_result_into_heap(first, heap, windows, 2, 0)
+ _merge_result_into_heap(second, heap, windows, 2, ordinal)
+
+ assert first.closed
+ assert second.closed
+ assert [
+ entry[2]["transaction_id"]
+ for entry in sorted(heap, key=lambda entry: entry[0], reverse=True)
+ ] == [4, 3, 2]
+
+
+def test_total_sort_key_distinguishes_rows_at_same_timestamp() -> None:
+ issued_at = datetime(2026, 1, 1)
+ older = {
+ "issued_at": issued_at,
+ "transaction_id": 10,
+ "sequence": 1,
+ "entity_kind": "chart",
+ "entity_id": 7,
+ }
+ newer = {**older, "sequence": 2}
+ assert _record_sort_key(newer) > _record_sort_key(older)
+
+
+# ---- merge_entity_windows -----------------------------------------------
+
+
+def test_merge_entity_windows_collapses_repeated_keys() -> None:
+ """Repeated ``(api_kind, entity_id)`` entries union their window lists
+ so the fetch query's OR-clause stays compact."""
+ merged = merge_entity_windows(
+ [
+ ("Slice", 1, [Window(0, 100)]),
+ ("Slice", 1, [Window(200, 300)]),
+ ("SqlaTable", 5, [Window(0, None)]),
+ ]
+ )
+ by_key = {(kind, eid): windows for kind, eid, windows in merged}
+ assert by_key[("Slice", 1)] == [Window(0, 100), Window(200, 300)]
+ assert by_key[("SqlaTable", 5)] == [Window(0, None)]
+
+
+def test_merge_entity_windows_preserves_singletons() -> None:
+ """Non-duplicated entries pass through unchanged."""
+ inputs: list[EntityWindows] = [
+ ("Slice", 1, [Window(0, 100)]),
+ ("Dashboard", 2, [Window(10, 20)]),
+ ]
+ merged = merge_entity_windows(inputs)
+ assert sorted(merged) == sorted(inputs)
+
+
+def test_merge_entity_windows_unions_overlapping_windows_for_one_entity() -> None:
+ """Same entity, many redundant attachment windows → collapsed to one.
+
+ This guards the SQLite expression-tree limit: a fixture that
+ re-creates a chart-on-dashboard association across many transactions
+ used to produce N separate OR branches in the fetch query (one per
+ redundant window). merge_entity_windows must coalesce them.
+ """
+ scope: list[EntityWindows] = [
+ ("Slice", 1, [Window(10, 20)]),
+ ("Slice", 1, [Window(15, 25)]), # overlaps
+ ("Slice", 1, [Window(25, 30)]), # touches
+ ("Slice", 1, [Window(40, 50)]), # disjoint
+ ]
+ merged = merge_entity_windows(scope)
+ assert merged == [("Slice", 1, [Window(10, 30), Window(40, 50)])]
+
+
+# ---- union_windows -------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "windows, expected",
+ [
+ # Disjoint windows pass through
+ (
+ [Window(10, 20), Window(30, 40)],
+ [Window(10, 20), Window(30, 40)],
+ ),
+ # Overlapping windows merge
+ ([Window(10, 20), Window(15, 25)], [Window(10, 25)]),
+ # Touching windows merge (half-open: [10,20) + [20,30) = [10,30))
+ ([Window(10, 20), Window(20, 30)], [Window(10, 30)]),
+ # Many overlapping windows collapse to one
+ (
+ [Window(10, 20), Window(15, 25), Window(20, 30), Window(25, 35)],
+ [Window(10, 35)],
+ ),
+ # Input order doesn't matter
+ (
+ [Window(30, 40), Window(10, 20), Window(15, 25)],
+ [Window(10, 25), Window(30, 40)],
+ ),
+ # Open-ended absorbs everything to the right
+ ([Window(10, None), Window(50, 60)], [Window(10, None)]),
+ # Open-ended at the right merges into open-ended
+ ([Window(10, 20), Window(15, None)], [Window(10, None)]),
+ # Empty input
+ ([], []),
+ # Single window pass-through
+ ([Window(5, 10)], [Window(5, 10)]),
+ ],
+)
+def test_union_windows(windows: list[Window], expected: list[Window]) -> None:
+ assert union_windows(windows) == expected
+
+
+# ---- row_within_any_window (Python post-filter for the fetch query) ------
+
+
+def test_row_in_window_inside() -> None:
+ assert row_within_any_window({"transaction_id": 15}, [Window(10, 20)])
+
+
+def test_row_in_window_at_start_boundary_inclusive() -> None:
+ """Half-open: ``[10, 20)`` includes 10."""
+ assert row_within_any_window({"transaction_id": 10}, [Window(10, 20)])
+
+
+def test_row_in_window_at_end_boundary_exclusive() -> None:
+ """Half-open: ``[10, 20)`` excludes 20."""
+ assert not row_within_any_window({"transaction_id": 20}, [Window(10, 20)])
+
+
+def test_row_in_open_ended_window() -> None:
+ """``end=None`` means +∞."""
+ assert row_within_any_window({"transaction_id": 999}, [Window(10, None)])
+
+
+def test_row_in_any_of_several_windows() -> None:
+ assert row_within_any_window(
+ {"transaction_id": 50},
+ [Window(10, 20), Window(40, 60), Window(90, 100)],
+ )
+
+
+def test_row_in_no_windows_returns_false() -> None:
+ assert not row_within_any_window({"transaction_id": 50}, [])
+ assert not row_within_any_window(
+ {"transaction_id": 25}, [Window(10, 20), Window(30, 40)]
+ )
+
+
+# ---- Kind translation round-trip -----------------------------------------
+
+
+def test_kind_translation_is_bijective_for_supported_kinds() -> None:
+ """Every API kind maps to a table kind and back to the same value.
+ Locks in the contract that the two maps don't drift."""
+ for api_kind, table_kind in API_KIND_TO_TABLE.items():
+ assert TABLE_KIND_TO_API[table_kind] == api_kind
+
+
+# ---- _build_summary (AV-012) ---------------------------------------------
+
+
+def test_summary_for_dataset_column_change() -> None:
+ rec = {"kind": "column", "entity_name": "Sales Transactions"}
+ assert _build_summary("SqlaTable", rec) == (
+ "Dataset column changed: Sales Transactions"
+ )
+
+
+def test_summary_for_chart_filter_change() -> None:
+ rec = {"kind": "filter", "entity_name": "Top Charts"}
+ assert _build_summary("Slice", rec) == "Chart filter changed: Top Charts"
+
+
+def test_summary_for_restore_event() -> None:
+ rec = {"kind": "restore", "entity_name": "Q4 Dashboard"}
+ assert _build_summary("Dashboard", rec) == "Dashboard restored: Q4 Dashboard"
+
+
+def test_summary_unknown_kind_falls_back_to_updated() -> None:
+ """Unmapped change kinds collapse to a generic 'updated' verb."""
+ rec = {"kind": "mystery_kind", "entity_name": "X"}
+ assert _build_summary("Dashboard", rec) == "Dashboard updated: X"
+
+
+def test_summary_without_entity_name_drops_colon() -> None:
+ """Tombstoned entities have no name; the headline reads naturally
+ without a trailing colon and empty value."""
+ rec = {"kind": "filter", "entity_name": ""}
+ assert _build_summary("Slice", rec) == "Chart filter changed"
+
+
+# ---- _changed_by_dict ----------------------------------------------------
+
+
+def test_changed_by_returns_none_when_no_user_attached() -> None:
+ """Saves from CLI/Celery/import have no Flask user (sc-103156 §Session
+ 2026-05-18 clarification)."""
+ assert _changed_by_dict({"changed_by_id": None}) is None
+
+
+def test_changed_by_projects_only_display_fields() -> None:
+ """Per the ActivityChangedBy contract: id + first_name + last_name only.
+ Username is intentionally omitted (data-model.md)."""
+ record = {
+ "changed_by_id": 5,
+ "first_name": "Mike",
+ "last_name": "Bridge",
+ "user_id": 5, # internal column, must not leak
+ }
+ result = _changed_by_dict(record)
+ assert result == {"id": 5, "first_name": "Mike", "last_name": "Bridge"}
+ assert result is not None
+ assert "username" not in result
+
+
+# ---- impact_for_record (pure, post-batch) -------------------------------
+
+
+def test_impact_for_record_dashboard_path_dataset_related_uses_count() -> None:
+ """The only path/related shape that carries impact: ``Dashboard`` →
+ ``SqlaTable``. The count comes from the pre-batched lookup."""
+ record = {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100}
+ counts = {(5, 100): 3}
+ assert impact_for_record(record, "Dashboard", counts) == {"charts": 3}
+
+
+def test_impact_for_record_missing_count_yields_none() -> None:
+ """A pair the batch query didn't return (no matching siblings)
+ collapses to ``None`` rather than ``{"charts": 0}``."""
+ record = {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100}
+ assert impact_for_record(record, "Dashboard", {}) is None
+
+
+def test_impact_for_record_zero_count_yields_none() -> None:
+ """Explicit zero in the counts map is treated the same as missing —
+ no impact field on the wire."""
+ record = {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100}
+ assert impact_for_record(record, "Dashboard", {(5, 100): 0}) is None
+
+
+def test_impact_for_record_dashboard_path_chart_related_yields_none() -> None:
+ """Dashboard → chart is a direct dependency; no further sibling
+ layer to count."""
+ record = {"entity_kind": "chart", "entity_id": 5, "transaction_id": 100}
+ assert impact_for_record(record, "Dashboard", {(5, 100): 999}) is None
+
+
+def test_impact_for_record_chart_path_with_dataset_related_yields_none() -> None:
+ """Chart → dataset: the chart is itself the only dependent of the
+ dataset edit."""
+ record = {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100}
+ assert impact_for_record(record, "Slice", {(5, 100): 999}) is None
+
+
+def test_impact_for_record_dataset_path_yields_none() -> None:
+ """Datasets have no transitive layer (AV-004)."""
+ record = {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100}
+ assert impact_for_record(record, "SqlaTable", {(5, 100): 999}) is None
+
+
+# ---- collect_impact_pairs -----------------------------------------------
+
+
+def test_collect_impact_pairs_dashboard_path_collects_only_datasets() -> None:
+ """The batched pre-query only needs ``(dataset_id, tx)`` pairs.
+ Chart-related and self records aren't relevant."""
+ records = [
+ {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100},
+ {"entity_kind": "dataset", "entity_id": 7, "transaction_id": 200},
+ {"entity_kind": "chart", "entity_id": 9, "transaction_id": 300},
+ {"entity_kind": "dashboard", "entity_id": 1, "transaction_id": 400},
+ ]
+ assert collect_impact_pairs(records, "Dashboard") == {(5, 100), (7, 200)}
+
+
+def test_collect_impact_pairs_dedupes_repeated_pairs() -> None:
+ """Multiple change records for the same (dataset, tx) collapse to
+ one pair — the batch query computes the count once."""
+ records = [
+ {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100},
+ {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100},
+ {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100},
+ ]
+ pairs = collect_impact_pairs(records, "Dashboard")
+ assert pairs == {(5, 100)}
+
+
+def test_collect_impact_pairs_chart_path_returns_empty() -> None:
+ """Chart paths have no dashboard layer to count siblings on, so the
+ batch never needs to fire."""
+ records = [
+ {"entity_kind": "dataset", "entity_id": 5, "transaction_id": 100},
+ ]
+ assert collect_impact_pairs(records, "Slice") == set()
+
+
+def test_collect_impact_pairs_dataset_path_returns_empty() -> None:
+ records = [
+ {"entity_kind": "chart", "entity_id": 5, "transaction_id": 100},
+ ]
+ assert collect_impact_pairs(records, "SqlaTable") == set()
+
+
+def test_collect_impact_pairs_empty_records_returns_empty() -> None:
+ assert collect_impact_pairs([], "Dashboard") == set()
+
+
+# ---- parse_activity_query_params (shared API helper) ---------------------
+
+
+def test_parser_defaults_when_empty() -> None:
+ """No params → ``include='all'``, ``page=0``, ``page_size=DEFAULT``."""
+ assert parse_activity_query_params({}) == {
+ "include": "all",
+ "page": 0,
+ "page_size": _DEFAULT_PAGE_SIZE,
+ }
+
+
+def test_parser_clamps_page_size_to_max() -> None:
+ """A request for more than the contract maximum is clamped, not 400'd
+ (silent clamp matches AV-019's bounded-payload guarantee)."""
+ params = parse_activity_query_params({"page_size": str(_MAX_PAGE_SIZE * 5)})
+ assert params["page_size"] == _MAX_PAGE_SIZE
+
+
+def test_parser_accepts_iso_datetime_with_z_suffix() -> None:
+ """Python <3.11 fromisoformat rejects 'Z'; the parser tolerates it."""
+ params = parse_activity_query_params({"since": "2026-01-01T00:00:00Z"})
+ assert params["since"].year == 2026
+
+
+def test_parser_normalises_z_suffix_to_naive_utc() -> None:
+ """The 'Z' result must be tz-NAIVE: ``issued_at`` is a naive column, so a
+ tz-aware bind shifts the comparison by the session offset (or raises) on
+ PostgreSQL. The 'Z' instant is already UTC, so the value is unchanged."""
+ since = parse_activity_query_params({"since": "2026-01-01T00:00:00Z"})["since"]
+ assert since.tzinfo is None
+ assert since == datetime(2026, 1, 1, 0, 0, 0)
+
+
+def test_parser_normalises_offset_to_naive_utc() -> None:
+ """A non-UTC offset is converted to UTC and stripped to naive, so the
+ comparison against the naive ``issued_at`` column is in the same frame."""
+ since = parse_activity_query_params({"since": "2026-01-01T05:00:00+02:00"})["since"]
+ assert since.tzinfo is None
+ assert since == datetime(2026, 1, 1, 3, 0, 0) # 05:00 +02:00 -> 03:00 UTC
+
+
+def test_parser_rejects_invalid_include() -> None:
+ with pytest.raises(ActivityParamsError, match="include"):
+ parse_activity_query_params({"include": "sibling"})
+
+
+def test_parser_rejects_malformed_datetime() -> None:
+ with pytest.raises(ActivityParamsError, match="since"):
+ parse_activity_query_params({"since": "yesterday"})
+
+
+def test_parser_rejects_negative_page() -> None:
+ with pytest.raises(ActivityParamsError, match="page"):
+ parse_activity_query_params({"page": "-1"})
+
+
+def test_parser_rejects_zero_page_size() -> None:
+ with pytest.raises(ActivityParamsError, match="page_size"):
+ parse_activity_query_params({"page_size": "0"})
+
+
+def test_parser_error_is_a_value_error() -> None:
+ """``ActivityParamsError`` subclasses ``ValueError`` so callers that
+ only know about the standard library exception hierarchy still catch
+ it correctly."""
+ with pytest.raises(ValueError, match="include"):
+ parse_activity_query_params({"include": "nope"})
+
+
+# ---- Observability metric-key convention (T050 cross-coupling) ----------
+
+
+def test_metric_prefix_matches_versioning_namespace_convention() -> None:
+ """T050: cross-coupling sanity. The activity-view's instrumentation
+ prefix (``superset.activity_view.*``) must be a sibling of sc-103156's
+ eventual ``superset.versioning.*`` namespace, not nested under
+ a different root. Both endpoint families belong to the versioning
+ feature; their metrics should be discoverable from one Grafana
+ filter (``superset.activity_view.*`` OR ``superset.versioning.*``).
+
+ Locking the prefix in a test catches accidental drift in a code
+ review — a future PR renaming the prefix would fail this assertion
+ and require explicit acknowledgement.
+ """
+ from superset.versioning.activity.orchestrator import _METRIC_PREFIX
+
+ assert _METRIC_PREFIX == "superset.activity_view", (
+ f"Activity-view metrics prefix changed from "
+ f"'superset.activity_view' to {_METRIC_PREFIX!r}. If this was "
+ "intentional, update sc-103156's FR-027 instrumentation to "
+ "match the new convention OR document the new naming in plan §D-17."
+ )
+ # Sibling-namespace check: starts with the versioning-feature root.
+ assert _METRIC_PREFIX.startswith("superset."), (
+ "All Superset metrics live under 'superset.*'; activity_view must too."
+ )
+
+
+# ---- _emit_request_shape_attributes: related-entity counts ---------------
+#
+# The ``related_entity_count.*`` gauges report how many *other* entities an
+# activity request fanned out to. ``resolve_scope`` always prepends the path
+# entity itself (the "self" window) to the scope list, so the metric loop
+# must exclude that self entry — otherwise a chart/dataset request reports
+# one phantom related entity of its own kind.
+
+
+def _gauge_value(mock_sl: object, suffix: str) -> float:
+ """Return the value of the single ``gauge`` call whose metric name ends
+ with *suffix*. Fails loudly if absent so a renamed metric surfaces here."""
+ for call in mock_sl.gauge.call_args_list: # type: ignore[attr-defined]
+ name = call.args[0]
+ if name.endswith(suffix):
+ return call.args[1]
+ emitted = [c.args[0] for c in mock_sl.gauge.call_args_list] # type: ignore[attr-defined]
+ raise AssertionError(f"no gauge ending {suffix!r}; emitted {emitted}")
+
+
+@patch("superset.extensions.stats_logger_manager")
+def test_related_entity_count_excludes_self_for_chart(mock_mgr) -> None:
+ """A chart request scopes to itself + the datasets it used. The charts
+ gauge must read 0 (no *related* charts) even though the self Slice is in
+ the scope list; the datasets gauge counts only the two related datasets."""
+ sl = mock_mgr.instance
+ entity_windows: list[EntityWindows] = [
+ ("Slice", 7, [Window(0, None)]), # self — must not be counted
+ ("SqlaTable", 5, [Window(0, None)]), # related dataset
+ ("SqlaTable", 9, [Window(0, None)]), # related dataset
+ ]
+
+ _emit_request_shape_attributes(
+ "slice",
+ include="all",
+ has_since_filter=False,
+ page_size=25,
+ record_count=3,
+ entity_windows=entity_windows,
+ path_kind="Slice",
+ path_id=7,
+ )
+
+ assert _gauge_value(sl, "related_entity_count.charts") == 0.0
+ assert _gauge_value(sl, "related_entity_count.datasets") == 2.0
+
+
+@patch("superset.extensions.stats_logger_manager")
+def test_related_entity_count_excludes_self_for_dataset(mock_mgr) -> None:
+ """Datasets have no related scope, so an ``include=all`` dataset request
+ scopes to itself only. The datasets gauge must read 0, not 1."""
+ sl = mock_mgr.instance
+ entity_windows: list[EntityWindows] = [
+ ("SqlaTable", 9, [Window(0, None)]), # self only
+ ]
+
+ _emit_request_shape_attributes(
+ "sqlatable",
+ include="all",
+ has_since_filter=False,
+ page_size=25,
+ record_count=1,
+ entity_windows=entity_windows,
+ path_kind="SqlaTable",
+ path_id=9,
+ )
+
+ assert _gauge_value(sl, "related_entity_count.datasets") == 0.0
+
+
+@patch("superset.extensions.stats_logger_manager")
+def test_related_entity_count_counts_genuine_related_of_same_kind(mock_mgr) -> None:
+ """Self-exclusion keys on (kind, id), not kind alone: a dashboard whose
+ scope happened to include another dashboard would still count it."""
+ sl = mock_mgr.instance
+ entity_windows: list[EntityWindows] = [
+ ("Dashboard", 1, [Window(0, None)]), # self
+ ("Slice", 5, [Window(0, None)]), # related chart
+ ("Slice", 6, [Window(0, None)]), # related chart
+ ]
+
+ _emit_request_shape_attributes(
+ "dashboard",
+ include="all",
+ has_since_filter=False,
+ page_size=25,
+ record_count=2,
+ entity_windows=entity_windows,
+ path_kind="Dashboard",
+ path_id=1,
+ )
+
+ assert _gauge_value(sl, "related_entity_count.charts") == 2.0
+
+
+def test_parser_passes_q_through_and_drops_blank() -> None:
+ """``q`` reaches get_activity stripped; blank/missing stays absent."""
+ assert parse_activity_query_params({"q": " revenue "})["q"] == "revenue"
+ assert "q" not in parse_activity_query_params({})
+ assert "q" not in parse_activity_query_params({"q": " "})
+
+
+def test_record_matches_searches_decorated_surfaces() -> None:
+ """The q filter covers summary, entity_name, kind, path, and values —
+ case-insensitively (PR #40988: client search only covered loaded
+ pages; the server filter must cover the same surfaces)."""
+ from superset.versioning.activity.orchestrator import _record_matches
+
+ record = {
+ "summary": "Dataset updated: Sales Transactions",
+ "entity_name": "Sales Transactions",
+ "kind": "field",
+ "path": ["params", "adhoc_filters", "country"],
+ "from_value": None,
+ "to_value": {"label": "Revenue (EUR)"},
+ }
+ assert _record_matches(record, "sales") # entity_name/summary
+ assert _record_matches(record, "COUNTRY") # path segment
+ assert _record_matches(record, "revenue (eur)") # to_value
+ assert not _record_matches(record, "nonexistent")
+
+
+def test_record_matches_falsy_values_and_json_form() -> None:
+ """Falsy values must stay searchable (False/0 must not collapse to
+ ''), and values match in their JSON form — the text the client
+ renders — not Python repr."""
+ from superset.versioning.activity.orchestrator import _record_matches
+
+ record = {
+ "summary": "",
+ "entity_name": "",
+ "kind": "field",
+ "path": ["params", "show_legend"],
+ "from_value": True,
+ "to_value": False,
+ }
+ assert _record_matches(record, "false") # JSON 'false', not Python 'False'
+ assert _record_matches(record, "true")
+ zero = {**record, "path": ["params", "row_limit"], "from_value": 10, "to_value": 0}
+ assert _record_matches(zero, "0")
+ nested = {**record, "to_value": {"label": "Revenue"}}
+ assert _record_matches(nested, '"label"') # JSON double-quoted key
+
+
+def test_build_summary_meta_headline_branches() -> None:
+ """The __meta__ headline dispatches on the transaction's action_kind
+ (path is pure navigation): restore renders 'restored to version N'
+ (with entity_name when present); unknown meta actions fall back to
+ 'updated'."""
+ restore = {
+ "kind": "__meta__",
+ "action_kind": "restore",
+ "path": ["__meta__"],
+ "to_value": {"version_uuid": "u", "version_number": 3},
+ "entity_name": "Top 10 Girls",
+ }
+ assert _build_summary("Slice", restore) == (
+ "Chart restored to version 3: Top 10 Girls"
+ )
+ nameless = {**restore, "entity_name": ""}
+ assert _build_summary("Slice", nameless) == "Chart restored to version 3"
+ unknown = {
+ "kind": "__meta__",
+ "action_kind": "import",
+ "path": ["__meta__"],
+ "to_value": {},
+ "entity_name": "",
+ }
+ assert _build_summary("Dashboard", unknown) == "Dashboard updated"