You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by jl...@apache.org on 2026/08/18 17:22:58 UTC

(superset) branch master updated: fix(dashboard): align list OpenAPI schema (#43256)

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

sadpandajoe 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 f9946020967 fix(dashboard): align list OpenAPI schema (#43256)
f9946020967 is described below

commit f99460209678bb66ba957a5781040661f61ac514
Author: Endi Monan <65...@users.noreply.github.com>
AuthorDate: Tue Aug 18 19:22:50 2026 +0200

    fix(dashboard): align list OpenAPI schema (#43256)
---
 docs/static/resources/openapi.json                 |  72 ++++++++------
 superset/dashboards/api.py                         |   3 +-
 superset/views/custom_tags_api_mixin.py            |  17 +++-
 tests/integration_tests/base_api_tests.py          |  52 ++++++++++
 tests/unit_tests/openapi/test_static_spec.py       |  54 ++++++++++
 .../unit_tests/views/test_custom_tags_api_mixin.py | 109 +++++++++++++++++++++
 6 files changed, 274 insertions(+), 33 deletions(-)

diff --git a/docs/static/resources/openapi.json b/docs/static/resources/openapi.json
index ac0264764ce..f3f29908b55 100644
--- a/docs/static/resources/openapi.json
+++ b/docs/static/resources/openapi.json
@@ -3407,22 +3407,26 @@
             "nullable": true,
             "type": "string"
           },
+          "description": {
+            "nullable": true,
+            "type": "string"
+          },
+          "editors": {
+            "items": {
+              "$ref": "#/components/schemas/DashboardRestApi.get_list.Subject"
+            },
+            "type": "array"
+          },
           "id": {
             "type": "integer"
           },
           "is_managed_externally": {
             "type": "boolean"
           },
-          "owners": {
-            "$ref": "#/components/schemas/DashboardRestApi.get_list.User2"
-          },
           "published": {
             "nullable": true,
             "type": "boolean"
           },
-          "roles": {
-            "$ref": "#/components/schemas/DashboardRestApi.get_list.Role"
-          },
           "slug": {
             "maxLength": 255,
             "nullable": true,
@@ -3432,10 +3436,10 @@
             "readOnly": true
           },
           "tags": {
-            "$ref": "#/components/schemas/DashboardRestApi.get_list.Tag"
-          },
-          "thumbnail_url": {
-            "readOnly": true
+            "items": {
+              "$ref": "#/components/schemas/DashboardRestApi.get_list.Tag"
+            },
+            "type": "array"
           },
           "url": {
             "readOnly": true
@@ -3444,57 +3448,65 @@
             "format": "uuid",
             "nullable": true,
             "type": "string"
+          },
+          "viewers": {
+            "items": {
+              "$ref": "#/components/schemas/DashboardRestApi.get_list.Subject1"
+            },
+            "type": "array"
           }
         },
         "type": "object"
       },
