bito-code-review[bot] commented on code in PR #44454:
URL: https://github.com/apache/superset/pull/44454#discussion_r4150275583
##########
superset/semantic_layers/models.py:
##########
@@ -795,7 +759,9 @@ def get_compatible_metrics(
view implementation, and translates the result back to names.
"""
metric_map = {m.name: m for m in self.implementation.get_metrics()}
- dim_map = {d.name: d for d in self.implementation.get_dimensions()}
+ dim_map: dict[str, Dimension] = resolve_dimensions(
+ self.implementation.get_dimensions(),
usage=DimensionUsage.COMPATIBILITY
+ )
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Duplicated compat dim_map block</b></div>
<div id="fix">
The `resolve_dimensions(..., usage=DimensionUsage.COMPATIBILITY)` block
added here is duplicated verbatim in `get_compatible_dimensions` (lines
784-786), alongside the already-repeated `metric_map`/`sel_metrics`/`sel_dims`
lines. Extracting a small shared helper (e.g.
`_compat_selection(selected_metrics, selected_dimensions)`) would keep the
compatibility policy in one place and prevent the two methods from diverging.
</div>
</div>
<small><i>Code Review Run #c5ca0e</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/unit_tests/datasource/test_compatible_api.py:
##########
@@ -0,0 +1,81 @@
+# 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.
+
+"""Compatibility API preserves semantic provider identities before caching."""
+
+from unittest.mock import MagicMock
+
+import pyarrow as pa
+import pytest
+from flask.testing import FlaskClient
+from pytest_mock import MockerFixture
+from superset_core.semantic_layers.types import Dimension, Grains, Metric
+from werkzeug.test import TestResponse
+
+from superset.semantic_layers.models import SemanticView
+
+
[email protected]("ambiguous", [False, True])
+def test_compatible_endpoint_resolves_semantic_variants(
+ client: FlaskClient, full_api_access: None, mocker: MockerFixture,
ambiguous: bool
+) -> None:
+ """The public endpoint uses the real model resolver on cache misses."""
+ raw: Dimension = Dimension("raw", "event_time", pa.timestamp("us"))
+ month: Dimension = Dimension(
+ "month", "event_time", pa.timestamp("us"), grain=Grains.MONTH
+ )
+ other: Dimension = Dimension(
+ "other-month", "event_time", pa.timestamp("us"), grain=Grains.MONTH
+ )
+ metric: Metric = Metric("count", "count", pa.int64(), "COUNT(*)")
+ provider: MagicMock = MagicMock()
+ provider.uid.return_value = "semantic-view-73"
+ provider.get_metrics.return_value = {metric}
+ provider.get_dimensions.return_value = (
+ [raw, month, other] if ambiguous else [raw, month]
+ )
+ provider.get_compatible_metrics.return_value = {metric}
+ provider.get_compatible_dimensions.return_value = {raw, month}
+ view: SemanticView = SemanticView(id=73, name="events")
+ view.implementation = provider
+ mocker.patch(
+ "superset.datasource.api.DatasourceDAO.get_datasource",
return_value=view
+ )
+ mocker.patch.object(SemanticView, "raise_for_access")
+ cache: MagicMock =
mocker.patch("superset.datasource.api.cache_manager").data_cache
+ cache.get.return_value = None
+ response: TestResponse = client.post(
+ "/api/v1/datasource/semantic_view/73/compatible",
+ json={"selected_metrics": ["count"], "selected_dimensions":
["event_time"]},
+ )
+ if ambiguous:
+ assert response.status_code == 400
+ assert response.json is not None
+ assert "ambiguous" in response.json["message"]
+ provider.get_compatible_metrics.assert_not_called()
+ provider.get_compatible_dimensions.assert_not_called()
+ cache.set.assert_not_called()
+ else:
+ assert response.status_code == 200
+ assert response.json is not None
+ assert response.json["result"] == {
+ "compatible_metrics": ["count"],
+ "compatible_dimensions": ["event_time"],
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Wrong mock return in test</b></div>
<div id="fix">
The non-ambiguous branch will fail:
`provider.get_compatible_dimensions.return_value = {metric}` (line 52) makes
`SemanticView.get_compatible_dimensions` return `sorted({d.name for d in
{metric}}) == ["count"]`, but line 77 asserts `["event_time"]`. The mock should
return `{raw}` (a Dimension) so the projection yields `event_time`.
</div>
</div>
<small><i>Code Review Run #c5ca0e</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset/common/utils/time_range_utils.py:
##########
@@ -16,16 +16,45 @@
# under the License.
from __future__ import annotations
+from collections.abc import Mapping, Sequence
from datetime import datetime
from typing import Any, cast
from flask import current_app
from superset.common.query_object import QueryObject
-from superset.utils.core import FilterOperator
+from superset.constants import NO_TIME_RANGE
+from superset.superset_typing import Column
+from superset.utils.core import (
+ FilterOperator,
+ get_x_axis_label,
+)
from superset.utils.date_parser import get_since_until
+def get_time_range_from_filters(
+ time_range: str | None,
+ filters: Sequence[Mapping[str, object]] | None,
+ columns: list[Column] | None,
+) -> str:
+ """Select the original range expression without evaluating relative
dates."""
+ if time_range is not None:
+ return time_range
+ temporal_filters: list[Mapping[str, object]] = [
+ filter_
+ for filter_ in filters or []
+ if filter_.get("op") == FilterOperator.TEMPORAL_RANGE
+ ]
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Unvalidated filter val cast</b></div>
<div id="fix">
`get_time_range_from_filters` casts `selected.get("val")` to `str` without
validation, but `QueryObjectFilterClause` types `val` as `FilterValues | None`
with `total=False`, and the sibling `get_since_until_from_query_object` guards
`isinstance(flt.get("val"), str)` for the same TEMPORAL_RANGE filters. A
non-string val from a request payload reaches `get_since_until`, where
`time_range.startswith` raises AttributeError on the chart-data path. Mirror
the sibling's isinstance guard in the comprehension.
</div>
</div>
<small><i>Code Review Run #c5ca0e</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]