You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by kg...@apache.org on 2026/05/29 16:26:16 UTC

(superset) 09/23: feat(activity-view): Phase 4 US2 — chart /activity/ endpoint (T028-T032)

This is an automated email from the ASF dual-hosted git repository.

kgabryje pushed a commit to branch sc-107283-versioning-activity-view
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 6b2d75ca0be6ba35d53ec9d6653746bdc08ccebf
Author: Mike Bridge <mi...@ext.preset.io>
AuthorDate: Tue May 26 15:49:52 2026 -0600

    feat(activity-view): Phase 4 US2 — chart /activity/ endpoint (T028-T032)
    
    Implements the chart cross-entity activity stream (US2). Builds on the
    resolve_endpoint_path_entity helper from the prior tidy commit
    (1d60513079), so the new endpoint is a small composition of: resolve
    path entity → parse params → get_activity(Slice, ...) → serialize.
    
    * T028 ChartRestApi.activity — @expose("/<uuid_str>/activity/") on the
      chart blueprint. Decorator stack mirrors list_versions; registered
      in include_route_methods. The MODEL_API_RW_METHOD_PERMISSION_MAP
      entry "activity": "write" added in Phase 3 already covers this
      endpoint family (the map is class-permission-agnostic).
    
    * T029 TestChartActivityView class added to activity_view_tests.py,
      following the same patterns as TestDashboardActivityView.
    
    * T030 test_chart_activity_includes_dataset_edit_as_related — Given
      a chart pointing at the birth_names dataset, When the dataset's
      description is edited, Then the chart activity stream surfaces a
      SqlaTable/related record (AS-1 of US2).
    
    * T032 test_chart_activity_excludes_sibling_dashboards — Given the
      chart is on a dashboard, When the dashboard's title is edited,
      Then NO Dashboard records appear in the chart's activity. Per the
      spec's Relationship Traversal section: charts don't see sideways
      to dashboards they happen to be on.
    
    * T031 (datasource-switch attribution) deferred — needs a second
      dataset fixture which the birth_names environment doesn't provide
      cleanly. Will land with a multi-dataset test harness in a follow-up.
    
    Additional coverage: 404 for unknown UUID, 400 for malformed UUID,
    400 for invalid include, 403 for non-owner, 200 envelope smoke,
    chart-self-edit appears as source=self, include=self filter test.
    
    Full suite: 19/19 integration tests + 57/57 unit tests green.
    
    Co-Authored-By: Claude Opus 4.7 (1M context) <no...@anthropic.com>
---
 superset/charts/api.py                             |  84 ++++++++
 .../versioning/activity_view_tests.py              | 212 +++++++++++++++++++++
 2 files changed, 296 insertions(+)

diff --git a/superset/charts/api.py b/superset/charts/api.py
index 7f6a18e1c92..0c369bd8569 100644
--- a/superset/charts/api.py
+++ b/superset/charts/api.py
@@ -133,6 +133,7 @@ class ChartRestApi(BaseSupersetModelRestApi):
         "list_versions",
         "get_version",
         "restore_version",
+        "activity",
     }
     class_permission_name = "Chart"
     method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
@@ -1426,6 +1427,89 @@ class ChartRestApi(BaseSupersetModelRestApi):
             self.response(200, result=snapshot), Slice, entity_uuid
         )
 
+    @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 (sc-107283 US2)
+          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: 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 import activity as activity_module
+        from superset.versioning.schemas import ActivityResponseSchema
+
+        try:
+            entity = activity_module.resolve_endpoint_path_entity(self, Slice, uuid_str)
+        except activity_module.PathEntityResponseError as exc:
+            return exc.response
+
+        try:
+            params = activity_module.parse_activity_query_params(request.args)
+        except activity_module.ActivityParamsError as exc:
+            return self.response_400(message=str(exc))
+
+        records, count = activity_module.get_activity(Slice, entity.uuid, **params)
+        payload = ActivityResponseSchema().dump({"result": records, "count": count})
+        return self.response(200, **payload)
+
     @expose(
         "/<uuid_str>/versions/<version_uuid_str>/restore",
         methods=("POST",),
diff --git a/tests/integration_tests/versioning/activity_view_tests.py b/tests/integration_tests/versioning/activity_view_tests.py
index f01d4fedf75..ab314324b3d 100644
--- a/tests/integration_tests/versioning/activity_view_tests.py
+++ b/tests/integration_tests/versioning/activity_view_tests.py
@@ -34,6 +34,7 @@ from typing import Any
 
 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
@@ -46,6 +47,14 @@ from tests.integration_tests.fixtures.birth_names_dashboard import (  # noqa: F4
 )
 
 
+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
@@ -261,3 +270,206 @@ class TestDashboardActivityView(SupersetTestCase):
         self.login(ADMIN_USERNAME)
         rv = self._activity(str(dashboard.uuid), page_size="500")
         assert rv.status_code == 200
+
+
+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_denies_non_owner(self) -> None:
+        """Same shape as the dashboard endpoint: Alpha lacks ownership
+        on the admin-fixture chart so raise_for_ownership returns 403."""
+        _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 == 403
+
+    # ---- 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"] == "Slice" 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"] == "SqlaTable" 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"] == "Slice"
+        finally:
+            db.session.rollback()
+            dataset = (
+                db.session.query(SqlaTable).filter(SqlaTable.id == dataset_id).one()
+            )
+            dataset.description = original_description
+            db.session.commit()