codeant-ai-for-open-source[bot] commented on code in PR #39914:
URL: https://github.com/apache/superset/pull/39914#discussion_r3507460523
##########
superset/reports/notifications/slackv2.py:
##########
@@ -48,6 +48,55 @@
logger = logging.getLogger(__name__)
+_TRANSIENT_SLACK_API_ERROR_CODES = frozenset(
+ {
+ "fatal_error",
+ "internal_error",
+ "ratelimited",
+ "request_timeout",
+ "rollup_error",
+ "service_unavailable",
+ "timeout",
+ }
+)
Review Comment:
**Suggestion:** Add an explicit type annotation to this new module-level
constant so it complies with the type-hint requirement for annotatable
variables. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This new module-level constant is inferable and can be annotated, but it has
no explicit type hint. That matches the custom rule requiring type hints on new
or modified Python variables that can be annotated.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=4a397b3457fc4b2b8b9c8a8d95640b21&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=4a397b3457fc4b2b8b9c8a8d95640b21&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/reports/notifications/slackv2.py
**Line:** 51:61
**Comment:**
*Custom Rule: Add an explicit type annotation to this new module-level
constant so it complies with the type-hint requirement for annotatable
variables.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=3b4c372fc5a9f4835e74ada6a6ff1f4545cf0b44de19361cbf2a1321a19a5c97&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=3b4c372fc5a9f4835e74ada6a6ff1f4545cf0b44de19361cbf2a1321a19a5c97&reaction=dislike'>π</a>
##########
superset/utils/slack.py:
##########
@@ -34,12 +36,42 @@
logger = logging.getLogger(__name__)
+_SLACK_V1_DEPRECATION_MESSAGE = (
+ "Slack v1 (the legacy `Slack` recipient type and `files.upload` API) is "
+ "deprecated and will be removed in the next major release. Slack retired "
+ "the `files.upload` endpoint in 2025, so v1 file uploads no longer work; "
+ "only text-only `chat_postMessage` sends still succeed. Grant your Slack "
+ "bot the `channels:read` and `groups:read` scopes so existing v1 "
+ "recipients can be auto-upgraded to SlackV2 on "
+ "their next send."
+)
Review Comment:
**Suggestion:** Add an explicit type annotation for this new module-level
constant to comply with the Python typing rule. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
The new module-level string constant is unannotated and could be typed as
`str`, so it matches the Python type-hints rule for annotatable variables.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=3371473b01254b6bac543a46293b765f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=3371473b01254b6bac543a46293b765f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/utils/slack.py
**Line:** 39:47
**Comment:**
*Custom Rule: Add an explicit type annotation for this new module-level
constant to comply with the Python typing rule.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=3aeba80f5603b43dd83c30d900a463e5bc970fe39fe1b5c9b59aead368422250&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=3aeba80f5603b43dd83c30d900a463e5bc970fe39fe1b5c9b59aead368422250&reaction=dislike'>π</a>
##########
superset/utils/slack.py:
##########
@@ -34,12 +36,42 @@
logger = logging.getLogger(__name__)
+_SLACK_V1_DEPRECATION_MESSAGE = (
+ "Slack v1 (the legacy `Slack` recipient type and `files.upload` API) is "
+ "deprecated and will be removed in the next major release. Slack retired "
+ "the `files.upload` endpoint in 2025, so v1 file uploads no longer work; "
+ "only text-only `chat_postMessage` sends still succeed. Grant your Slack "
+ "bot the `channels:read` and `groups:read` scopes so existing v1 "
+ "recipients can be auto-upgraded to SlackV2 on "
+ "their next send."
+)
+
+
+# functools.cache gives us a process-lifetime, thread-safe one-shot guard
+# without the read-then-write race that bare module globals would have under
+# multi-threaded WSGI workers. The cached return value (None) is irrelevant β
+# we only care that the body executes at most once per process.
[email protected]
+def _emit_v1_flag_off_deprecation() -> None:
+ warnings.warn(_SLACK_V1_DEPRECATION_MESSAGE, DeprecationWarning,
stacklevel=3)
+ logger.warning(
+ "ALERT_REPORT_SLACK_V2 is disabled; %s", _SLACK_V1_DEPRECATION_MESSAGE
+ )
+
+
[email protected]
+def _emit_v1_scope_missing_deprecation() -> None:
+ warnings.warn(_SLACK_V1_DEPRECATION_MESSAGE, DeprecationWarning,
stacklevel=3)
+
class SlackChannelTypes(StrEnum):
PUBLIC = "public_channel"
PRIVATE = "private_channel"
+_SLACK_CONVERSATION_TYPES = ",".join(SlackChannelTypes)
Review Comment:
**Suggestion:** Add a concrete type annotation for this new derived constant
value. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This new module-level constant is a plain string assignment without an
explicit annotation, so it is a valid type-hint omission under the rule.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b1410a4383d3413ca7ee89f66a6aa662&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b1410a4383d3413ca7ee89f66a6aa662&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/utils/slack.py
**Line:** 72:72
**Comment:**
*Custom Rule: Add a concrete type annotation for this new derived
constant value.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=6a826660ee9eab2eba377ac087fa27e5b3612df30fb1729962e8fc87e4c000dc&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=6a826660ee9eab2eba377ac087fa27e5b3612df30fb1729962e8fc87e4c000dc&reaction=dislike'>π</a>
##########
superset/utils/slack.py:
##########
@@ -224,21 +256,75 @@ def get_channels_with_search(
return channels
+_SCOPE_MISSING_ERROR_CODES = frozenset(
+ {"missing_scope", "not_allowed_token_type", "no_permission"}
+)
Review Comment:
**Suggestion:** Add an explicit typed annotation for this new frozenset
constant. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
The frozenset constant is newly introduced and lacks a type annotation, so
this is a real omission that the typing rule covers.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=da4bfdbbafd3450c840974f4da16c95a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=da4bfdbbafd3450c840974f4da16c95a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/utils/slack.py
**Line:** 259:261
**Comment:**
*Custom Rule: Add an explicit typed annotation for this new frozenset
constant.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=7ddbc8ccc3cd1bac4f102d57070d1b792e869796595252ff199c9bc3e85365e6&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=7ddbc8ccc3cd1bac4f102d57070d1b792e869796595252ff199c9bc3e85365e6&reaction=dislike'>π</a>
##########
superset/utils/slack.py:
##########
@@ -117,7 +149,7 @@ def _get_channels(
client = get_slack_client()
channel_schema = SlackChannelSchema()
channels: list[SlackChannelSchema] = []
- extra_params = {"types": ",".join(SlackChannelTypes)}
+ extra_params = {"types": _SLACK_CONVERSATION_TYPES}
Review Comment:
**Suggestion:** Add a type annotation to this newly introduced local
dictionary so the variable is explicitly typed. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This newly added local dictionary is inferable as a typed variable and is
not annotated, which fits the rule requiring type hints on relevant variables
that can be annotated.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7a421a2370f34e00847f1b47590bc8c6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7a421a2370f34e00847f1b47590bc8c6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/utils/slack.py
**Line:** 152:152
**Comment:**
*Custom Rule: Add a type annotation to this newly introduced local
dictionary so the variable is explicitly typed.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=bfe90690cbbd44000dcf474885f119ad967e287b23b43b0d4d77ec48025dbbdc&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=bfe90690cbbd44000dcf474885f119ad967e287b23b43b0d4d77ec48025dbbdc&reaction=dislike'>π</a>
##########
superset/utils/slack.py:
##########
@@ -224,21 +256,75 @@ def get_channels_with_search(
return channels
+_SCOPE_MISSING_ERROR_CODES = frozenset(
+ {"missing_scope", "not_allowed_token_type", "no_permission"}
+)
+
+
def should_use_v2_api() -> bool:
if not feature_flag_manager.is_feature_enabled("ALERT_REPORT_SLACK_V2"):
+ _emit_v1_flag_off_deprecation()
return False
try:
client = get_slack_client()
+ extra_params = {"types": _SLACK_CONVERSATION_TYPES}
Review Comment:
**Suggestion:** Add a type annotation to this newly introduced local
dictionary in the probe path as well. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
The probe path introduces another local dictionary assignment without an
annotation, so it is also a genuine type-hint omission under the stated rule.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=262eb7c6f49f424586c8e028879737c1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=262eb7c6f49f424586c8e028879737c1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/utils/slack.py
**Line:** 270:270
**Comment:**
*Custom Rule: Add a type annotation to this newly introduced local
dictionary in the probe path as well.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=e5bfe2f49a08a35b12ce3d9e3c567ed21fb72446f0974f0734956c0c5a8038e8&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=e5bfe2f49a08a35b12ce3d9e3c567ed21fb72446f0974f0734956c0c5a8038e8&reaction=dislike'>π</a>
##########
tests/unit_tests/reports/notifications/slack_tests.py:
##########
@@ -16,16 +16,50 @@
# under the License.
import uuid
-from unittest.mock import MagicMock, patch
+from typing import Any
+from unittest.mock import call, MagicMock, patch
import pandas as pd
import pytest
-from slack_sdk.errors import SlackApiError
+from slack_sdk.errors import (
+ BotUserAccessError,
+ SlackApiError,
+ SlackClientConfigurationError,
+ SlackClientError,
+ SlackClientNotConnectedError,
+ SlackObjectFormationError,
+ SlackRequestError,
+ SlackTokenRotationError,
+)
+from slack_sdk.web.slack_response import SlackResponse
-from superset.reports.notifications.slackv2 import SlackV2Notification
+from superset.reports.notifications.exceptions import (
+ NotificationAuthorizationException,
+ NotificationMalformedException,
+ NotificationParamException,
+ NotificationUnprocessableException,
+)
+from superset.reports.notifications.slackv2 import (
+ _give_up_slack_api_retry,
+ SlackV2Notification,
+)
from superset.utils.core import HeaderDataType
[email protected](autouse=True)
+def _skip_backoff_sleep():
Review Comment:
**Suggestion:** Add an explicit return type annotation to this fixture
function (for example an iterator/generator of None) to satisfy the required
type-hint rule. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This fixture is newly added and has no return type annotation. The custom
rule requires type hints on functions and methods, so this is a real violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=539c24e61a804e3aa615dbc9061ca214&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=539c24e61a804e3aa615dbc9061ca214&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/reports/notifications/slack_tests.py
**Line:** 50:50
**Comment:**
*Custom Rule: Add an explicit return type annotation to this fixture
function (for example an iterator/generator of None) to satisfy the required
type-hint rule.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=cd5a88cbc33350bd33c3105123d452c30ba42c501e26737d0e2de1bd097c3c34&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=cd5a88cbc33350bd33c3105123d452c30ba42c501e26737d0e2de1bd097c3c34&reaction=dislike'>π</a>
##########
tests/unit_tests/commands/report/execute_test.py:
##########
@@ -1309,73 +1309,109 @@ def
test_update_recipient_to_slack_v2_missing_channels(mocker: MockerFixture):
mock_cmmd.update_report_schedule_slack_v2()
-def test_update_recipient_to_slack_v2_reverts_all_on_partial_failure(
+def test_update_recipient_to_slack_v2_multiple_recipients(
mocker: MockerFixture,
) -> None:
- """
- When the second of two Slack recipients fails channel resolution, BOTH
- recipients are fully reverted β type AND exact original
- ``recipient_config_json`` string β not just the loop variable's type. This
- prevents the intervening ``create_log`` commit from flushing a
half-migrated,
- inconsistent state.
+ """All Slack recipients are upgraded atomically when every channel
resolves."""
+
+ def fake_get_channels(search_string, types, exact_match):
Review Comment:
**Suggestion:** Add explicit type hints to this helper functionβs parameters
and return type to satisfy the projectβs typing requirement for new function
definitions. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
The added local helper function has no parameter or return type annotations,
which violates the Python type-hint requirement for new or modified code. This
is a real rule violation in the final file state.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b4dd78123fc14e4f908c868cab667fe7&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b4dd78123fc14e4f908c868cab667fe7&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/commands/report/execute_test.py
**Line:** 1317:1317
**Comment:**
*Custom Rule: Add explicit type hints to this helper functionβs
parameters and return type to satisfy the projectβs typing requirement for new
function definitions.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=f8751742213399420df255daf2381e0ca345f554ae819e8be9df49d7e5b55869&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=f8751742213399420df255daf2381e0ca345f554ae819e8be9df49d7e5b55869&reaction=dislike'>π</a>
##########
tests/unit_tests/reports/notifications/slack_tests.py:
##########
@@ -431,3 +470,632 @@ def test_slack_mixin_get_body_truncates_large_table(
)
body = notification._get_body(content=content)
assert "(table was truncated)" in body
+
+
+# ---------------------------------------------------------------------------
+# Bulletproof v2 send-path coverage
+#
+# The tests above exercise the chat_postMessage path (text-only sends). The
+# tests below cover files_upload_v2 across screenshots/CSV/PDF, multi-channel
+# fan-out, exception mapping, backoff, statsd, and logs propagation. Together
+# they guarantee that every observable behavior of SlackV2Notification.send()
+# is locked down before Slack v1 is removed.
+# ---------------------------------------------------------------------------
+
+
+def _make_v2_notification(content, target: str = "C12345"):
Review Comment:
**Suggestion:** Annotate the untyped `content` parameter and the return type
of this helper so the function signature is fully typed. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
The helper is newly added and omits a type annotation for `content` as well
as a return type. That matches the type-hint rule violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=1c2d5312b36d432ea71a153b37c7417a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=1c2d5312b36d432ea71a153b37c7417a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/reports/notifications/slack_tests.py
**Line:** 486:486
**Comment:**
*Custom Rule: Annotate the untyped `content` parameter and the return
type of this helper so the function signature is fully typed.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=4e8aca492cc9f7bf8c6a1a316de98d1e048d7c6b2c4e6da7cdaa1a751733b58a&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=4e8aca492cc9f7bf8c6a1a316de98d1e048d7c6b2c4e6da7cdaa1a751733b58a&reaction=dislike'>π</a>
##########
tests/unit_tests/reports/notifications/slack_tests.py:
##########
@@ -431,3 +470,632 @@ def test_slack_mixin_get_body_truncates_large_table(
)
body = notification._get_body(content=content)
assert "(table was truncated)" in body
+
+
+# ---------------------------------------------------------------------------
+# Bulletproof v2 send-path coverage
+#
+# The tests above exercise the chat_postMessage path (text-only sends). The
+# tests below cover files_upload_v2 across screenshots/CSV/PDF, multi-channel
+# fan-out, exception mapping, backoff, statsd, and logs propagation. Together
+# they guarantee that every observable behavior of SlackV2Notification.send()
+# is locked down before Slack v1 is removed.
+# ---------------------------------------------------------------------------
+
+
+def _make_v2_notification(content, target: str = "C12345"):
+ """Helper to build a SlackV2Notification with a given target string."""
+ from superset.reports.models import ReportRecipients, ReportRecipientType
+
+ return SlackV2Notification(
+ recipient=ReportRecipients(
+ type=ReportRecipientType.SLACKV2,
+ recipient_config_json=f'{{"target": "{target}"}}',
+ ),
+ content=content,
+ )
+
+
+def _make_content(mock_header_data, **overrides):
Review Comment:
**Suggestion:** Provide type annotations for `mock_header_data`,
`overrides`, and the return type so this helper does not omit required type
hints. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This new helper lacks type hints for `mock_header_data`, `overrides`, and
the return type. That is a direct violation of the required Python type-hint
rule.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=16df20be93614a79817536f7695a4209&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=16df20be93614a79817536f7695a4209&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/reports/notifications/slack_tests.py
**Line:** 499:499
**Comment:**
*Custom Rule: Provide type annotations for `mock_header_data`,
`overrides`, and the return type so this helper does not omit required type
hints.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=22dd4d797bb4d8988ad827eef2228804606c2d04004e799cf8142ae35f7d38c7&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=22dd4d797bb4d8988ad827eef2228804606c2d04004e799cf8142ae35f7d38c7&reaction=dislike'>π</a>
##########
tests/unit_tests/utils/slack_test.py:
##########
@@ -287,3 +297,226 @@ def test_handle_pagination_multiple_pages(self, mocker):
{"name": "general", "id": "C12345"},
{"name": "random", "id": "C67890"},
]
+
+
+# ---------------------------------------------------------------------------
+# should_use_v2_api: drives the v1βv2 auto-upgrade decision and emits
+# DeprecationWarning + logger.warning for both no-flag and missing-scope cases.
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _reset_v1_warning_caches():
+ """Each test sees fresh once-per-process warning state.
+
+ The deprecation emitters are wrapped in `functools.cache` to give
+ thread-safe one-shot semantics in production. Tests need them to fire
+ again, so we clear the cache before and after each case.
+ """
Review Comment:
**Suggestion:** Add a full function signature annotation for this fixture,
including an explicit generator-compatible return type. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
The fixture function is newly added and has no return type annotation. Under
the type-hints rule, modified Python functions should include explicit
annotations where applicable, so this is a real violation.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=28bc172cb78e4a0580edcb0cd26cb608&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=28bc172cb78e4a0580edcb0cd26cb608&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/utils/slack_test.py
**Line:** 308:315
**Comment:**
*Custom Rule: Add a full function signature annotation for this
fixture, including an explicit generator-compatible return type.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=3fa1f0541dd7f4794c057a8e7ebd6d2af2096502a9d24b75a8c8e5e24d3ec90f&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=3fa1f0541dd7f4794c057a8e7ebd6d2af2096502a9d24b75a8c8e5e24d3ec90f&reaction=dislike'>π</a>
##########
tests/unit_tests/reports/notifications/slack_tests.py:
##########
@@ -431,3 +470,632 @@ def test_slack_mixin_get_body_truncates_large_table(
)
body = notification._get_body(content=content)
assert "(table was truncated)" in body
+
+
+# ---------------------------------------------------------------------------
+# Bulletproof v2 send-path coverage
+#
+# The tests above exercise the chat_postMessage path (text-only sends). The
+# tests below cover files_upload_v2 across screenshots/CSV/PDF, multi-channel
+# fan-out, exception mapping, backoff, statsd, and logs propagation. Together
+# they guarantee that every observable behavior of SlackV2Notification.send()
+# is locked down before Slack v1 is removed.
+# ---------------------------------------------------------------------------
+
+
+def _make_v2_notification(content, target: str = "C12345"):
+ """Helper to build a SlackV2Notification with a given target string."""
+ from superset.reports.models import ReportRecipients, ReportRecipientType
+
+ return SlackV2Notification(
+ recipient=ReportRecipients(
+ type=ReportRecipientType.SLACKV2,
+ recipient_config_json=f'{{"target": "{target}"}}',
+ ),
+ content=content,
+ )
+
+
+def _make_content(mock_header_data, **overrides):
+ """Helper to build a minimal NotificationContent."""
+ from superset.reports.notifications.base import NotificationContent
+
+ defaults: dict = {
+ "name": "test alert",
+ "header_data": mock_header_data,
+ "description": "desc",
+ }
+ defaults.update(overrides)
+ return NotificationContent(**defaults)
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_with_single_screenshot_calls_files_upload_v2(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {"execution_id": uuid.uuid4()}
+ content = _make_content(mock_header_data,
screenshots=[b"screenshot-bytes"])
+ notification = _make_v2_notification(content, target="C12345")
+
+ notification.send()
+
+ upload = slack_client_mock.return_value.files_upload_v2
+ upload.assert_called_once()
+ kwargs = upload.call_args.kwargs
+ assert kwargs["channel"] == "C12345"
+ assert kwargs["file"] == b"screenshot-bytes"
+ assert kwargs["title"] == "test alert"
+ assert kwargs["filename"] == "test alert.png"
+ assert "test alert" in kwargs["initial_comment"]
+ # chat_postMessage should NOT be called when files are present
+ slack_client_mock.return_value.chat_postMessage.assert_not_called()
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_with_multiple_screenshots_uploads_each(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ content = _make_content(
+ mock_header_data, screenshots=[b"shot-1", b"shot-2", b"shot-3"]
+ )
+ notification = _make_v2_notification(content, target="C12345")
+
+ notification.send()
+
+ upload = slack_client_mock.return_value.files_upload_v2
+ assert upload.call_count == 3
+ uploaded_files = [c.kwargs["file"] for c in upload.call_args_list]
+ assert uploaded_files == [b"shot-1", b"shot-2", b"shot-3"]
+ # All three uploads target the same single channel
+ for c in upload.call_args_list:
+ assert c.kwargs["channel"] == "C12345"
+ assert c.kwargs["filename"] == "test alert.png"
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_with_csv_calls_files_upload_v2(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ content = _make_content(mock_header_data, csv=b"col1,col2\n1,2\n")
+ notification = _make_v2_notification(content, target="C12345")
+
+ notification.send()
+
+ upload = slack_client_mock.return_value.files_upload_v2
+ upload.assert_called_once()
+ kwargs = upload.call_args.kwargs
+ assert kwargs["file"] == b"col1,col2\n1,2\n"
+ assert kwargs["filename"] == "test alert.csv"
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_with_pdf_calls_files_upload_v2(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ content = _make_content(mock_header_data, pdf=b"%PDF-1.4...")
+ notification = _make_v2_notification(content, target="C12345")
+
+ notification.send()
+
+ upload = slack_client_mock.return_value.files_upload_v2
+ upload.assert_called_once()
+ kwargs = upload.call_args.kwargs
+ assert kwargs["file"] == b"%PDF-1.4..."
+ assert kwargs["filename"] == "test alert.pdf"
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_to_multiple_channels_uploads_per_channel(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ content = _make_content(mock_header_data, screenshots=[b"shot-1",
b"shot-2"])
+ notification = _make_v2_notification(content,
target="C12345,C67890,C11111")
+
+ notification.send()
+
+ upload = slack_client_mock.return_value.files_upload_v2
+ # 3 channels x 2 files = 6 uploads
+ assert upload.call_count == 6
+ seen = {(c.kwargs["channel"], c.kwargs["file"]) for c in
upload.call_args_list}
+ assert seen == {
+ ("C12345", b"shot-1"),
+ ("C12345", b"shot-2"),
+ ("C67890", b"shot-1"),
+ ("C67890", b"shot-2"),
+ ("C11111", b"shot-1"),
+ ("C11111", b"shot-2"),
+ }
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_text_only_uses_chat_post_message(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345,C67890")
+
+ notification.send()
+
+ # No files β chat_postMessage per channel, no files_upload_v2 calls
+ slack_client_mock.return_value.files_upload_v2.assert_not_called()
+ chat = slack_client_mock.return_value.chat_postMessage
+ assert chat.call_count == 2
+ channels = sorted(c.kwargs["channel"] for c in chat.call_args_list)
+ assert channels == ["C12345", "C67890"]
+
+
+def test_v2_inline_files_precedence(mock_header_data) -> None:
+ """CSV beats screenshots beats PDF; only one inline-file type is sent."""
+ content = _make_content(
+ mock_header_data,
+ csv=b"a,b\n1,2",
+ screenshots=[b"shot-1"],
+ pdf=b"%PDF",
+ )
+ notification = _make_v2_notification(content, target="C12345")
+ file_type, files = notification._get_inline_files()
+ assert file_type == "csv"
+ assert files == [b"a,b\n1,2"]
+
+ content = _make_content(
+ mock_header_data,
+ screenshots=[b"shot-1"],
+ pdf=b"%PDF",
+ )
+ notification = _make_v2_notification(content, target="C12345")
+ file_type, files = notification._get_inline_files()
+ assert file_type == "png"
+ assert files == [b"shot-1"]
+
+ content = _make_content(mock_header_data, pdf=b"%PDF")
+ notification = _make_v2_notification(content, target="C12345")
+ file_type, files = notification._get_inline_files()
+ assert file_type == "pdf"
+ assert files == [b"%PDF"]
+
+
[email protected](
+ ("slack_exc_factory", "expected_exc"),
+ [
+ (
+ lambda: BotUserAccessError("bot user blocked"),
+ NotificationParamException,
+ ),
+ (
+ lambda: SlackRequestError("bad request"),
+ NotificationParamException,
+ ),
+ (
+ lambda: SlackClientConfigurationError("misconfigured"),
+ NotificationParamException,
+ ),
+ (
+ lambda: SlackObjectFormationError("malformed"),
+ NotificationMalformedException,
+ ),
+ (
+ lambda: SlackTokenRotationError(
+ SlackApiError(message="rotation failed", response={"ok":
False})
+ ),
+ NotificationAuthorizationException,
+ ),
+ (
+ lambda: SlackClientNotConnectedError("offline"),
+ NotificationUnprocessableException,
+ ),
+ (
+ # Fallback: any other SlackClientError becomes Unprocessable.
+ lambda: SlackClientError("misc client error"),
+ NotificationUnprocessableException,
+ ),
+ ],
+)
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_maps_slack_sdk_exceptions(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ slack_exc_factory,
+ expected_exc,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ slack_client_mock.return_value.chat_postMessage.side_effect =
slack_exc_factory()
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with pytest.raises(expected_exc):
+ notification.send()
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_retries_on_transient_slack_api_error(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ """`@backoff.on_exception(NotificationUnprocessableException, max_tries=5)`
+ retries the wrapped exception that send() actually raises.
+
+ A persistent Slack rate-limit (or any other transient failure that maps to
+ NotificationUnprocessableException) results in exactly max_tries=5 send
+ attempts before the final exception propagates. This mirrors the existing
+ pattern in webhook.py.
+ """
+ flask_global_mock.logs_context = {}
+ slack_client_mock.return_value.chat_postMessage.side_effect =
SlackApiError(
+ message="rate limited", response={"ok": False, "error": "ratelimited"}
+ )
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with pytest.raises(NotificationUnprocessableException):
+ notification.send()
+
+ assert slack_client_mock.return_value.chat_postMessage.call_count == 5
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_retries_then_succeeds_on_transient_failure(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ """The point of switching backoff to NotificationUnprocessableException is
+ that a *transient* failure now retries and the send ultimately succeeds β
+ behavior the old (dead) SlackApiError decorator never delivered. Fail
twice,
+ then succeed: send() must return normally after exactly 3 attempts and
still
+ record the success gauge.
+ """
+ flask_global_mock.logs_context = {}
+ slack_client_mock.return_value.chat_postMessage.side_effect = [
+ SlackApiError(
+ message="rate limited", response={"ok": False, "error":
"ratelimited"}
+ ),
+ SlackApiError(
+ message="rate limited", response={"ok": False, "error":
"ratelimited"}
+ ),
+ {"ok": True},
+ ]
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with patch(
+ "superset.extensions.stats_logger_manager.instance.gauge"
+ ) as statsd_mock:
+ notification.send()
+
+ assert slack_client_mock.return_value.chat_postMessage.call_count == 3
+ statsd_mock.assert_called_with("reports.slack.send.ok", 1)
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_retries_only_failed_channel(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ failed_attempts = 0
+
+ def chat_side_effect(channel: str, text: str) -> dict[str, bool]:
+ nonlocal failed_attempts
+ if channel == "C67890" and failed_attempts < 2:
+ failed_attempts += 1
+ raise SlackApiError(
+ message="rate limited", response={"ok": False, "error":
"ratelimited"}
+ )
+ return {"ok": True}
+
+ slack_client_mock.return_value.chat_postMessage.side_effect =
chat_side_effect
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345,C67890")
+
+ notification.send()
+
+ assert [
+ slack_call.kwargs["channel"]
+ for slack_call in
slack_client_mock.return_value.chat_postMessage.call_args_list
+ ] == ["C12345", "C67890", "C67890", "C67890"]
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_does_not_retry_permanent_slack_api_error(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ slack_client_mock.return_value.chat_postMessage.side_effect =
SlackApiError(
+ message="channel not found",
+ response={"ok": False, "error": "channel_not_found"},
+ )
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with pytest.raises(NotificationUnprocessableException):
+ notification.send()
+
+ assert slack_client_mock.return_value.chat_postMessage.call_count == 1
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_does_not_retry_param_errors(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ """Non-transient errors (config / auth / malformed) are NOT retried β only
+ NotificationUnprocessableException triggers backoff. A
+ NotificationParamException-class failure (BotUserAccessError β 422) hits
+ the API exactly once and surfaces immediately.
+ """
+ flask_global_mock.logs_context = {}
+ slack_client_mock.return_value.chat_postMessage.side_effect =
BotUserAccessError(
+ "bot user blocked"
+ )
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with pytest.raises(NotificationParamException):
+ notification.send()
+
+ assert slack_client_mock.return_value.chat_postMessage.call_count == 1
+
+
+def _make_slack_response(status_code: int, data: dict[str, Any]) ->
SlackResponse:
+ """Build an SDK-faithful SlackResponse that carries a real ``status_code``.
+
+ The existing retry tests pass ``SlackApiError(response={...})`` β a plain
+ dict, which has no ``status_code`` attribute. That makes
+ ``_get_slack_api_status_code`` return ``None`` and the ``429 / 5xx β
retry``
+ branch in ``_give_up_slack_api_retry`` is never exercised. The real SDK
hands
+ back a ``SlackResponse`` with a populated ``status_code``, so we mirror
that
+ here to cover the status-code branch faithfully.
+ """
+ return SlackResponse(
+ client=None,
+ http_verb="POST",
+ api_url="https://slack.com/api/chat.postMessage",
+ req_args={},
+ data=data,
+ headers={},
+ status_code=status_code,
+ )
+
+
[email protected](
+ "status_code,data",
+ [
+ # 5xx with an empty / unknown body: no `error` code to classify, so the
+ # status-code branch is the only thing that can decide to retry. This
is
+ # the case the dict-based tests silently lost.
+ (503, {"ok": False}),
+ (502, {}),
+ # Rate limiting is retryable by status code as well as error code.
+ (429, {"ok": False, "error": "ratelimited"}),
+ ],
+)
+def test_give_up_slack_api_retry_retries_on_status_code(
+ status_code: int, data: dict[str, Any]
+) -> None:
+ response = _make_slack_response(status_code, data)
+ ex = SlackApiError(message="transient", response=response)
+
+ # give_up == False -> the request WILL be retried by backoff.
+ assert _give_up_slack_api_retry(ex) is False
+
+
+def test_give_up_slack_api_retry_gives_up_on_permanent_status_code() -> None:
+ """Control: a 4xx (non-429) with a non-transient error code is not retried,
+ even when carried by a faithful SlackResponse β so the new helper above is
+ asserting the status-code branch, not merely that everything retries.
+ """
+ response = _make_slack_response(404, {"ok": False, "error":
"channel_not_found"})
+ ex = SlackApiError(message="permanent", response=response)
+
+ assert _give_up_slack_api_retry(ex) is True
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_records_statsd_gauge_on_success(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ flask_global_mock.logs_context = {}
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with patch(
+ "superset.extensions.stats_logger_manager.instance.gauge"
+ ) as statsd_mock:
+ notification.send()
+
+ statsd_mock.assert_called_with("reports.slack.send.ok", 1)
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_records_statsd_gauge_warning_on_param_error(
+ slack_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ """Status<500 exceptions (NotificationParamException is 422) β .warning."""
+ flask_global_mock.logs_context = {}
+ slack_client_mock.return_value.chat_postMessage.side_effect = (
+ SlackClientConfigurationError("bad config")
+ )
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+
+ with patch(
+ "superset.extensions.stats_logger_manager.instance.gauge"
+ ) as statsd_mock:
+ with pytest.raises(NotificationParamException):
+ notification.send()
+
+ assert call("reports.slack.send.warning", 1) in statsd_mock.call_args_list
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.logger")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_propagates_execution_id_to_logs(
+ slack_client_mock: MagicMock,
+ logger_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ """The success log carries the execution_id from g.logs_context."""
+ execution_id = uuid.uuid4()
+ flask_global_mock.logs_context = {"execution_id": execution_id}
+
+ content = _make_content(mock_header_data, screenshots=[b"shot"])
+ notification = _make_v2_notification(content, target="C12345")
+ notification.send()
+
+ logger_mock.info.assert_called_with(
+ "Report sent to slack", extra={"execution_id": execution_id}
+ )
+
+
+@patch("superset.reports.notifications.slackv2.g")
+@patch("superset.reports.notifications.slackv2.logger")
+@patch("superset.reports.notifications.slackv2.get_slack_client")
+def test_v2_send_handles_missing_logs_context(
+ slack_client_mock: MagicMock,
+ logger_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ mock_header_data,
+) -> None:
+ """When g.logs_context is None or missing, the log uses
execution_id=None."""
+ # Mirrors `getattr(g, "logs_context", {}) or {}` falsy-coalescing path.
+ flask_global_mock.logs_context = None
+
+ content = _make_content(mock_header_data)
+ notification = _make_v2_notification(content, target="C12345")
+ notification.send()
+
+ logger_mock.info.assert_called_with(
+ "Report sent to slack", extra={"execution_id": None}
+ )
+
+
+# ---------------------------------------------------------------------------
+# End-to-end auto-upgrade: v1 recipient β SlackV1NotificationError β upgrade β
+# row mutated to IDs β second send takes the v2 fast path with no resolution.
+# ---------------------------------------------------------------------------
+
+
+@patch(
+ "superset.utils.slack.feature_flag_manager.is_feature_enabled",
+ return_value=True,
+)
+@patch("superset.reports.notifications.slack.g")
+@patch("superset.utils.slack.get_slack_client")
+@patch("superset.reports.notifications.slack.get_slack_client")
+@patch("superset.commands.report.execute.get_channels_with_search")
+def test_auto_upgrade_round_trip_v1_to_v2(
+ get_channels_with_search_mock: MagicMock,
+ v1_client_mock: MagicMock,
+ util_client_mock: MagicMock,
+ flask_global_mock: MagicMock,
+ feature_flag_mock: MagicMock,
+ mock_header_data,
+) -> None:
Review Comment:
**Suggestion:** Add a type hint for the untyped fixture argument so the test
function signature is fully annotated. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This added test function leaves `mock_header_data` untyped while the rest of
the parameters are annotated. That is a real omission under the type-hint
requirement.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d59f47e436504265a0dac13c6f266a78&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=d59f47e436504265a0dac13c6f266a78&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/reports/notifications/slack_tests.py
**Line:** 1036:1043
**Comment:**
*Custom Rule: Add a type hint for the untyped fixture argument so the
test function signature is fully annotated.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=470d6a96cedfcaf156b5679c00501f70ab67d4dcfe065783b71722f06b0e8ffd&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=470d6a96cedfcaf156b5679c00501f70ab67d4dcfe065783b71722f06b0e8ffd&reaction=dislike'>π</a>
##########
tests/unit_tests/utils/slack_test.py:
##########
@@ -287,3 +297,226 @@ def test_handle_pagination_multiple_pages(self, mocker):
{"name": "general", "id": "C12345"},
{"name": "random", "id": "C67890"},
]
+
+
+# ---------------------------------------------------------------------------
+# should_use_v2_api: drives the v1βv2 auto-upgrade decision and emits
+# DeprecationWarning + logger.warning for both no-flag and missing-scope cases.
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def _reset_v1_warning_caches():
+ """Each test sees fresh once-per-process warning state.
+
+ The deprecation emitters are wrapped in `functools.cache` to give
+ thread-safe one-shot semantics in production. Tests need them to fire
+ again, so we clear the cache before and after each case.
+ """
+ _emit_v1_flag_off_deprecation.cache_clear()
+ _emit_v1_scope_missing_deprecation.cache_clear()
+ yield
+ _emit_v1_flag_off_deprecation.cache_clear()
+ _emit_v1_scope_missing_deprecation.cache_clear()
+
+
+class TestShouldUseV2Api:
+ def test_returns_true_when_flag_on_and_scopes_present(self, mocker):
+ mocker.patch(
+ "superset.utils.slack.feature_flag_manager.is_feature_enabled",
+ return_value=True,
+ )
+ mock_client = mocker.Mock()
+ mock_client.conversations_list.return_value = {
+ "channels": [{"id": "C1", "name": "general"}]
+ }
+ mocker.patch("superset.utils.slack.get_slack_client",
return_value=mock_client)
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ assert should_use_v2_api() is True
+ assert not any(issubclass(w.category, DeprecationWarning) for w in
caught)
+ mock_client.conversations_list.assert_called_once_with(
+ limit=1,
+ exclude_archived=True,
+ types="public_channel,private_channel",
+ )
+
+ def test_returns_false_when_flag_off_and_emits_deprecation_once(self,
mocker):
+ mocker.patch(
+ "superset.utils.slack.feature_flag_manager.is_feature_enabled",
+ return_value=False,
+ )
+ logger_mock = mocker.patch("superset.utils.slack.logger")
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ assert should_use_v2_api() is False
+ assert should_use_v2_api() is False # second call: no new warning
+ assert should_use_v2_api() is False # third call: no new warning
+
+ deprecation_warnings = [
+ w for w in caught if issubclass(w.category, DeprecationWarning)
+ ]
+ # Exactly one DeprecationWarning across three calls.
+ assert len(deprecation_warnings) == 1
+ assert str(deprecation_warnings[0].message) ==
_SLACK_V1_DEPRECATION_MESSAGE
+ # logger.warning fires only once for the same reason.
+ assert logger_mock.warning.call_count == 1
+ assert (
+ "ALERT_REPORT_SLACK_V2 is disabled" in
logger_mock.warning.call_args.args[0]
+ )
+
Review Comment:
**Suggestion:** Annotate all untyped parameters in this method and add an
explicit return type for consistency with typed Python code. [custom_rule]
**Severity Level:** Minor β οΈ
<details>
<summary><b>Why it matters? π€ </b></summary>
This added test method has untyped parameters and no explicit return
annotation, which violates the requirement to type-hint new or modified Python
functions and methods.
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e3747f6243d34c31b1fcd37897534063&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
[](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e3747f6243d34c31b1fcd37897534063&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
*(Use Cmd/Ctrl + Click for best experience)*
<details>
<summary><b>Prompt for AI Agent π€ </b></summary>
```mdx
This is a comment left during a code review.
**Path:** tests/unit_tests/utils/slack_test.py
**Line:** 345:369
**Comment:**
*Custom Rule: Annotate all untyped parameters in this method and add an
explicit return type for consistency with typed Python code.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask
user if the user wants to fix the rest of the comments as well. if said yes,
then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=bedd47bcc18285b7f9e4f2f1c1339ccc822b79d3461a7e68e29b14604e3c0e04&reaction=like'>π</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39914&comment_hash=bedd47bcc18285b7f9e4f2f1c1339ccc822b79d3461a7e68e29b14604e3c0e04&reaction=dislike'>π</a>
--
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]