-      "DashboardRestApi.get_list.Role": {
+      "DashboardRestApi.get_list.Subject": {
         "properties": {
           "id": {
             "type": "integer"
           },
-          "name": {
-            "maxLength": 64,
+          "label": {
+            "maxLength": 255,
             "type": "string"
+          },
+          "type": {
+            "type": "integer"
           }
         },
-        "required": ["name"],
+        "required": ["label", "type"],
         "type": "object"
       },
-      "DashboardRestApi.get_list.Tag": {
+      "DashboardRestApi.get_list.Subject1": {
         "properties": {
           "id": {
             "type": "integer"
           },
-          "name": {
-            "maxLength": 250,
-            "nullable": true,
+          "label": {
+            "maxLength": 255,
             "type": "string"
           },
           "type": {
-            "enum": [1, 2, 3, 4]
+            "type": "integer"
           }
         },
+        "required": ["label", "type"],
         "type": "object"
       },
-      "DashboardRestApi.get_list.User": {
+      "DashboardRestApi.get_list.Tag": {
         "properties": {
-          "first_name": {
-            "maxLength": 64,
-            "type": "string"
-          },
           "id": {
             "type": "integer"
           },
-          "last_name": {
-            "maxLength": 64,
+          "name": {
+            "maxLength": 250,
+            "nullable": true,
             "type": "string"
+          },
+          "type": {
+            "enum": [1, 2, 3, 4]
           }
         },
-        "required": ["first_name", "last_name"],
         "type": "object"
       },
-      "DashboardRestApi.get_list.User1": {
+      "DashboardRestApi.get_list.User": {
         "properties": {
           "first_name": {
             "maxLength": 64,
@@ -3511,7 +3523,7 @@
         "required": ["first_name", "last_name"],
         "type": "object"
       },
-      "DashboardRestApi.get_list.User2": {
+      "DashboardRestApi.get_list.User1": {
         "properties": {
           "first_name": {
             "maxLength": 64,
@@ -16506,7 +16518,7 @@
                     },
                     "result": {
                       "items": {
-                        "type": "object"
+                        "$ref": "#/components/schemas/DashboardRestApi.get_list"
                       },
                       "type": "array"
                     }
diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py
index cdd71d2b9ee..cbde7183106 100644
--- a/superset/dashboards/api.py
+++ b/superset/dashboards/api.py
@@ -418,7 +418,8 @@ class DashboardRestApi(
                       result:
                         type: array
                         items:
-                          type: object
+                          $ref: >-
+                            #/components/schemas/{{self.__class__.__name__}}.get_list
             400:
               $ref: '#/components/responses/400'
             401:
diff --git a/superset/views/custom_tags_api_mixin.py b/superset/views/custom_tags_api_mixin.py
index abc1a1fe3e2..c04d5d7790a 100644
--- a/superset/views/custom_tags_api_mixin.py
+++ b/superset/views/custom_tags_api_mixin.py
@@ -27,8 +27,9 @@ class CustomTagsOptimizationMixin:
 
     When enabled via config, this mixin:
     1. Configures list_columns to use custom_tags (filtered relationship)
-    2. Rewrites frontend requests from 'tags.*' to 'custom_tags.*'
-    3. Transforms responses to rename 'custom_tags' back to 'tags'
+    2. Exposes custom_tags as tags in the response schema
+    3. Rewrites frontend requests from 'tags.*' to 'custom_tags.*'
+    4. Transforms responses to rename 'custom_tags' back to 'tags'
 
     This provides SQL query optimization (97% reduction) while maintaining
     frontend compatibility.
@@ -62,6 +63,18 @@ class CustomTagsOptimizationMixin:
         self._custom_tags_only = current_app.config.get(config_key, False)
         self.list_columns = custom_columns if self._custom_tags_only else full_columns
 
+    def _init_model_schemas(self) -> None:
+        """Keep the optimized relationship's public schema name stable."""
+        super()._init_model_schemas()  # type: ignore[misc]
+
+        list_model_schema = getattr(self, "list_model_schema", None)
+        if (
+            self._custom_tags_only
+            and list_model_schema
+            and "custom_tags" in list_model_schema.fields
+        ):
+            list_model_schema.fields["custom_tags"].data_key = "tags"
+
     def get_list(self, **kwargs: Any) -> Response:
         """Override to rewrite request parameters for custom_tags optimization.
 
diff --git a/tests/integration_tests/base_api_tests.py b/tests/integration_tests/base_api_tests.py
index 43bb569959e..870deb832c4 100644
--- a/tests/integration_tests/base_api_tests.py
+++ b/tests/integration_tests/base_api_tests.py
@@ -16,6 +16,7 @@
 # under the License.
 """Unit tests for Superset"""
 
+from pathlib import Path
 from unittest.mock import patch
 
 import rison
@@ -42,6 +43,57 @@ class TestOpenApiSpec(SupersetTestCase):
         response = json.loads(rv.data.decode("utf-8"))
         validate(response)
 
+    def test_dashboard_list_uses_generated_response_schema(self):
+        """Keep the generated dashboard list contract aligned with published docs.
+
+        If an intentional list schema change breaks this test, regenerate
+        ``docs/static/resources/openapi.json`` with ``superset update-api-docs``
+        under the production-default configuration, then review the focused
+        dashboard diff.
+        """
+        self.login(ADMIN_USERNAME)
+        rv = self.client.get("api/v1/_openapi")
+
+        assert rv.status_code == 200
+        generated_spec = json.loads(rv.data.decode("utf-8"))
+        published_spec_path = (
+            Path(__file__).parents[2] / "docs" / "static" / "resources" / "openapi.json"
+        )
+        published_spec = json.loads(published_spec_path.read_text(encoding="utf-8"))
+
+        generated_result_items = generated_spec["paths"]["/api/v1/dashboard/"]["get"][
+            "responses"
+        ]["200"]["content"]["application/json"]["schema"]["properties"]["result"][
+            "items"
+        ]
+        published_result_items = published_spec["paths"]["/api/v1/dashboard/"]["get"][
+            "responses"
+        ]["200"]["content"]["application/json"]["schema"]["properties"]["result"][
+            "items"
+        ]
+
+        assert (
+            generated_result_items
+            == published_result_items
+            == {"$ref": "#/components/schemas/DashboardRestApi.get_list"}
+        )
+
+        schema_prefix = "DashboardRestApi.get_list"
+        generated_schemas = {
+            name: schema
+            for name, schema in generated_spec["components"]["schemas"].items()
+            if name == schema_prefix or name.startswith(f"{schema_prefix}.")
+        }
+        published_schemas = {
+            name: schema
+            for name, schema in published_spec["components"]["schemas"].items()
+            if name == schema_prefix or name.startswith(f"{schema_prefix}.")
+        }
+
+        assert generated_schemas == published_schemas, (
+            "Dashboard list OpenAPI components changed; regenerate the published spec"
+        )
+
     def test_info_endpoint(self):
         """
         API: Test info endpoint
diff --git a/tests/unit_tests/openapi/test_static_spec.py b/tests/unit_tests/openapi/test_static_spec.py
new file mode 100644
index 00000000000..b27df651990
--- /dev/null
+++ b/tests/unit_tests/openapi/test_static_spec.py
@@ -0,0 +1,54 @@
+# 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.
+
+from pathlib import Path
+
+from superset.utils import json
+
+
+def test_documented_dashboard_list_schema_matches_public_contract() -> None:
+    """The published dashboard list contract must use generated relationships."""
+    spec_path = (
+        Path(__file__).parents[3] / "docs" / "static" / "resources" / "openapi.json"
+    )
+    spec = json.loads(spec_path.read_text(encoding="utf-8"))
+    schemas = spec["components"]["schemas"]
+    schema_name = "DashboardRestApi.get_list"
+    properties = schemas[schema_name]["properties"]
+
+    result_items = spec["paths"]["/api/v1/dashboard/"]["get"]["responses"]["200"][
+        "content"
+    ]["application/json"]["schema"]["properties"]["result"]["items"]
+    assert result_items == {"$ref": f"#/components/schemas/{schema_name}"}
+
+    assert "description" in properties
+    assert {"owners", "roles", "thumbnail_url"}.isdisjoint(properties)
+
+    relationship_refs = {
+        "editors": "DashboardRestApi.get_list.Subject",
+        "tags": "DashboardRestApi.get_list.Tag",
+        "viewers": "DashboardRestApi.get_list.Subject1",
+    }
+    for field_name, component_name in relationship_refs.items():
+        assert properties[field_name] == {
+            "items": {"$ref": f"#/components/schemas/{component_name}"},
+            "type": "array",
+        }
+        assert component_name in schemas
+
+    assert f"{schema_name}.Role" not in schemas
+    assert f"{schema_name}.User2" not in schemas
diff --git a/tests/unit_tests/views/test_custom_tags_api_mixin.py b/tests/unit_tests/views/test_custom_tags_api_mixin.py
new file mode 100644
index 00000000000..99d08e672d5
--- /dev/null
+++ b/tests/unit_tests/views/test_custom_tags_api_mixin.py
@@ -0,0 +1,109 @@
+# 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.
+"""Tests for both renaming mechanisms in ``CustomTagsOptimizationMixin``.
+
+The schema-level ``data_key`` rename only applies to the API's default list
+schema; requests that pass ``select_columns`` make FAB build a fresh schema
+on the fly, so for those the ``pre_get_list`` response rewrite is what keeps
+the public ``tags`` name. Both paths need coverage.
+"""
+
+from typing import Any
+
+from marshmallow import fields, Schema
+
+from superset.views.custom_tags_api_mixin import CustomTagsOptimizationMixin
+
+
+class BaseApi:
+    """Stub for the FAB ``ModelRestApi`` base. The mixin chains via
+    ``super()``, so the stub must define the hooks the mixin overrides."""
+
+    list_model_schema: Schema
+    pre_get_list_calls: int = 0
+
+    def _init_model_schemas(self) -> None:
+        self.list_model_schema = Schema.from_dict(
+            {"custom_tags": fields.List(fields.String())}
+        )()
+
+    def pre_get_list(self, _data: dict[str, Any]) -> None:
+        self.pre_get_list_calls += 1
+
+
+class CustomTagsApi(CustomTagsOptimizationMixin, BaseApi):
+    _custom_tags_only = True
+
+
+class UnoptimizedTagsApi(CustomTagsOptimizationMixin, BaseApi):
+    _custom_tags_only = False
+
+
+def test_custom_tags_schema_uses_public_tags_name() -> None:
+    api = CustomTagsApi()
+
+    api._init_model_schemas()
+
+    assert api.list_model_schema.dump({"custom_tags": ["critical"]}) == {
+        "tags": ["critical"]
+    }
+
+
+def test_custom_tags_schema_keeps_name_when_optimization_disabled() -> None:
+    api = UnoptimizedTagsApi()
+
+    api._init_model_schemas()
+
+    assert api.list_model_schema.dump({"custom_tags": ["critical"]}) == {
+        "custom_tags": ["critical"]
+    }
+
+
+def test_pre_get_list_renames_custom_tags_when_enabled() -> None:
+    api = CustomTagsApi()
+    data: dict[str, Any] = {
+        "result": [
+            {"id": 1, "custom_tags": [{"name": "critical"}]},
+            {"id": 2},
+        ]
+    }
+
+    api.pre_get_list(data)
+
+    assert data["result"][0] == {"id": 1, "tags": [{"name": "critical"}]}
+    assert data["result"][1] == {"id": 2}
+    assert api.pre_get_list_calls == 1
+
+
+def test_pre_get_list_keeps_custom_tags_when_disabled() -> None:
+    api = UnoptimizedTagsApi()
+    data: dict[str, Any] = {"result": [{"id": 1, "custom_tags": []}]}
+
+    api.pre_get_list(data)
+
+    assert data["result"][0] == {"id": 1, "custom_tags": []}
+    assert api.pre_get_list_calls == 1
+
+
+def test_pre_get_list_tolerates_missing_result_key() -> None:
+    api = CustomTagsApi()
+    data: dict[str, Any] = {"count": 0}
+
+    api.pre_get_list(data)
+
+    assert data == {"count": 0}
+    assert api.pre_get_list_calls == 1