You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "Vitor-Avila (via GitHub)" <gi...@apache.org> on 2026/10/05 21:22:25 UTC

[PR] feat: SIP-209 Improved Alerts & Reports [superset]

Vitor-Avila opened a new pull request, #44992:
URL: https://github.com/apache/superset/pull/44992

   ### SUMMARY
   This PR implements [SIP-209](https://github.com/apache/superset/issues/39642). 
   
   With the new `ALERT_REPORT_DYNAMIC_EXECUTOR` FF off, existing execution behavior is unchanged (fully backwards compatible). When enabled, **Run as** field controls content generation, including RLS and database OAuth2 credentials. Alerts can separately set **Run alert query as** for the SQL condition execution, or inherit **Run as**.
   
   Admins can choose a specific user or **Application default**, which uses `ALERT_REPORTS_EXECUTORS`. New schedules default to their creator, and existing schedules retain the application default until changed.
   Non-admins can only select themselves. When editing a schedule that runs under another identity, they can change metadata but must switch execution to their own account before changing content or recipients.
   
   The new Alerts & Reports configuration modal lets admins manage alert attachments, minimum alert and report intervals, email-subject date formatting, and recipient restrictions. All these configs fall back to the existing FF/config until a value is saved.
   
   The migration adds nullable executor references to report schedules and a UUID-keyed `report_config` table. It does not backfill or change existing schedules.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   <!--- Skip this if not applicable -->
   
   ### TESTING INSTRUCTIONS
   1. Apply `superset db upgrade` and keep `ALERT_REPORT_DYNAMIC_EXECUTOR` off. Run an existing alert and report to confirm they still use `ALERT_REPORTS_EXECUTORS`.
   2. Enable the flag and edit an existing schedule. Confirm **Application default** preserves its behavior. Create a schedule and confirm it defaults to the creator. As an admin, select a different **Run as** user; for an alert, choose a separate **Run alert query as** user and verify both identities are used during execution.
   3. As a non-admin editor of a schedule using another identity, confirm metadata edits are allowed and content/recipient edits require **Execute using my permissions**. Confirm the user picker is unavailable.
   4. Change each global setting in the configuration modal. Try a shorter-than-allowed interval and recipients excluded by the users-only and domain policies, including both policies together. Confirm conflicting existing schedules are listed and disallowed delivery is blocked.
   5. Turn off **Include attachment** for an alert and save it without an asset; then turn it on and confirm an asset and attachment settings are required. Put a `strftime` placeholder in an email subject and verify the date-format setting controls rendering.
   
   ### ADDITIONAL INFORMATION
   - [x] Has associated issue: https://github.com/apache/superset/issues/39642.
   - [x] Required feature flags: `ALERT_REPORT_DYNAMIC_EXECUTOR` for per-schedule executors.
   - [x] Changes UI
   - [x] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [x] Migration is atomic, supports rollback & is backwards-compatible
     - [x] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [x] Introduces new feature or API: `GET`/`PUT /api/v1/report/configuration/`
   - [ ] Removes existing feature or API
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4203206653


##########
superset/commands/report/update.py:
##########
@@ -65,6 +131,194 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _compare_fields(
+        self,
+        keys: frozenset[str],
+        current: dict[str, Any],
+        normalizers: dict[str, Callable[[Any], Any]],
+    ) -> set[str]:
+        """
+        Return submitted fields whose normalized values differ from the stored values
+        """
+        changed: set[str] = set()
+        for field in keys & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,

Review Comment:
   Done!



##########
superset/commands/report/update.py:
##########
@@ -65,6 +131,194 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _compare_fields(
+        self,
+        keys: frozenset[str],
+        current: dict[str, Any],
+        normalizers: dict[str, Callable[[Any], Any]],
+    ) -> set[str]:
+        """
+        Return submitted fields whose normalized values differ from the stored values
+        """
+        changed: set[str] = set()
+        for field in keys & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,
+            "recipients": _normalize_recipients,
+        }
+        return self._compare_fields(CONTENT_FIELDS, current, normalizers)
+
+    def _changed_condition_fields(self) -> set[str]:
+        """Return alert-condition fields that differ from the stored values."""
+        assert self._model is not None
+        current = {
+            "database": self._model.database_id,
+            "sql": self._model.sql,
+            "validator_type": self._model.validator_type,
+            "validator_config_json": _normalize_json(self._model.validator_config_json),
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "validator_config_json": _normalize_json,
+        }
+        return self._compare_fields(ALERT_CONDITION_FIELDS, current, normalizers)
+
+    def _validate_executors(
+        self,
+        report_type: str,
+        changed_content_fields: set[str],
+        changed_condition_fields: set[str],
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Resolve the "Run As" fields (SIP-209) on update.
+
+        Fields absent from the payload keep their stored value. Admins may set
+        any active user or explicit executor type. Clearing content restores the
+        legacy application-configured executor;
+        clearing the query executor inherits the content identity.
+        Non-admins may only point the fields at themselves and, when the schedule
+        executes as another user,
+        may not change its content or recipients: doing so would let an editor
+        read data with someone else's credentials.
+        """
+        assert self._model is not None
+        has_run_as = bool({"run_as", "run_as_type"} & self._properties.keys())
+        has_query_as = bool(
+            {"run_alert_query_as", "run_alert_query_as_type"} & self._properties.keys()
+        )
+        run_as_id = self._properties.pop("run_as", None)
+        query_as_id = self._properties.pop("run_alert_query_as", None)
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):
+            self._properties.pop("run_as_type", None)
+            self._properties.pop("run_alert_query_as_type", None)
+            return
+
+        run_as = (
+            self.validate_run_as(
+                "run_as", run_as_id, exceptions, default_to_current_user=False
+            )
+            if has_run_as
+            else self._model.run_as
+        )
+
+        query_as = None
+        if report_type == ReportScheduleType.REPORT:
+            if has_query_as and (
+                query_as_id is not None
+                or self._properties.get("run_alert_query_as_type") is not None
+            ):
+                exceptions.append(ReportScheduleRunAlertQueryAsNotAllowedError())
+            else:
+                self._properties["run_alert_query_as"] = None
+                self._properties["run_alert_query_as_type"] = None
+        elif has_query_as:
+            query_as = self.validate_run_as(
+                "run_alert_query_as",
+                query_as_id,
+                exceptions,
+                default_to_current_user=False,
+            )
+        else:
+            query_as = self._model.run_alert_query_as
+
+        if security_manager.is_admin():
+            return
+        current_user_id = get_user_id()
+        executes_as_other_user = any(
+            user is not None and user.id != current_user_id
+            for user in (run_as, query_as)
+        )
+        typed_executor = any(
+            self._properties.get(field, getattr(self._model, field))
+            not in (None, ExecutorType.FIXED_USER)
+            for field in ("run_as_type", "run_alert_query_as_type")
+        )
+        content_type = self._properties.get("run_as_type", self._model.run_as_type)
+        unresolved_executor = (
+            content_type is None
+            or (content_type == ExecutorType.FIXED_USER and run_as is None)
+            or (
+                report_type == ReportScheduleType.ALERT
+                and query_as is None
+                and self._properties.get(
+                    "run_alert_query_as_type", self._model.run_alert_query_as_type
+                )
+                == ExecutorType.FIXED_USER
+            )
+        )
+        if (
+            executes_as_other_user or typed_executor or unresolved_executor
+        ) and changed_content_fields:
+            exceptions.append(ReportScheduleRunAsContentForbiddenError())
+

Review Comment:
   Had a lot of thought about this one. I've decided to remove the `report_format` from the `CONTENT_FIELDS` definition. It doesn't really change the content someone is getting, just the format in which the content is delivered. It might change on the rare occasion of a server-side paginated chart, but I think it's a well-scoped scenario.
   
   The asset subscription modal only provides a way to update the format, it doesn't allow to edit any of the other `CONTENT_FIELDS`, so this flow also gets unblocked with this change. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4195509151


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -1782,10 +1981,30 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
     if (!currentAlert?.editors?.length) {
       errors.push(TRANSLATIONS.EDITORS_ERROR_TEXT);
     }
+    const needsContentExecutor =
+      isReport ||
+      (attachmentsEnabledForAlerts && reportFormat !== 'NONE') ||
+      !currentAlert?.run_alert_query_as_type;
+    if (
+      dynamicExecutorEnabled &&
+      isAdmin &&
+      ((needsContentExecutor &&
+        currentAlert?.run_as_type === 'fixed_user' &&
+        !currentAlert?.run_as?.value) ||

Review Comment:
   Addressed in new commit.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4199833846


##########
superset/commands/report/update.py:
##########
@@ -88,6 +284,14 @@ def validate(self) -> None:  # noqa: C901
 
         exceptions: list[ValidationError] = []
 
+        # Snapshot content changes before validators replace ids with objects.
+        # Only needed for the "Run As" authorization rules (SIP-209).
+        changed_content_fields = (

Review Comment:
   The content snapshot is taken here, before the `creation_method` block below replaces `recipients` with the requesting user's email. A non-admin editor who PUTs the stored recipients unchanged on a chart/dashboard subscription that runs as someone else compares as "no change", then gets their own address swapped in. The schedule keeps the other user's `run_as`, so that user's rendered content is delivered to the editor with no `ReportScheduleRunAsContentForbiddenError`. Should the snapshot be taken after the recipient rewrite, or should `recipients` be counted as changed whenever the rewrite alters them?



##########
superset/commands/report/update_config.py:
##########
@@ -0,0 +1,145 @@
+# 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.
+import logging
+from functools import partial
+from typing import Any
+
+from croniter import CroniterBadDateError
+
+from superset.commands.base import BaseCommand
+from superset.commands.report.exceptions import (
+    ReportConfigConflictError,
+    ReportConfigUpdateFailedError,
+)
+from superset.daos.report import ReportConfigDAO, ReportScheduleDAO
+from superset.reports.models import (
+    ReportConfigKey,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.reports.utils import cron_meets_minimum_interval, get_email_addresses
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateReportConfigCommand(BaseCommand):
+    """
+    Update the global Alerts & Reports configuration.
+
+    Recipient restrictions and minimum intervals are validated against every
+    existing schedule: when any of them would become invalid under the new
+    configuration the command fails and lists the impacted schedules, so admins
+    can fix them before tightening the policy. Enabling/disabling attachments
+    for alerts applies immediately to all alerts and is never a conflict.
+    """
+
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+        self._impacted: list[dict[str, Any]] = []
+
+    @transaction(on_error=partial(on_error, reraise=ReportConfigUpdateFailedError))
+    def run(self) -> dict[str, Any]:
+        self.validate()
+        ReportConfigDAO.upsert(self._properties)

Review Comment:
   Saving the configuration never checks attachment readiness. Create an alert with `report_format="PNG"` and no chart/dashboard while global attachments are off (`requires_attachment()` allows it), then turn attachments on here: the save succeeds, but the alert has no asset, so its next delivery fails in `_get_url()`. Should enabling attachments list such alerts as conflicts like the recipient and frequency checks do?



##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -418,6 +418,108 @@ ALERT_REPORTS_EXECUTORS = [FixedExecutor("admin")]
 
 Please refer to `ExecutorType` in the codebase for other executor types.
 
+#### Per-schedule "Run As" executor
+
+`ALERT_REPORTS_EXECUTORS` is a global, server-side setting that is invisible to the people
+configuring alerts and reports, which makes permission problems hard to diagnose and is
+especially painful for databases authenticated with OAuth2, where the impersonated account
+must hold a valid token. [SIP-209](https://github.com/apache/superset/issues/39642)
+introduces an explicit, per-schedule alternative behind the `ALERT_REPORT_DYNAMIC_EXECUTOR`
+[feature flag](/admin-docs/configuration/configuring-superset#feature-flags):
+
+```python
+FEATURE_FLAGS = {
+    "ALERT_REPORTS": True,
+    "ALERT_REPORT_DYNAMIC_EXECUTOR": True,
+}
+```
+
+When the flag is enabled:
+
+- Every alert/report gets a **Run as** field recording which user's RBAC permissions and
+  database credentials are used to render the content. Alerts get an additional
+  **Run alert query as** field for the alert condition SQL, so the audience of an alert
+  does not need direct database access.
+- Admins can select **Application default** or **Specific user**:
+  * **Application default:** resolves through `ALERT_REPORTS_EXECUTORS` value.
+  * **Specific user:** User picker option.
+  Non-admins can only select themselves. They see no user search and the API rejects
+  selecting another user. Reports scheduled from a dashboard or chart always execute
+  as the subscribing user.
+- When a non-admin edits an alert/report configured to run as someone else, they can
+  change its metadata, type, and condition (database, SQL, and validator), but not its
+  selected chart/dashboard, filters, attachment format, or recipients. To change those,
+  they must first set **Run as** to their own account via the **Execute using my permissions**
+  button (or ask an admin). For alerts, this action selects the current user for both content
+  and SQL condition execution. Legacy schedules without an explicit ``run_as`` user also
+  require this switch before a non-admin changes the delivered asset or recipients.
+- Untouched legacy schedules continue using `ALERT_REPORTS_EXECUTORS`. **Application
+  default** preserves this behavior in the Run as selector, including when an admin
+  clears an explicit executor.
+- A selected user that is deleted remains recorded as a **Specific user** selection.
+  Resolving a deleted or inactive user fails rather than switching to a legacy executor.
+  Alert SQL templates, SQL mutation hooks, authorization and database access all use
+  the query executor's identity.
+
+It's possible to set a custom "Run As" tooltip value via the `ALERT_REPORTS_RUN_AS_TOOLTIP`
+config in `superset_config.py`. This is useful if you want to provide further context on what
+the "Application default" means. **It does not change the feature behavior**.
+`ALERT_REPORTS_EXECUTORS` is deprecated in favor of this field and will be removed once the
+feature graduates from the flag.
+
+### Alerts & Reports configuration
+
+Admins can manage the global Alerts & Reports settings at runtime from the **Configuration**
+button on the Alerts & Reports list page (also available through
+`GET`/`PUT /api/v1/report/configuration/`). Values are stored in the `report_config` table;
+a setting that was never saved falls back to the corresponding `superset_config.py` value or
+feature flag.
+
+| Setting | Fallback | Description |
+| --- | --- | --- |
+| Enable attachments for alerts | `ALERTS_ATTACH_REPORTS` FF | Whether alerts deliver their attachment. Applies to subsequent attempts; saving a change cancels pending attempts. |

Review Comment:
   This row says saving the setting "cancels pending attempts", but `UpdateReportConfigCommand` only validates and upserts, and the retry section further down says setting changes don't cancel queued retries (they read the latest value when they start). An admin disabling attachments would expect a pending retry to be dropped when it still runs. Could this sentence be removed?



##########
superset/commands/report/update.py:
##########
@@ -42,17 +47,61 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(

Review Comment:
   `CONTENT_FIELDS` doesn't include `sql`, `database` or the validator fields, so a non-admin editor can rewrite an alert's condition while `run_alert_query_as` still points at another user. Save-time `validate_alert_query` authorizes as the saving user and skips the check when templated SQL doesn't parse before rendering, while execution renders and runs the query as the stored executor. For example, an editor submits `{% if current_username() != 'editor' %}SELECT secret FROM restricted.t LIMIT 1{% else %}SELECT 1{% endif %}`, runs the alert, and reads the result from `last_value_row_json` or the log `value`. Should changes to the alert query count as content for the other-identity guard?



##########
superset/commands/report/update.py:
##########
@@ -42,17 +47,61 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(
+    {
+        "chart",
+        "dashboard",
+        "extra",
+        "recipients",
+        "report_format",
+    }
+)
+
+
+def _normalize_json(value: Any) -> str:
+    """Canonical JSON string for a dict/JSON-string value (for comparisons)."""
+    if isinstance(value, str):
+        try:
+            value = json.loads(value)
+        except json.JSONDecodeError:
+            return value
+    if value is None:
+        value = {}
+    if not isinstance(value, (dict, list)):
+        return str(value)
+    return json.dumps(value, sort_keys=True)
+
+
+def _normalize_recipients(recipients: Any) -> list[tuple[str, str]]:
+    """Canonical, order-independent representation of a recipients list."""
+    normalized: list[tuple[str, str]] = []
+    for recipient in recipients or []:
+        if isinstance(recipient, dict):
+            recipient_type = recipient.get("type")
+            config = recipient.get("recipient_config_json")
+        else:
+            recipient_type = recipient.type
+            config = recipient.recipient_config_json
+        normalized.append((str(recipient_type), _normalize_json(config)))

Review Comment:
   A legacy recipient stored as `{"target": "a@x.com"}` (e.g. from chart/dashboard subscriptions) is compared with the modal's resubmitted `{"target": ..., "ccTarget": "", "bccTarget": ""}`, so the JSON differs and `recipients` is flagged as changed. With the flag on, a non-admin renaming a schedule that runs as another user or the application default then gets `ReportScheduleRunAsContentForbiddenError` without touching recipients. Should empty `ccTarget`/`bccTarget` be dropped before comparing?



##########
superset/reports/schemas.py:
##########
@@ -125,6 +127,46 @@
     "Creation method is used to inform the frontend whether the report/alert was "
     "created in the dashboard, chart, or alerts and reports UI."
 )
+run_as_description = (
+    "ID of the user whose credentials (RBAC permissions, database OAuth2 tokens) "
+    "are used when rendering the content (screenshot, PDF, CSV, XLSX or text). "
+    "Admins can set any active user; non-admins can only set themselves. Only"
+    "honored when the ALERT_REPORT_DYNAMIC_EXECUTOR feature flag is enabled. "
+    "Admins can set this and run_as_type to null to use ALERT_REPORTS_EXECUTORS."
+)
+run_alert_query_as_description = (
+    "ID of the user whose credentials are used when running the alert condition "
+    "SQL query, useful when the audience of the alert does not have access to the "
+    "database. Null inherits the content executor at execution time."
+)
+
+
+_RUN_AS_FIELD_KEYS = (
+    "run_as",
+    "run_alert_query_as",
+    "run_as_type",
+    "run_alert_query_as_type",
+)
+_REPORT_EXECUTOR_TYPES = [
+    ExecutorType.FIXED_USER,
+]
+
+
+class RunAsFieldStripMixin:
+    """Drop the "Run As" fields from the raw payload when the dynamic executor
+    feature (``ALERT_REPORT_DYNAMIC_EXECUTOR``) is disabled, so callers on the
+    legacy path never store an executor by accident."""
+
+    @pre_load
+    def strip_run_as_fields_if_disabled(
+        self,
+        data: dict[str, Any],
+        **kwargs: Any,
+    ) -> dict[str, Any]:
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):

Review Comment:
   Nothing exercises this `pre_load` strip: the schema tests deserialize single fields, and the command tests bypass the schemas. If the hook were removed, a legacy client posting `run_as_type: "creator"` with `ALERT_REPORT_DYNAMIC_EXECUTOR` off would start getting validation errors (or storing an executor) and no test would fail. Could a test `load()` a POST/PUT payload with the flag off and assert the four executor keys are absent, and with it on that invalid values error?



##########
superset/commands/report/base.py:
##########
@@ -345,45 +393,118 @@ def validate_report_frequency(
         report_type: str,
     ) -> None:
         """
-        Validates if the report scheduled frequency doesn't exceed a limit
-        configured in `config.py`.
+        Validates if the report scheduled frequency doesn't exceed the minimum
+        interval in effect.
 
         :param cron_schedule: The cron schedule configured.
         :param report_type: The report type (Alert/Report).
         """
         config_key = (
-            "ALERT_MINIMUM_INTERVAL"
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL
             if report_type == ReportScheduleType.ALERT
-            else "REPORT_MINIMUM_INTERVAL"
+            else ReportConfigKey.REPORT_MINIMUM_INTERVAL
         )
-        minimum_interval = app.config.get(config_key, 0)
-        if callable(minimum_interval):
-            minimum_interval = minimum_interval()
+        minimum_interval = ReportConfigDAO.get_effective_value(config_key)

Review Comment:
   The new tests stub `validate_report_frequency` in the create/update fixtures, and the DAO and cron helper tests cover their pieces separately, so nothing checks that this lookup uses the saved minimum. If it fell back to the app config, a saved report minimum of 600 with an app minimum of 0 would still accept `* * * * *` and every current test would pass. Could a test call `validate_report_frequency()` against the real `ReportConfigDAO` and assert `ReportScheduleFrequencyNotAllowed`?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4189046207


##########
superset/daos/report.py:
##########
@@ -392,3 +399,215 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def invalidate_pending_executions(schedule_ids: list[int] | None = None) -> None:
+        """Fence queued retries and running attempts after a configuration save.
+
+        The caller's transaction holds row locks only while saving metadata.
+        Preserve execution windows so old cron messages cannot replay the work.
+        """
+        query = db.session.query(ReportSchedule).filter(
+            ReportSchedule.last_state.in_([ReportState.WORKING, ReportState.RETRYING])
+        )
+        if schedule_ids is not None:
+            query = query.filter(ReportSchedule.id.in_(schedule_ids))
+        for schedule in query.populate_existing().with_for_update().all():
+            if schedule.execution_owner:
+                db.session.query(ReportExecutionLog).filter(
+                    ReportExecutionLog.report_schedule_id == schedule.id,
+                    ReportExecutionLog.uuid == UUID(schedule.execution_owner),
+                    ReportExecutionLog.state.in_(
+                        [ReportState.WORKING, ReportState.RETRYING]
+                    ),
+                ).update(
+                    {
+                        ReportExecutionLog.state: ReportState.ERROR,
+                        ReportExecutionLog.end_dttm: datetime.utcnow(),
+                        ReportExecutionLog.error_message: (
+                            "Execution cancelled: configuration changed"
+                        ),
+                    },
+                    synchronize_session=False,
+                )
+            schedule.execution_owner = str(uuid4())
+            schedule.last_state = ReportState.ERROR
+            schedule.last_eval_dttm = datetime.utcnow()
+            schedule.retry_attempt = 0
+            schedule.retry_scheduled_dttm = None
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) with at least one e-mail recipient.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .join(
+                ReportRecipients,
+                ReportRecipients.report_schedule_id == ReportSchedule.id,
+            )
+            .filter(ReportRecipients.type == ReportRecipientType.EMAIL)
+            .options(selectinload(ReportSchedule.recipients))
+            .distinct()
+            .all()
+        )
+
+    @staticmethod
+    def find_by_type(report_type: ReportScheduleType) -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) of the given type.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.type == report_type)
+            .all()
+        )
+
+
+class ReportConfigDAO:
+    """
+    Access to the global Alerts & Reports configuration (``report_config``).
+
+    Values are stored as JSON-encoded key-value rows. A key without a row is
+    "not configured" and resolves to the legacy application config or feature
+    flag through :meth:`get_effective_value`, which keeps deployments that never
+    open the configuration UI behaving exactly as before.
+    """
+
+    @staticmethod
+    def get_stored_values() -> dict[str, Any]:
+        """
+        Return the raw stored configuration, keyed by :class:`ReportConfigKey`.
+
+        Read and decoding failures propagate: unavailable policy is not an
+        unrestricted policy. A stored null remains distinct from a missing row.
+        """
+        rows = db.session.query(ReportConfig).all()
+        return {
+            row.key: json.loads(row.value) if row.value is not None else None
+            for row in rows
+        }
+
+    @staticmethod
+    def get_fallback_value(key: ReportConfigKey) -> Any:
+        """Return the legacy application config / feature flag value for ``key``."""
+        if key == ReportConfigKey.ALERTS_ATTACH_REPORTS:
+            return feature_flag_manager.is_feature_enabled("ALERTS_ATTACH_REPORTS")
+        if key == ReportConfigKey.DATE_FORMAT_IN_EMAIL_SUBJECT:
+            return feature_flag_manager.is_feature_enabled(
+                "DATE_FORMAT_IN_EMAIL_SUBJECT"
+            )
+        if key in (
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL,
+            ReportConfigKey.REPORT_MINIMUM_INTERVAL,
+        ):
+            value = current_app.config.get(key.upper(), 0)
+            return value() if callable(value) else value
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return False
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return []
+        return None
+
+    @staticmethod
+    def get_effective_value(key: ReportConfigKey) -> Any:
+        """
+        Return the value in effect for ``key``: the stored value when present,
+        otherwise the legacy fallback.
+        """
+        if key in (stored := ReportConfigDAO.get_stored_values()):
+            return stored[key]
+        return ReportConfigDAO.get_fallback_value(key)
+
+    @staticmethod
+    def get_effective_config() -> dict[str, Any]:
+        """Return the value in effect for every :class:`ReportConfigKey`."""
+        stored = ReportConfigDAO.get_stored_values()
+        return {
+            key.value: (
+                stored[key]
+                if key in stored
+                else ReportConfigDAO.get_fallback_value(key)
+            )
+            for key in ReportConfigKey
+        }
+
+    @staticmethod
+    def upsert(values: dict[str, Any]) -> None:
+        """
+        Store values, retaining an explicit null as a configured value.
+        Only keys without a row inherit application configuration. Does not commit.
+        """
+        rows = {row.key: row for row in db.session.query(ReportConfig).all()}
+        for key, value in values.items():
+            key = str(ReportConfigKey(key))
+            row = rows.get(key)
+            if row is None:
+                row = ReportConfig(key=key)
+                db.session.add(row)

Review Comment:
   **Suggestion:** Concurrent first saves of the same key can both see no row and insert; the unique key rejects one request, so that configuration update fails.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Rarely` ยท ๐Ÿท๏ธ `Race condition`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e79dfd710dba4eeb8bfb476da53f3329&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e79dfd710dba4eeb8bfb476da53f3329&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/daos/report.py
   **Line:** 542:548
   **Comment:**
   	*Race Condition: Concurrent first saves of the same key can both see no row and insert; the unique key rejects one request, so that configuration update fails.
   
   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%2F44992&comment_hash=4cbdc2cc5063c30cd9efac4e91e1f72ba7c2ae63514c9986be5578ed3f46c107&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=4cbdc2cc5063c30cd9efac4e91e1f72ba7c2ae63514c9986be5578ed3f46c107&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/reports/api.py:
##########
@@ -93,16 +99,24 @@ def ensure_alert_reports_enabled(self) -> Optional[Response]:
         "slack_channels",  # not using RouteMethod since locally defined
         "subscribe",
         "execute",  # not using RouteMethod since locally defined
+        "get_configuration",
+        "put_configuration",
     }
     class_permission_name = "ReportSchedule"
-    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
+    method_permission_name = {
+        **MODEL_API_RW_METHOD_PERMISSION_MAP,
+        "get_configuration": "read",
+        "put_configuration": "write",
+    }
     resource_name = "report"
     allow_browser_login = True
 
     extra_fields_rel_fields = {
         **BaseSupersetModelRestApi.extra_fields_rel_fields,
         "created_by": ["email", "active"],
         "editors": ["type", "active", "secondary_label", "img"],
+        "run_as": ["email", "active"],
+        "run_alert_query_as": ["email", "active"],

Review Comment:
   **Suggestion:** Any user with report-list access can query these related fields and receive executor emails and active status; the guard only restricts editors and viewers.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Rarely` ยท ๐Ÿท๏ธ `Security`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b32bac42abf34d90ab2735d8bf46dca1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b32bac42abf34d90ab2735d8bf46dca1&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/reports/api.py
   **Line:** 118:119
   **Comment:**
   	*Security: Any user with report-list access can query these related fields and receive executor emails and active status; the guard only restricts editors and viewers.
   
   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%2F44992&comment_hash=9f4b483dda57f48b27cc0d41542e585cf388db5c494bfc7d72cb261e0e28908e&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=9f4b483dda57f48b27cc0d41542e585cf388db5c494bfc7d72cb261e0e28908e&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4195439163


##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -418,6 +418,117 @@ ALERT_REPORTS_EXECUTORS = [FixedExecutor("admin")]
 
 Please refer to `ExecutorType` in the codebase for other executor types.
 
+#### Per-schedule "Run As" executor
+
+`ALERT_REPORTS_EXECUTORS` is a global, server-side setting that is invisible to the people
+configuring alerts and reports, which makes permission problems hard to diagnose and is
+especially painful for databases authenticated with OAuth2, where the impersonated account
+must hold a valid token. [SIP-209](https://github.com/apache/superset/issues/39642)
+introduces an explicit, per-schedule alternative behind the `ALERT_REPORT_DYNAMIC_EXECUTOR`
+[feature flag](/admin-docs/configuration/configuring-superset#feature-flags):
+
+```python
+FEATURE_FLAGS = {
+    "ALERT_REPORTS": True,
+    "ALERT_REPORT_DYNAMIC_EXECUTOR": True,
+}
+```
+
+When the flag is enabled:
+
+- Every alert/report gets a **Run as** field recording which user's RBAC permissions and
+  database credentials are used to render the content. Alerts get an additional
+  **Run alert query as** field for the alert condition SQL, so the audience of an alert
+  does not need direct database access.
+- Admins can select **Application default** or **Specific user**:
+  * **Application default:** resolves through `ALERT_REPORTS_EXECUTORS` value.
+  * **Specific user:** User picker option.
+  Non-admins can only select themselves. They see no user search and the API rejects
+  selecting another user. Reports scheduled from a dashboard or chart always execute
+  as the subscribing user.
+- When a non-admin edits an alert/report that an admin configured to run as someone else,
+  they can change its metadata (name, schedule, active state, retries) but not its
+  content or recipients. To change those, they must first set **Run as** to their own
+  account using **Run as me** (or ask an admin). The form explains the restriction before
+  saving. For alerts, this action selects the current user for both content and condition
+  execution. It takes effect on Save and requires that user to have access to both.
+  Legacy schedules without an explicit content user also require this switch before
+  a non-admin changes content or recipients; metadata-only edits preserve their settings.
+- Untouched legacy schedules continue using `ALERT_REPORTS_EXECUTORS`. **Application
+  default** preserves this behavior in the Run as selector, including when an admin
+  clears an explicit executor. The API represents it with `run_as: null` and
+  `run_as_type: null`; omitting both fields on update preserves the stored executor.
+  New schedules default to the creator unless an admin selects Application default.
+  Clearing **Run alert query as** selects **Same as Run as**:
+  it follows later content-executor changes rather than copying the user at save time.
+- A selected user that is deleted remains recorded as a **Specific user** selection.
+  Resolving a deleted or inactive user fails rather than switching to a legacy executor.
+  Alert SQL templates, SQL mutation hooks, authorization and database access all use
+  the query executor's identity.
+
+`ALERT_REPORTS_EXECUTORS` is deprecated in favor of this field and will be removed once the
+feature graduates from the flag.
+
+### Alerts & Reports configuration
+
+Admins can manage the global Alerts & Reports settings at runtime from the **Configuration**
+button on the Alerts & Reports list page (also available through
+`GET`/`PUT /api/v1/report/configuration/`). Values are stored in the `report_config` table;
+a setting that was never saved falls back to the corresponding `superset_config.py` value or
+feature flag. The form saves only changed settings.
+Clearing an interval stores an explicit `null`, which means no minimum interval; it does
+not restore the application fallback. API `null` values likewise clear settings: attachment,
+date-format, and users-only switches become off, and domains become unrestricted. An explicit null row
+is retained. Configuration read or decoding failures are errors, never unrestricted defaults.
+
+| Setting | Fallback | Description |
+| --- | --- | --- |
+| Enable attachments for alerts | `ALERTS_ATTACH_REPORTS` feature flag | Whether alerts deliver their attachment. Applies to subsequent attempts; saving a change cancels pending attempts. |
+| Format dates in email subjects | `DATE_FORMAT_IN_EMAIL_SUBJECT` feature flag | Render date code placeholders in alert and report email subjects using the UTC date at delivery. |
+| Alert minimum interval | `ALERT_MINIMUM_INTERVAL` | Minimum interval between two executions of an alert. |
+| Report minimum interval | `REPORT_MINIMUM_INTERVAL` | Minimum interval between two executions of a report. |
+| Limit recipients to users | off | Only e-mail addresses of existing active users are accepted as recipients. |
+| Allowed e-mail domains | any | Allow-list of e-mail domains accepted as recipients. |
+
+Saving a stricter configuration is refused when existing alerts/reports (including disabled schedules) would violate it
+(a recipient outside the allowed domains, an address that is not a user, or a schedule that
+runs more often than the new minimum interval). The response lists the impacted schedules
+in pages of ten so they can be fixed first. The recipient policy is enforced when saving an alert/report
+and again at execution time, so a delivery to a recipient that is no longer allowed fails
+instead of being sent. These restrictions also apply to configured recipients of retry
+and final-failure notices. Owner/editor operational error notices are exempt; if recipient
+validation fails during a retry notice, only eligible operational notices are attempted.
+
+Domain matching is case-insensitive. An exact entry such as `example.com` does not
+include subdomains. Use wildcards like `*.example.com` / `example.* `to allow subdomains
+at any depth. Combining leading and trailing wildcards, or placing wildcards inside a label,

Review Comment:
   Clarified in a new commit.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213734816


##########
superset/commands/report/update.py:
##########
@@ -42,17 +48,97 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(

Review Comment:
   It's a fair point. I was thinking that `type` doesn't really change the content, but you're right that the change could effectively include an attachment that wasn't sent before. Fixing it.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4192056920


##########
superset/commands/report/update_config.py:
##########
@@ -0,0 +1,148 @@
+# 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.
+import logging
+from functools import partial
+from typing import Any
+
+from croniter import CroniterBadDateError
+
+from superset.commands.base import BaseCommand
+from superset.commands.report.exceptions import (
+    ReportConfigConflictError,
+    ReportConfigUpdateFailedError,
+)
+from superset.daos.report import ReportConfigDAO, ReportScheduleDAO
+from superset.reports.models import (
+    ReportConfigKey,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.reports.utils import cron_meets_minimum_interval, get_email_addresses
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateReportConfigCommand(BaseCommand):
+    """
+    Update the global Alerts & Reports configuration.
+
+    Recipient restrictions and minimum intervals are validated against every
+    existing schedule: when any of them would become invalid under the new
+    configuration the command fails and lists the impacted schedules, so admins
+    can fix them before tightening the policy. Enabling/disabling attachments
+    for alerts applies immediately to all alerts and is never a conflict.
+    """
+
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+        self._impacted: list[dict[str, Any]] = []
+
+    @transaction(on_error=partial(on_error, reraise=ReportConfigUpdateFailedError))
+    def run(self) -> dict[str, Any]:
+        self.validate()
+        effective = ReportConfigDAO.get_effective_config()
+        if any(effective.get(key) != value for key, value in self._properties.items()):
+            ReportScheduleDAO.invalidate_pending_executions()
+        ReportConfigDAO.upsert(self._properties)

Review Comment:
   While this is true, I don't think it's something this PR is introducing/specific to it. This type of race condition would happen in other flows as well.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4203209188


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -2327,310 +2613,461 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
               ),
               children: (
                 <>
-                  <StyledInputContainer>
-                    <div className="control-label">
-                      {t('Content type')}
-                      <span className="required">*</span>
-                    </div>
-                    <Select
-                      ariaLabel={t('Select content type')}
-                      onChange={onContentTypeChange}
-                      value={contentType}
-                      options={CONTENT_TYPE_OPTIONS}
-                      placeholder={t('Select content type')}
+                  {dynamicExecutorEnabled && !isAdmin && (
+                    <Alert
+                      type={restrictedExecutor ? 'warning' : 'info'}
+                      showIcon
+                      message={
+                        restrictedExecutor
+                          ? t('Content and recipient edits are restricted')
+                          : t('Content and permissions')
+                      }
+                      description={
+                        restrictedExecutor ? (
+                          <>
+                            <p>
+                              {t(

Review Comment:
   Done!



##########
superset/commands/report/alert.py:
##########
@@ -214,37 +216,41 @@ def _execute_query(self) -> pd.DataFrame:
         :raises AlertQueryError: SQL query is not valid
         :raises AlertQueryTimeout: The SQL query received a celery soft timeout
         """
-        sql_template = jinja_context.get_template_processor(
-            database=self._report_schedule.database
-        )
-
         try:
-            rendered_sql = sql_template.process_template(self._report_schedule.sql)
-            self._validate_rendered_sql(rendered_sql)
-            limited_rendered_sql = self._report_schedule.database.apply_limit_to_sql(
-                rendered_sql, ALERT_SQL_LIMIT
-            )
-
-            if app.config["MUTATE_ALERT_QUERY"]:
-                limited_rendered_sql = (
-                    self._report_schedule.database.mutate_sql_based_on_config(
-                        limited_rendered_sql
-                    )
+            user = get_dynamic_executor(self._report_schedule, alert_query=True)
+            if user is not None:
+                username = user.username
+            else:
+                executor, username = get_executor(  # pylint: disable=unused-variable
+                    executors=app.config["ALERT_REPORTS_EXECUTORS"],
+                    model=self._report_schedule,
                 )
-
-            executor, username = get_executor(  # pylint: disable=unused-variable
-                executors=app.config["ALERT_REPORTS_EXECUTORS"],
-                model=self._report_schedule,
-            )
-            user = security_manager.find_user(username)
+                user = security_manager.find_user(username)
             # A deleted/disabled executor user makes find_user return None. Raise
             # the dedicated error so the handler below re-surfaces it instead of
             # masking it as an opaque AlertQueryError (or letting the missing user
             # surface as a NoneType error from the downstream auth flow).
-            if user is None:
+            if user is None or not user.is_active:
                 raise ReportScheduleExecutorNotFoundError(username)
 
             with override_user(user):
+                sql_template = jinja_context.get_template_processor(

Review Comment:
   Done!



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4211902344


##########
tests/integration_tests/reports/api_tests.py:
##########
@@ -66,6 +68,249 @@
 
 
 class TestReportSchedulesApi(SupersetTestCase):
+    @pytest.fixture
+    def sip_schedule_cleanup(self) -> Iterator[None]:
+        """Remove schedules created by dynamic-executor API scenarios."""
+        yield
+        for schedule in db.session.query(ReportSchedule).filter(
+            ReportSchedule.name.like("sip209_api_%")
+        ):
+            db.session.delete(schedule)
+        db.session.commit()
+
+    def _sip_report_payload(self, name: str) -> dict[str, Any]:
+        """Build a chart report with the ordinary API-required fields."""
+        chart = db.session.query(Slice).first()
+        assert chart is not None
+        return {
+            "type": ReportScheduleType.REPORT,
+            "name": name,
+            "description": "Dynamic executor integration test",
+            "creation_method": ReportCreationMethod.ALERTS_REPORTS,
+            "crontab": "0 9 * * *",
+            "chart": chart.id,
+        }
+
+    @parameterized.expand([(False,), (True,)])
+    @with_feature_flags(ALERT_REPORT_DYNAMIC_EXECUTOR=True)
+    @pytest.mark.usefixtures(
+        "load_birth_names_dashboard_with_slices", "sip_schedule_cleanup"
+    )
+    def test_admin_create_report_executor(self, application_default: bool) -> None:
+        """An admin may choose their own account or the application default."""
+        self.login(ADMIN_USERNAME)
+        admin = self.get_user(ADMIN_USERNAME)
+        payload = self._sip_report_payload(f"sip209_api_admin_{application_default}")
+        payload.update(
+            {
+                "run_as": None if application_default else admin.id,
+                "run_as_type": None if application_default else ExecutorType.FIXED_USER,
+            }
+        )
+
+        response = self.client.post("/api/v1/report/", json=payload)
+        assert response.status_code == 201, response.json
+        schedule = db.session.get(ReportSchedule, response.json["id"])
+        assert schedule.run_as_fk == (None if application_default else admin.id)
+        assert schedule.run_as_type == (
+            None if application_default else ExecutorType.FIXED_USER
+        )
+
+    @with_feature_flags(ALERT_REPORT_DYNAMIC_EXECUTOR=True)
+    @pytest.mark.usefixtures(
+        "load_birth_names_dashboard_with_slices", "sip_schedule_cleanup"
+    )
+    def test_report_list_includes_executor_identity(self) -> None:
+        """The subscription editor can distinguish self from application default."""
+        self.login(ADMIN_USERNAME)
+        admin = self.get_user(ADMIN_USERNAME)
+        payload = self._sip_report_payload("sip209_api_subscription_executor")
+        payload.update({"run_as": admin.id, "run_as_type": "fixed_user"})
+        created = self.client.post("/api/v1/report/", json=payload)
+        assert created.status_code == 201, created.json
+
+        query = rison.dumps(
+            {"filters": [{"col": "id", "opr": "eq", "value": created.json["id"]}]}
+        )
+        response = self.client.get(f"/api/v1/report/?q={query}")
+        assert response.status_code == 200, response.json
+        assert response.json["result"][0]["run_as_type"] == "fixed_user"
+        assert response.json["result"][0]["run_as"]["id"] == admin.id
+
+    @parameterized.expand([("self",), ("default",), ("other",)])
+    @with_feature_flags(ALERT_REPORT_DYNAMIC_EXECUTOR=True)
+    @pytest.mark.usefixtures(
+        "load_birth_names_dashboard_with_slices", "sip_schedule_cleanup"
+    )
+    def test_non_admin_create_report_executor(self, executor: str) -> None:
+        """A non-admin can select only their own account."""
+        alpha = self.get_user("alpha")
+        admin = self.get_user(ADMIN_USERNAME)
+        self.login("alpha")
+        payload = self._sip_report_payload(f"sip209_api_alpha_{executor}")
+        if executor == "self":
+            payload.update({"run_as": alpha.id, "run_as_type": "fixed_user"})
+        elif executor == "default":
+            payload.update({"run_as": None, "run_as_type": None})
+        else:
+            payload.update({"run_as": admin.id, "run_as_type": "fixed_user"})
+
+        response = self.client.post("/api/v1/report/", json=payload)
+        if executor == "self":
+            assert response.status_code == 201, response.json
+            schedule = db.session.get(ReportSchedule, response.json["id"])
+            assert schedule.run_as_fk == alpha.id
+        else:
+            assert response.status_code == 422, response.json
+            assert "run_as" in response.json["message"]
+
+    @with_feature_flags(ALERT_REPORT_DYNAMIC_EXECUTOR=True)
+    @pytest.mark.usefixtures(
+        "load_birth_names_dashboard_with_slices", "sip_schedule_cleanup"
+    )
+    def test_non_admin_edits_own_executor_report(self) -> None:
+        """An owner may change content when the schedule runs as that owner."""
+        alpha = self.get_user("alpha")
+        self.login("alpha")
+        payload = self._sip_report_payload("sip209_api_owned")
+        payload.update({"run_as": alpha.id, "run_as_type": "fixed_user"})
+        created = self.client.post("/api/v1/report/", json=payload)
+        assert created.status_code == 201, created.json
+
+        response = self.client.put(
+            f"/api/v1/report/{created.json['id']}",
+            json={
+                "recipients": [
+                    {
+                        "type": ReportRecipientType.EMAIL,
+                        "recipient_config_json": {"target": alpha.email},
+                    }
+                ]
+            },
+        )
+        assert response.status_code == 200, response.json
+        schedule = db.session.get(ReportSchedule, created.json["id"])
+        assert schedule.run_as_fk == alpha.id
+        assert len(schedule.recipients) == 1
+
+    @with_feature_flags(ALERT_REPORT_DYNAMIC_EXECUTOR=True)
+    @pytest.mark.usefixtures(
+        "load_birth_names_dashboard_with_slices", "sip_schedule_cleanup"
+    )
+    def test_non_admin_edits_other_executor_report(self) -> None:
+        """An editor may change metadata, but content requires switching to self."""
+        admin = self.get_user(ADMIN_USERNAME)
+        alpha = self.get_user("alpha")
+        self.login(ADMIN_USERNAME)
+        payload = self._sip_report_payload("sip209_api_shared")
+        payload.update({"run_as": admin.id, "run_as_type": "fixed_user"})
+        created = self.client.post("/api/v1/report/", json=payload)
+        assert created.status_code == 201, created.json
+        schedule = db.session.get(ReportSchedule, created.json["id"])
+        schedule.editors = _subjects_for_users([admin, alpha])
+        db.session.commit()
+        uri = f"/api/v1/report/{schedule.id}"
+        recipients = [
+            {
+                "type": ReportRecipientType.EMAIL,
+                "recipient_config_json": {"target": alpha.email},
+            }
+        ]
+
+        self.logout()
+        self.login("alpha")
+        metadata = self.client.put(uri, json={"name": "sip209_api_shared_renamed"})
+        assert metadata.status_code == 200, metadata.json
+        db.session.refresh(schedule)
+        changed_format = (
+            ReportDataFormat.PDF
+            if schedule.report_format != ReportDataFormat.PDF
+            else ReportDataFormat.PNG
+        )
+        format_only = self.client.put(uri, json={"report_format": changed_format})

Review Comment:
   This PUT asserts 200 for a format-only change by an editor whose report runs as Admin, but `report_format` is now in `CONTENT_FIELDS`, so `_validate_executors` returns 422 (CI shows `assert 422 == 200` here on every backend). Should this assert the rejection and unchanged format, then cover the format change after switching execution to the editor?



##########
superset/commands/report/execute.py:
##########
@@ -672,6 +722,12 @@ def _get_url(
         # _get_embedded_data, _get_notification_content) funnels through this
         # method, so this is the single choke point.
         if chart is None and dashboard is None:
+            if (
+                user_friendly
+                and self._report_schedule.type == ReportScheduleType.ALERT
+                and not self._attachments_enabled()
+            ):
+                return ""

Review Comment:
   An attachment-free alert with no chart/dashboard now returns an empty URL here, but `send_error` (and the retry/final-failure builders) still pass `include_cta=self._report_schedule.include_cta is not False` without the `bool(url)` guard used in `_get_notification_content`. When the alert query fails, the editor email renders an "Explore in Superset" link with `href=""`. Should those sibling paths drop the CTA when the URL is empty?



##########
tests/unit_tests/migrations/test_add_run_as_and_report_config.py:
##########
@@ -0,0 +1,181 @@
+# 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 migration ``e4a7c2b9d1f3_add_run_as_and_report_config`` (SIP-209).
+
+Runs ``upgrade()`` and ``downgrade()`` against an in-memory SQLite engine
+seeded with minimal ``ab_user`` and ``report_schedule`` tables and asserts the
+new nullable columns and the ``report_config`` table are created and removed
+without touching existing rows.
+"""
+
+from __future__ import annotations
+
+from importlib import import_module
+from pathlib import Path
+
+import pytest
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from alembic.script import ScriptDirectory
+from sqlalchemy import (
+    Column,
+    create_engine,
+    inspect,
+    Integer,
+    MetaData,
+    select,
+    String,
+    Table,
+)
+from sqlalchemy.engine import Engine
+
+migration = import_module(
+    "superset.migrations.versions."
+    "2026-10-05_12-00_e4a7c2b9d1f3_add_run_as_and_report_config"
+)
+
+
+@pytest.fixture
+def engine() -> Engine:
+    engine = create_engine("sqlite:///:memory:")
+    md = MetaData()
+    Table(
+        "ab_user",
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("username", String(64)),
+    )
+    report_schedule = Table(
+        migration.REPORT_SCHEDULE_TABLE,
+        md,
+        Column("id", Integer, primary_key=True),
+        Column("name", String(150), nullable=False),
+        Column("type", String(50), nullable=False),
+    )
+    md.create_all(engine)
+    with engine.begin() as conn:
+        conn.execute(
+            report_schedule.insert(),
+            [{"id": 1, "name": "daily", "type": "Report"}],
+        )
+    return engine
+
+
+def _columns(engine: Engine, table: str) -> set[str]:
+    return {col["name"] for col in inspect(engine).get_columns(table)}
+
+
+def _run(engine: Engine, fn) -> None:
+    with engine.begin() as conn:
+        ctx = MigrationContext.configure(conn)
+        with Operations.context(ctx):
+            fn()
+
+
+def test_upgrade_adds_columns_and_config_table(engine: Engine) -> None:
+    _run(engine, migration.upgrade)
+
+    columns = _columns(engine, migration.REPORT_SCHEDULE_TABLE)
+    assert {
+        "run_as_fk",
+        "run_alert_query_as_fk",
+        "run_as_type",
+        "run_alert_query_as_type",
+    } <= columns
+    assert inspect(engine).has_table(migration.REPORT_CONFIG_TABLE)
+    assert {"id", "key", "value", "created_on", "changed_on"} <= _columns(
+        engine, migration.REPORT_CONFIG_TABLE
+    )
+
+    # Existing schedules are untouched and keep NULL executors (legacy path).
+    with engine.begin() as conn:
+        table = Table(migration.REPORT_SCHEDULE_TABLE, MetaData(), autoload_with=conn)
+        rows = conn.execute(select(table)).fetchall()
+    assert len(rows) == 1
+    assert rows[0].run_as_fk is None
+    assert rows[0].run_alert_query_as_fk is None
+
+    # Idempotent: a second run is a no-op.
+    _run(engine, migration.upgrade)
+
+
+def test_downgrade_reverts(engine: Engine) -> None:
+    _run(engine, migration.upgrade)
+    _run(engine, migration.downgrade)
+
+    assert not inspect(engine).has_table(migration.REPORT_CONFIG_TABLE)
+    columns = _columns(engine, migration.REPORT_SCHEDULE_TABLE)
+    assert "run_as_fk" not in columns
+    assert "run_alert_query_as_fk" not in columns
+    with engine.begin() as conn:
+        table = Table(migration.REPORT_SCHEDULE_TABLE, MetaData(), autoload_with=conn)
+        assert len(conn.execute(select(table)).fetchall()) == 1
+
+
+def test_sip_migration_is_the_single_head() -> None:
+    directory = Path(__file__).resolve().parents[3] / "superset" / "migrations"
+    script = ScriptDirectory(str(directory))
+    assert script.get_heads() == [migration.revision]

Review Comment:
   `script.get_heads() == [migration.revision]` pins this revision as the repository head, so the next unrelated migration that lands on top of it fails this test even though the chain is correct. `test_single_migration_head.py` already asserts a single head; should this check that this revision is an ancestor of the head instead?



##########
superset-frontend/src/features/reports/ReportModal/index.tsx:
##########
@@ -182,13 +190,26 @@ function ReportModal({
   const isEditMode = report && Object.keys(report).length;
 
   useEffect(() => {
+    setExecuteAsSelf(false);
     if (isEditMode) {
       setCurrentReport(report);
     } else {
       setCurrentReport('reset');
     }
   }, [isEditMode, report]);
 
+  const formatChanged =
+    isChart &&
+    Boolean(isEditMode) &&
+    (currentReport.report_format || defaultNotificationFormat) !==
+      report.report_format;
+  const formatRequiresTakeover =
+    isFeatureEnabled(FeatureFlag.AlertReportDynamicExecutor) &&
+    formatChanged &&
+    !isUserAdmin(bootstrapUser) &&
+    (report.run_as_type !== 'fixed_user' ||

Review Comment:
   `formatRequiresTakeover` reads `report.run_as?.id` and `run_as_type` from the store, but after `ADD_REPORT`/`SUBSCRIBE_REPORT`/`EDIT_REPORT` the reducer stores the request payload echoed by the API (`run_as` as an integer, or absent on a plain edit or a server-defaulted create). A non-admin who saves their own subscription and changes the format in the same session then gets `formatRequiresTakeover === true` and must tick "execute using my permissions" for a schedule that already runs as them. Should the comparison handle the integer/absent shape, or the store be refetched after mutations?



##########
superset/commands/report/execute.py:
##########
@@ -2571,22 +2678,10 @@ def run(self) -> None:  # noqa: C901
                     deadline.remaining_seconds,
                 )
 
-            # Resolve the executor at the run() boundary, tolerating a missing
-            # user (find_user -> None) so the state machine still runs and its
-            # error envelope writes the ERROR execution-log row and sends the
-            # editor notification. The dedicated ReportScheduleExecutorNotFoundError
-            # guard lives at the content sites (_get_screenshots / _get_data /
-            # _get_embedded_data), which raise inside that envelope. Guarding here
-            # instead would surface the executor error above the state machine,
-            # suppressing both the log row and the editor notification. The
-            # alert-query path (AlertCommand) is intentionally left unchanged โ€” a
-            # missing executor there surfaces as a query error, not the dedicated
-            # executor error; tightening it is out of scope here.
-            _, username = get_executor(
-                executors=app.config["ALERT_REPORTS_EXECUTORS"],
-                model=self._model,
-            )
-            user = security_manager.find_user(username)
+            # Resolve content identity without rejecting an attachment-free alert.
+            # Content fetches and AlertCommand validate their respective identities
+            # inside the state machine, where failures are logged and terminalized.
+            user, username = get_executor_user(self._model)

Review Comment:
   `get_executor_user` now intentionally returns `None` for an attachment-free alert whose content user is inactive, but the dashboard-permalink pre-commit just below still runs under that identity. With a saved dashboard tab (`ALERT_REPORT_TABS`), `get_dashboard_urls()` creates a tab permalink through the dashboard access check, which fails for the anonymous user outside the state machine's error envelope, so the alert query never runs even though its own executor is valid. Should the permalink step be skipped (or moved inside the envelope) when no attachment or link is needed?



##########
superset/commands/report/update.py:
##########
@@ -42,17 +48,97 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(

Review Comment:
   `type` isn't in `CONTENT_FIELDS`, so an editor of a schedule that runs as another user can send `{"type": "Report"}` on an alert whose stored `report_format` is PNG and whose attachments are globally disabled. Nothing in the stored content changes, so the guard doesn't fire, but reports always generate the attachment, so the next run delivers the chart rendered as the other user to the existing recipients. Should an Alertโ†’Report switch be treated as a content change here?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213727854


##########
superset-frontend/src/features/reports/ReportModal/index.tsx:
##########
@@ -182,13 +190,26 @@ function ReportModal({
   const isEditMode = report && Object.keys(report).length;
 
   useEffect(() => {
+    setExecuteAsSelf(false);
     if (isEditMode) {
       setCurrentReport(report);
     } else {
       setCurrentReport('reset');
     }
   }, [isEditMode, report]);
 
+  const formatChanged =
+    isChart &&
+    Boolean(isEditMode) &&
+    (currentReport.report_format || defaultNotificationFormat) !==
+      report.report_format;
+  const formatRequiresTakeover =
+    isFeatureEnabled(FeatureFlag.AlertReportDynamicExecutor) &&
+    formatChanged &&
+    !isUserAdmin(bootstrapUser) &&
+    (report.run_as_type !== 'fixed_user' ||

Review Comment:
   Good catch! Working on it.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202272488


##########
superset/commands/report/alert.py:
##########
@@ -214,37 +216,41 @@ def _execute_query(self) -> pd.DataFrame:
         :raises AlertQueryError: SQL query is not valid
         :raises AlertQueryTimeout: The SQL query received a celery soft timeout
         """
-        sql_template = jinja_context.get_template_processor(
-            database=self._report_schedule.database
-        )
-
         try:
-            rendered_sql = sql_template.process_template(self._report_schedule.sql)
-            self._validate_rendered_sql(rendered_sql)
-            limited_rendered_sql = self._report_schedule.database.apply_limit_to_sql(
-                rendered_sql, ALERT_SQL_LIMIT
-            )
-
-            if app.config["MUTATE_ALERT_QUERY"]:
-                limited_rendered_sql = (
-                    self._report_schedule.database.mutate_sql_based_on_config(
-                        limited_rendered_sql
-                    )
+            user = get_dynamic_executor(self._report_schedule, alert_query=True)
+            if user is not None:
+                username = user.username
+            else:
+                executor, username = get_executor(  # pylint: disable=unused-variable
+                    executors=app.config["ALERT_REPORTS_EXECUTORS"],
+                    model=self._report_schedule,
                 )
-
-            executor, username = get_executor(  # pylint: disable=unused-variable
-                executors=app.config["ALERT_REPORTS_EXECUTORS"],
-                model=self._report_schedule,
-            )
-            user = security_manager.find_user(username)
+                user = security_manager.find_user(username)
             # A deleted/disabled executor user makes find_user return None. Raise
             # the dedicated error so the handler below re-surfaces it instead of
             # masking it as an opaque AlertQueryError (or letting the missing user
             # surface as a NoneType error from the downstream auth flow).
-            if user is None:
+            if user is None or not user.is_active:
                 raise ReportScheduleExecutorNotFoundError(username)
 
             with override_user(user):

Review Comment:
   `override_user` doesn't restore `g.user` when the body raises, so a failing alert query leaves the separate query executor as the current user for the rest of the run. With `ALERT_REPORTS_EXECUTORS=[MODIFIER]`, content running as Alice and the query as Bob, a query error is persisted with `changed_by_fk` set to Bob, and the next execution resolves its content executor to Bob. Should the override be wrapped in `try/finally` (or the error-state write done after restoring the user) so a query-only identity can't become the content executor?



##########
superset/commands/report/update.py:
##########
@@ -65,6 +114,153 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,
+            "recipients": _normalize_recipients,
+        }
+        changed: set[str] = set()
+        for field in CONTENT_FIELDS & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _validate_executors(
+        self,
+        report_type: str,
+        changed_content_fields: set[str],
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Resolve the "Run As" fields (SIP-209) on update.
+
+        Fields absent from the payload keep their stored value. Admins may set
+        any active user or explicit executor type. Clearing content restores the
+        legacy application-configured executor;
+        clearing the query executor inherits the content identity.
+        Non-admins may only point the fields at themselves and, when the schedule
+        executes as another user,
+        may not change its content or recipients: doing so would let an editor
+        read data with someone else's credentials.
+        """
+        assert self._model is not None
+        has_run_as = bool({"run_as", "run_as_type"} & self._properties.keys())
+        has_query_as = bool(
+            {"run_alert_query_as", "run_alert_query_as_type"} & self._properties.keys()
+        )
+        run_as_id = self._properties.pop("run_as", None)
+        query_as_id = self._properties.pop("run_alert_query_as", None)
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):

Review Comment:
   With the flag off this returns early and `changed_content_fields` is also skipped, but the stored `run_as`/`run_as_type` are left in place. A non-admin editor can then change the dashboard, recipients or format of a schedule that was set to run as an admin while the flag was on. When the flag is turned back on, `get_dynamic_executor` resolves to that stored admin again and the editor's content is rendered with the admin's RLS and OAuth credentials. Should the other-identity content check also apply to a stored executor while the flag is off, or should those stored values be cleared when a non-admin edits content?



##########
superset/commands/report/base.py:
##########
@@ -345,45 +393,118 @@ def validate_report_frequency(
         report_type: str,
     ) -> None:
         """
-        Validates if the report scheduled frequency doesn't exceed a limit
-        configured in `config.py`.
+        Validates if the report scheduled frequency doesn't exceed the minimum
+        interval in effect.
 
         :param cron_schedule: The cron schedule configured.
         :param report_type: The report type (Alert/Report).
         """
         config_key = (
-            "ALERT_MINIMUM_INTERVAL"
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL
             if report_type == ReportScheduleType.ALERT
-            else "REPORT_MINIMUM_INTERVAL"
+            else ReportConfigKey.REPORT_MINIMUM_INTERVAL
         )
-        minimum_interval = app.config.get(config_key, 0)
-        if callable(minimum_interval):
-            minimum_interval = minimum_interval()
+        minimum_interval = ReportConfigDAO.get_effective_value(config_key)
 
+        if minimum_interval is None:
+            return
         if not isinstance(minimum_interval, int):
             logger.error(
                 "Invalid value for %s: %s", config_key, minimum_interval, exc_info=True
             )
             return
 
-        # Since configuration is in minutes, we only need to validate
-        # in case `minimum_interval` is <= 120 (2min)
-        if minimum_interval < 120:
-            return
-
-        iterations = 60 if minimum_interval <= 3660 else 24
         try:
-            schedule = croniter(cron_schedule)
-            current_exec = next(schedule)
-
-            for _i in range(iterations):
-                next_exec = next(schedule)
-                diff, current_exec = next_exec - current_exec, next_exec
-                if int(diff) < minimum_interval:
-                    raise ReportScheduleFrequencyNotAllowed(
-                        report_type=report_type, minimum_interval=minimum_interval
-                    )
+            if not cron_meets_minimum_interval(cron_schedule, minimum_interval):
+                raise ReportScheduleFrequencyNotAllowed(
+                    report_type=report_type, minimum_interval=minimum_interval
+                )
         except CroniterBadDateError as ex:
             raise ReportScheduleCrontabNotValidError(
                 cron_schedule=cron_schedule
             ) from ex
+
+    def validate_report_format(
+        self,
+        report_type: str,
+        report_format: str | None,
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Reports always deliver content: the "no attachment" format is only
+        allowed on alerts.
+        """
+        if (
+            report_type == ReportScheduleType.REPORT
+            and report_format == ReportDataFormat.NONE
+        ):
+            exceptions.append(ReportScheduleFormatRequiredError())
+
+    def validate_recipients_policy(self, exceptions: list[ValidationError]) -> None:
+        """
+        Validate the e-mail recipients in the payload against the global
+        recipient policy (allowed domains and/or existing users only).
+        """
+        recipients = self._properties.get("recipients")
+        if not recipients:
+            return
+        disallowed = ReportConfigDAO.find_disallowed_addresses(
+            get_email_addresses(recipients)
+        )
+        if disallowed:
+            exceptions.append(ReportScheduleRecipientNotAllowedError(disallowed))
+
+    def validate_run_as(
+        self,
+        field_name: str,
+        user_id: int | None,
+        exceptions: list[ValidationError],
+        *,
+        default_to_current_user: bool,
+    ) -> User | None:
+        """Validate a specific user or an admin-selected application default.
+
+        A blank query executor inherits the content executor. A blank content
+        executor selected by an admin uses the legacy application configuration.
+        """
+        is_admin = security_manager.is_admin()
+        current_user = get_user()
+        type_field = f"{field_name}_type"
+        executor_type = self._properties.pop(type_field, None)
+        if executor_type is not None and executor_type != ExecutorType.FIXED_USER:
+            if not is_admin:
+                exceptions.append(ReportScheduleRunAsForbiddenError(field_name))
+                return None
+            exceptions.append(
+                ValidationError(
+                    _("Choose Application default or a specific user"),
+                    field_name=field_name,
+                )
+            )
+            return None
+
+        if user_id is None and executor_type != ExecutorType.FIXED_USER:
+            if field_name == "run_alert_query_as":

Review Comment:
   Clearing the query executor is allowed for a non-admin without any identity check. On an alert whose `run_as` is another user and whose `run_alert_query_as` is the editor, `PUT {"run_alert_query_as": null}` clears both query fields, and the query then inherits the other user's identity. The guard in `_validate_executors` only fires when a content field also changes, and the alert's SQL is not one of them, so the unchanged query now runs with that user's database access and the editor can read the result from the alert's last value or logs. Should clearing `run_alert_query_as` be treated like a content change (or rejected for a non-admin) whenever the inherited `run_as` isn't the requester?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4189048675


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -1782,10 +1981,30 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
     if (!currentAlert?.editors?.length) {
       errors.push(TRANSLATIONS.EDITORS_ERROR_TEXT);
     }
+    const needsContentExecutor =
+      isReport ||
+      (attachmentsEnabledForAlerts && reportFormat !== 'NONE') ||
+      !currentAlert?.run_alert_query_as_type;
+    if (
+      dynamicExecutorEnabled &&
+      isAdmin &&
+      ((needsContentExecutor &&
+        currentAlert?.run_as_type === 'fixed_user' &&
+        !currentAlert?.run_as?.value) ||

Review Comment:
   **Suggestion:** `needsContentExecutor` can be false while `run_as_type` is `fixed_user` with no user; validation passes, but the API rejects the save.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Rarely` ยท ๐Ÿท๏ธ `Incorrect condition logic`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6decada8a26a48b59516e882cb4f555f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=6decada8a26a48b59516e882cb4f555f&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/src/features/alerts/AlertReportModal.tsx
   **Line:** 1991:1993
   **Comment:**
   	*Incorrect Condition Logic: `needsContentExecutor` can be false while `run_as_type` is `fixed_user` with no user; validation passes, but the API rejects the save.
   
   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%2F44992&comment_hash=6e936c43a583f334599b265fe7ffd32cba8bf5b955a6b604b168d78071c2450d&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=6e936c43a583f334599b265fe7ffd32cba8bf5b955a6b604b168d78071c2450d&reaction=dislike'>๐Ÿ‘Ž</a>



##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -418,6 +418,117 @@ ALERT_REPORTS_EXECUTORS = [FixedExecutor("admin")]
 
 Please refer to `ExecutorType` in the codebase for other executor types.
 
+#### Per-schedule "Run As" executor
+
+`ALERT_REPORTS_EXECUTORS` is a global, server-side setting that is invisible to the people
+configuring alerts and reports, which makes permission problems hard to diagnose and is
+especially painful for databases authenticated with OAuth2, where the impersonated account
+must hold a valid token. [SIP-209](https://github.com/apache/superset/issues/39642)
+introduces an explicit, per-schedule alternative behind the `ALERT_REPORT_DYNAMIC_EXECUTOR`
+[feature flag](/admin-docs/configuration/configuring-superset#feature-flags):
+
+```python
+FEATURE_FLAGS = {
+    "ALERT_REPORTS": True,
+    "ALERT_REPORT_DYNAMIC_EXECUTOR": True,
+}
+```
+
+When the flag is enabled:
+
+- Every alert/report gets a **Run as** field recording which user's RBAC permissions and
+  database credentials are used to render the content. Alerts get an additional
+  **Run alert query as** field for the alert condition SQL, so the audience of an alert
+  does not need direct database access.
+- Admins can select **Application default** or **Specific user**:
+  * **Application default:** resolves through `ALERT_REPORTS_EXECUTORS` value.
+  * **Specific user:** User picker option.
+  Non-admins can only select themselves. They see no user search and the API rejects
+  selecting another user. Reports scheduled from a dashboard or chart always execute
+  as the subscribing user.
+- When a non-admin edits an alert/report that an admin configured to run as someone else,
+  they can change its metadata (name, schedule, active state, retries) but not its
+  content or recipients. To change those, they must first set **Run as** to their own
+  account using **Run as me** (or ask an admin). The form explains the restriction before
+  saving. For alerts, this action selects the current user for both content and condition
+  execution. It takes effect on Save and requires that user to have access to both.
+  Legacy schedules without an explicit content user also require this switch before
+  a non-admin changes content or recipients; metadata-only edits preserve their settings.
+- Untouched legacy schedules continue using `ALERT_REPORTS_EXECUTORS`. **Application
+  default** preserves this behavior in the Run as selector, including when an admin
+  clears an explicit executor. The API represents it with `run_as: null` and
+  `run_as_type: null`; omitting both fields on update preserves the stored executor.
+  New schedules default to the creator unless an admin selects Application default.
+  Clearing **Run alert query as** selects **Same as Run as**:
+  it follows later content-executor changes rather than copying the user at save time.
+- A selected user that is deleted remains recorded as a **Specific user** selection.
+  Resolving a deleted or inactive user fails rather than switching to a legacy executor.
+  Alert SQL templates, SQL mutation hooks, authorization and database access all use
+  the query executor's identity.
+
+`ALERT_REPORTS_EXECUTORS` is deprecated in favor of this field and will be removed once the
+feature graduates from the flag.
+
+### Alerts & Reports configuration
+
+Admins can manage the global Alerts & Reports settings at runtime from the **Configuration**
+button on the Alerts & Reports list page (also available through
+`GET`/`PUT /api/v1/report/configuration/`). Values are stored in the `report_config` table;
+a setting that was never saved falls back to the corresponding `superset_config.py` value or
+feature flag. The form saves only changed settings.
+Clearing an interval stores an explicit `null`, which means no minimum interval; it does
+not restore the application fallback. API `null` values likewise clear settings: attachment,
+date-format, and users-only switches become off, and domains become unrestricted. An explicit null row
+is retained. Configuration read or decoding failures are errors, never unrestricted defaults.
+
+| Setting | Fallback | Description |
+| --- | --- | --- |
+| Enable attachments for alerts | `ALERTS_ATTACH_REPORTS` feature flag | Whether alerts deliver their attachment. Applies to subsequent attempts; saving a change cancels pending attempts. |
+| Format dates in email subjects | `DATE_FORMAT_IN_EMAIL_SUBJECT` feature flag | Render date code placeholders in alert and report email subjects using the UTC date at delivery. |
+| Alert minimum interval | `ALERT_MINIMUM_INTERVAL` | Minimum interval between two executions of an alert. |
+| Report minimum interval | `REPORT_MINIMUM_INTERVAL` | Minimum interval between two executions of a report. |
+| Limit recipients to users | off | Only e-mail addresses of existing active users are accepted as recipients. |
+| Allowed e-mail domains | any | Allow-list of e-mail domains accepted as recipients. |
+
+Saving a stricter configuration is refused when existing alerts/reports (including disabled schedules) would violate it
+(a recipient outside the allowed domains, an address that is not a user, or a schedule that
+runs more often than the new minimum interval). The response lists the impacted schedules
+in pages of ten so they can be fixed first. The recipient policy is enforced when saving an alert/report
+and again at execution time, so a delivery to a recipient that is no longer allowed fails
+instead of being sent. These restrictions also apply to configured recipients of retry
+and final-failure notices. Owner/editor operational error notices are exempt; if recipient
+validation fails during a retry notice, only eligible operational notices are attempted.
+
+Domain matching is case-insensitive. An exact entry such as `example.com` does not
+include subdomains. Use wildcards like `*.example.com` / `example.* `to allow subdomains
+at any depth. Combining leading and trailing wildcards, or placing wildcards inside a label,

Review Comment:
   **Suggestion:** `example.*` matches only the root `example.<TLD>` domain, not subdomains, so recipients on subdomains will still be rejected.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Sometimes` ยท ๐Ÿท๏ธ `Comment mismatch`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5e0af4a7bcf3494cacd96f329469bba8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5e0af4a7bcf3494cacd96f329469bba8&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** docs/admin_docs/configuration/alerts-reports.mdx
   **Line:** 503:504
   **Comment:**
   	*Comment Mismatch: `example.*` matches only the root `example.<TLD>` domain, not subdomains, so recipients on subdomains will still be rejected.
   
   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%2F44992&comment_hash=f9b01b31e02f2ae6e62b7a2d4165ff374d8e061aa21cfe8afaae42428dbe04d5&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=f9b01b31e02f2ae6e62b7a2d4165ff374d8e061aa21cfe8afaae42428dbe04d5&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4215527223


##########
superset/daos/report.py:
##########
@@ -392,3 +404,187 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) with at least one e-mail recipient.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .join(
+                ReportRecipients,
+                ReportRecipients.report_schedule_id == ReportSchedule.id,
+            )
+            .filter(ReportRecipients.type == ReportRecipientType.EMAIL)
+            .options(selectinload(ReportSchedule.recipients))
+            .distinct()
+            .all()
+        )
+
+    @staticmethod
+    def find_by_type(report_type: ReportScheduleType) -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) of the given type.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.type == report_type)
+            .all()
+        )
+
+
+class ReportConfigDAO:
+    """
+    Access to the global Alerts & Reports configuration in ``key_value``.
+
+    One versioned document stores only settings explicitly saved by an admin.
+    Missing settings resolve to legacy application config or feature flag values.
+    """
+
+    VERSION: Literal[1] = 1
+
+    @staticmethod
+    def get_stored_values() -> dict[str, Any]:
+        """
+        Return explicitly saved settings from the versioned document.
+
+        A stored null is distinct from a missing setting key.
+        """
+        document: ReportConfigDocument | None = KeyValueDAO.get_value(
+            KeyValueResource.ALERT_REPORT_CONFIG,
+            FIXED_RESOURCE_KEYS[KeyValueResource.ALERT_REPORT_CONFIG],
+            JsonKeyValueCodec(),
+        )
+        if document is None:
+            return {}
+        return dict(document["settings"])
+
+    @staticmethod
+    def get_fallback_value(key: ReportConfigKey) -> Any:
+        """Return the legacy application config / feature flag value for ``key``."""
+        if key == ReportConfigKey.ALERTS_ATTACH_REPORTS:
+            return feature_flag_manager.is_feature_enabled("ALERTS_ATTACH_REPORTS")
+        if key == ReportConfigKey.DATE_FORMAT_IN_EMAIL_SUBJECT:
+            return feature_flag_manager.is_feature_enabled(
+                "DATE_FORMAT_IN_EMAIL_SUBJECT"
+            )
+        if key in (
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL,
+            ReportConfigKey.REPORT_MINIMUM_INTERVAL,
+        ):
+            value = current_app.config.get(key.upper(), 0)
+            return value() if callable(value) else value
+        # These are new configs, no legacy fallback
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return False
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return []
+        return None
+
+    @staticmethod
+    def get_effective_value(key: ReportConfigKey) -> Any:
+        """
+        Return the value in effect for ``key``: the stored value when present,
+        otherwise the legacy fallback.
+        """
+        if key in (stored := ReportConfigDAO.get_stored_values()):
+            return stored[key]
+        return ReportConfigDAO.get_fallback_value(key)
+
+    @staticmethod
+    def get_effective_config() -> dict[str, Any]:
+        """Return the value in effect for every ``ReportConfigKey``."""
+        stored = ReportConfigDAO.get_stored_values()
+        return {
+            key.value: (
+                stored[key]
+                if key in stored
+                else ReportConfigDAO.get_fallback_value(key)
+            )
+            for key in ReportConfigKey
+        }
+
+    @staticmethod
+    def upsert(values: dict[str, Any]) -> None:
+        """
+        Merge submitted settings into the shared document without committing.
+        Only absent keys inherit application configuration; null stays explicit.
+        """
+        stored = ReportConfigDAO.get_stored_values()

Review Comment:
   while this is technically true, it's also not something specific to this SIP. This would be true for many flows in Superset, so I'll ignore it for now. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #44992:
URL: https://github.com/apache/superset/pull/44992#issuecomment-6016936158

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/44992?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `64.64143%` with `355 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 66.05%. Comparing base ([`ce39d22`](https://app.codecov.io/gh/apache/superset/commit/ce39d221aacc6d6d1d9817d7fb9b42ac3fe5daae?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`a17d5da`](https://app.codecov.io/gh/apache/superset/commit/a17d5da3eaa555667dd8200a9ae45324aabc8d4d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 3 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/44992?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/commands/report/update.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Fcommands%2Freport%2Fupdate.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvcmVwb3J0L3VwZGF0ZS5weQ==) | 30.10% | [63 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...-frontend/src/features/alerts/AlertReportModal.tsx](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset-frontend%2Fsrc%2Ffeatures%2Falerts%2FAlertReportModal.tsx&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2ZlYXR1cmVzL2FsZXJ0cy9BbGVydFJlcG9ydE1vZGFsLnRzeA==) | 82.05% | [42 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/reports/utils.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Freports%2Futils.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvcmVwb3J0cy91dGlscy5weQ==) | 51.16% | [38 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/report/base.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Fcommands%2Freport%2Fbase.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvcmVwb3J0L2Jhc2UucHk=) | 40.29% | [35 Missing and 5 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/report/update\_config.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Fcommands%2Freport%2Fupdate_config.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvcmVwb3J0L3VwZGF0ZV9jb25maWcucHk=) | 33.89% | [39 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/daos/report.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Fdaos%2Freport.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGFvcy9yZXBvcnQucHk=) | 55.26% | [29 Missing and 5 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/commands/report/execute.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Fcommands%2Freport%2Fexecute.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY29tbWFuZHMvcmVwb3J0L2V4ZWN1dGUucHk=) | 48.93% | [20 Missing and 4 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/reports/api.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Freports%2Fapi.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvcmVwb3J0cy9hcGkucHk=) | 57.14% | [17 Missing and 1 partial :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [superset/reports/schemas.py](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset%2Freports%2Fschemas.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvcmVwb3J0cy9zY2hlbWFzLnB5) | 70.90% | [14 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [...d/src/features/alerts/ReportConfigurationModal.tsx](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&filepath=superset-frontend%2Fsrc%2Ffeatures%2Falerts%2FReportConfigurationModal.tsx&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2ZlYXR1cmVzL2FsZXJ0cy9SZXBvcnRDb25maWd1cmF0aW9uTW9kYWwudHN4) | 89.92% | [13 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | ... and [5 more](https://app.codecov.io/gh/apache/superset/pull/44992?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | |
   > :exclamation:  There is a different number of reports uploaded between BASE (ce39d22) and HEAD (a17d5da). Click for more details.
   > 
   > <details><summary>HEAD has 4 uploads less than BASE</summary>
   >
   >| Flag | BASE (ce39d22) | HEAD (a17d5da) |
   >|------|------|------|
   >|python|7|3|
   ></details>
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #44992       +/-   ##
   ===========================================
   - Coverage   82.36%   66.05%   -16.31%     
   ===========================================
     Files        2997     3002        +5     
     Lines      185523   186638     +1115     
     Branches    42938    43252      +314     
   ===========================================
   - Hits       152799   123292    -29507     
   - Misses      29970    60637    +30667     
   + Partials     2754     2709       -45     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage ฮ” | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `36.26% <33.33%> (-0.05%)` | :arrow_down: |
   | [mysql](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [postgres](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `38.11% <33.33%> (-0.06%)` | :arrow_down: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `55.04% <51.94%> (-31.26%)` | :arrow_down: |
   | [sqlite](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `54.91% <51.94%> (-0.10%)` | :arrow_down: |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/44992/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/44992?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #44992:
URL: https://github.com/apache/superset/pull/44992#issuecomment-6003227505

   ### <span aria-hidden="true">โœ…</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">๐Ÿ”จ</span> Latest commit | f7cce4a026aa9303767c5a3e7be84575f73e7e9b |
   |<span aria-hidden="true">๐Ÿ”</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6ac415128449550007b6408f |
   |<span aria-hidden="true">๐Ÿ˜Ž</span> Deploy Preview | [https://deploy-preview-44992--superset-docs-preview.netlify.app](https://deploy-preview-44992--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">๐Ÿ“ฑ</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQ0OTkyLS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.DnYjohFk8Fb7ni3LGYX3DLyM__hcQv1_MPABtOdfRfc)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">๐Ÿค–</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#q1YqKMrPLShRslJS0lFKKkrMS84AstNSE0v0izMLdI0MLIHiKakFOfmVnilAGbPEZBNDU0MjCxMTS1NTAwMD8yQzEwOLNKVaAA) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-44992--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4195402163


##########
superset/reports/api.py:
##########
@@ -93,16 +99,24 @@ def ensure_alert_reports_enabled(self) -> Optional[Response]:
         "slack_channels",  # not using RouteMethod since locally defined
         "subscribe",
         "execute",  # not using RouteMethod since locally defined
+        "get_configuration",
+        "put_configuration",
     }
     class_permission_name = "ReportSchedule"
-    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
+    method_permission_name = {
+        **MODEL_API_RW_METHOD_PERMISSION_MAP,
+        "get_configuration": "read",
+        "put_configuration": "write",
+    }
     resource_name = "report"
     allow_browser_login = True
 
     extra_fields_rel_fields = {
         **BaseSupersetModelRestApi.extra_fields_rel_fields,
         "created_by": ["email", "active"],
         "editors": ["type", "active", "secondary_label", "img"],
+        "run_as": ["email", "active"],
+        "run_alert_query_as": ["email", "active"],

Review Comment:
   Addressed in new commit. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202748466


##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -418,6 +418,111 @@ ALERT_REPORTS_EXECUTORS = [FixedExecutor("admin")]
 
 Please refer to `ExecutorType` in the codebase for other executor types.
 
+#### Per-schedule "Run As" executor
+
+`ALERT_REPORTS_EXECUTORS` is a global, server-side setting that is invisible to the people
+configuring alerts and reports, which makes permission problems hard to diagnose and is
+especially painful for databases authenticated with OAuth2, where the impersonated account
+must hold a valid token. [SIP-209](https://github.com/apache/superset/issues/39642)
+introduces an explicit, per-schedule alternative behind the `ALERT_REPORT_DYNAMIC_EXECUTOR`
+[feature flag](/admin-docs/configuration/configuring-superset#feature-flags):
+
+```python
+FEATURE_FLAGS = {
+    "ALERT_REPORTS": True,
+    "ALERT_REPORT_DYNAMIC_EXECUTOR": True,
+}
+```
+
+When the flag is enabled:
+
+- Every alert/report gets a **Run as** field recording which user's RBAC permissions and
+  database credentials are used to render the content. Alerts get an additional
+  **Run alert query as** field for the alert condition SQL, so the audience of an alert
+  does not need direct database access.
+- Admins can select **Application default** or **Specific user**:
+  * **Application default:** resolves through `ALERT_REPORTS_EXECUTORS` value.
+  * **Specific user:** User picker option.
+  Non-admins can only select themselves. They see no user search and the API rejects
+  selecting another user. Reports scheduled from a dashboard or chart always execute
+  as the subscribing user.

Review Comment:
   "Reports scheduled from a dashboard or chart always execute as the subscribing user" isn't true for existing subscriptions: the migration leaves the executor fields null and execution falls back to `ALERT_REPORTS_EXECUTORS`. An operator on `FixedExecutor("admin")` who enables the flag would assume subscriptions now use the subscriber's permissions and OAuth tokens, but untouched ones still run as admin. Could this say it applies to newly created subscriptions and note how to move existing ones?



##########
superset/commands/report/update.py:
##########
@@ -65,6 +131,194 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _compare_fields(
+        self,
+        keys: frozenset[str],
+        current: dict[str, Any],
+        normalizers: dict[str, Callable[[Any], Any]],
+    ) -> set[str]:
+        """
+        Return submitted fields whose normalized values differ from the stored values
+        """
+        changed: set[str] = set()
+        for field in keys & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,
+            "recipients": _normalize_recipients,
+        }
+        return self._compare_fields(CONTENT_FIELDS, current, normalizers)
+
+    def _changed_condition_fields(self) -> set[str]:
+        """Return alert-condition fields that differ from the stored values."""
+        assert self._model is not None
+        current = {
+            "database": self._model.database_id,
+            "sql": self._model.sql,
+            "validator_type": self._model.validator_type,
+            "validator_config_json": _normalize_json(self._model.validator_config_json),
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "validator_config_json": _normalize_json,
+        }
+        return self._compare_fields(ALERT_CONDITION_FIELDS, current, normalizers)
+
+    def _validate_executors(
+        self,
+        report_type: str,
+        changed_content_fields: set[str],
+        changed_condition_fields: set[str],
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Resolve the "Run As" fields (SIP-209) on update.
+
+        Fields absent from the payload keep their stored value. Admins may set
+        any active user or explicit executor type. Clearing content restores the
+        legacy application-configured executor;
+        clearing the query executor inherits the content identity.
+        Non-admins may only point the fields at themselves and, when the schedule
+        executes as another user,
+        may not change its content or recipients: doing so would let an editor
+        read data with someone else's credentials.
+        """
+        assert self._model is not None
+        has_run_as = bool({"run_as", "run_as_type"} & self._properties.keys())
+        has_query_as = bool(
+            {"run_alert_query_as", "run_alert_query_as_type"} & self._properties.keys()
+        )
+        run_as_id = self._properties.pop("run_as", None)
+        query_as_id = self._properties.pop("run_alert_query_as", None)
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):
+            self._properties.pop("run_as_type", None)
+            self._properties.pop("run_alert_query_as_type", None)
+            return
+
+        run_as = (
+            self.validate_run_as(
+                "run_as", run_as_id, exceptions, default_to_current_user=False
+            )
+            if has_run_as
+            else self._model.run_as
+        )
+
+        query_as = None
+        if report_type == ReportScheduleType.REPORT:
+            if has_query_as and (
+                query_as_id is not None
+                or self._properties.get("run_alert_query_as_type") is not None
+            ):
+                exceptions.append(ReportScheduleRunAlertQueryAsNotAllowedError())
+            else:
+                self._properties["run_alert_query_as"] = None
+                self._properties["run_alert_query_as_type"] = None
+        elif has_query_as:
+            query_as = self.validate_run_as(
+                "run_alert_query_as",
+                query_as_id,
+                exceptions,
+                default_to_current_user=False,
+            )
+        else:
+            query_as = self._model.run_alert_query_as
+
+        if security_manager.is_admin():
+            return
+        current_user_id = get_user_id()
+        executes_as_other_user = any(
+            user is not None and user.id != current_user_id
+            for user in (run_as, query_as)
+        )
+        typed_executor = any(
+            self._properties.get(field, getattr(self._model, field))
+            not in (None, ExecutorType.FIXED_USER)
+            for field in ("run_as_type", "run_alert_query_as_type")
+        )
+        content_type = self._properties.get("run_as_type", self._model.run_as_type)
+        unresolved_executor = (
+            content_type is None
+            or (content_type == ExecutorType.FIXED_USER and run_as is None)
+            or (
+                report_type == ReportScheduleType.ALERT
+                and query_as is None
+                and self._properties.get(
+                    "run_alert_query_as_type", self._model.run_alert_query_as_type
+                )
+                == ExecutorType.FIXED_USER
+            )
+        )
+        if (
+            executes_as_other_user or typed_executor or unresolved_executor
+        ) and changed_content_fields:
+            exceptions.append(ReportScheduleRunAsContentForbiddenError())
+

Review Comment:
   With the flag on, a migrated chart/dashboard subscription has `run_as_type = None`, so `unresolved_executor` is true and any content change by a non-admin is rejected here. The chart's "Edit email report" modal (`features/reports/ReportModal`) is not touched by this PR and sends no `run_as` or takeover action, so its owner changing the format PNG to CSV gets a 422 with no way to resolve it from that UI. Is the subscription editor meant to stay unusable for legacy subscriptions, or should it send `run_as` / should the server default a null type for the subscription's own creator?



##########
superset/reports/utils.py:
##########
@@ -0,0 +1,190 @@
+# 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.
+"""
+Helpers shared by the Alerts & Reports commands, DAO and execution engine.
+
+Recipient and interval helpers are shared by save-time and execution-time
+validation.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from typing import Any, TYPE_CHECKING
+
+from croniter import croniter
+
+from superset import is_feature_enabled
+from superset.commands.report.exceptions import ReportScheduleExecutorNotFoundError
+from superset.reports.models import ReportRecipientType
+from superset.tasks.types import ExecutorType
+from superset.utils import json
+
+if TYPE_CHECKING:
+    from flask_appbuilder.security.sqla.models import User
+
+    from superset.reports.models import ReportSchedule
+
+# Recipient fields inside ``recipient_config_json`` holding e-mail addresses.
+EMAIL_RECIPIENT_FIELDS = ("target", "ccTarget", "bccTarget")
+_EMAIL_SEPARATOR_RE = re.compile(r"[,;]")
+
+# Simple hostname validation for the allowed e-mail domains configuration.
+EMAIL_DOMAIN_REGEX = re.compile(
+    r"^(?!\*\..*\.\*$)(?:\*\.)?(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+"
+    r"(?:[a-zA-Z]{2,63}|\*)$"
+)
+
+
+def get_dynamic_executor(
+    report_schedule: ReportSchedule,
+    *,
+    alert_query: bool = False,
+) -> User | None:
+    """
+    Return the user explicitly configured to execute ``report_schedule``.
+
+    When ``alert_query`` is set, a typed query executor is preferred; an unset
+    query type inherits the content selection. An unset content type returns
+    ``None`` so callers use ``ALERT_REPORTS_EXECUTORS``. The type marker is
+    authoritative even if a stale user relationship is present.
+
+    The returned user may be inactive; callers decide how to surface that.
+    """
+    if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):
+        return None
+    field = "run_as"
+    if alert_query and report_schedule.run_alert_query_as_type is not None:
+        field = "run_alert_query_as"
+    executor_type = getattr(report_schedule, f"{field}_type")
+    if executor_type is None:
+        return None
+    if executor_type != ExecutorType.FIXED_USER:
+        raise ReportScheduleExecutorNotFoundError(str(executor_type))
+    user = getattr(report_schedule, field)
+    if user is None:
+        raise ReportScheduleExecutorNotFoundError("deleted user")
+    return user
+
+
+def split_email_addresses(value: str | None) -> list[str]:

Review Comment:
   `split_email_addresses` only splits on `,` and `;`, but delivery uses `recipients_string_to_list`, which also splits on whitespace. A stored recipient like `external@outside.org internal@example.com` is read here as one address with domain `example.com`, so it passes an `example.com` allowed-domain policy (both in the save-time conflict scan and at send time) while the email goes to both. Can this use the same separator set as delivery (`,`, `;`, whitespace)?



##########
superset/commands/report/update.py:
##########
@@ -65,6 +131,194 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _compare_fields(
+        self,
+        keys: frozenset[str],
+        current: dict[str, Any],
+        normalizers: dict[str, Callable[[Any], Any]],
+    ) -> set[str]:
+        """
+        Return submitted fields whose normalized values differ from the stored values
+        """
+        changed: set[str] = set()
+        for field in keys & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,

Review Comment:
   A non-admin editor who only renames or reschedules a report that runs as someone else can still get a 422 and be forced to take over execution. The modal's save always writes `extra.dashboard.nativeFilters = []` (AlertReportModal.tsx:1033), so a stored `extra` like `{"dashboard":{"anchor":""}}` (e.g. created through the API) no longer matches after `_normalize_json`, and `extra` counts as a content change. The same happens for a non-email recipient such as `{"target":"C12345678"}`: the modal adds empty `ccTarget`/`bccTarget`, and the normalization at line 117 only strips those for Email. Should absent/empty filter lists and empty cc/bcc be normalized the same way for every recipient type?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213564858


##########
superset/commands/security/reset.py:
##########
@@ -62,7 +63,10 @@ def run(self) -> None:
             db.session.delete(database)
         db.session.query(Dashboard).delete()
         db.session.query(Slice).delete()
-        db.session.query(KeyValueEntry).delete()
+        config_uuid = FIXED_RESOURCE_KEYS[KeyValueResource.ALERT_REPORT_CONFIG]
+        db.session.query(KeyValueEntry).filter(
+            KeyValueEntry.uuid.is_(None) | (KeyValueEntry.uuid != config_uuid)
+        ).delete()

Review Comment:
   The `ENABLE_FACTORY_RESET_COMMAND` clears the `key_value` table. Updated the logic to preserve these configs (as the command typically wouldn't impact them). 
   
   I included `KeyValueEntry.uuid.is_(None)` just because technically `UUID` is `nullable=False`, so in the event there are entries without a UUID value, it would be deleted before, so deleting it here for consistency.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213973855


##########
superset/commands/report/execute.py:
##########
@@ -2571,22 +2678,10 @@ def run(self) -> None:  # noqa: C901
                     deadline.remaining_seconds,
                 )
 
-            # Resolve the executor at the run() boundary, tolerating a missing
-            # user (find_user -> None) so the state machine still runs and its
-            # error envelope writes the ERROR execution-log row and sends the
-            # editor notification. The dedicated ReportScheduleExecutorNotFoundError
-            # guard lives at the content sites (_get_screenshots / _get_data /
-            # _get_embedded_data), which raise inside that envelope. Guarding here
-            # instead would surface the executor error above the state machine,
-            # suppressing both the log row and the editor notification. The
-            # alert-query path (AlertCommand) is intentionally left unchanged โ€” a
-            # missing executor there surfaces as a query error, not the dedicated
-            # executor error; tightening it is out of scope here.
-            _, username = get_executor(
-                executors=app.config["ALERT_REPORTS_EXECUTORS"],
-                model=self._model,
-            )
-            user = security_manager.find_user(username)
+            # Resolve content identity without rejecting an attachment-free alert.
+            # Content fetches and AlertCommand validate their respective identities
+            # inside the state machine, where failures are logged and terminalized.
+            user, username = get_executor_user(self._model)

Review Comment:
   Will work on address this.



##########
superset/commands/report/execute.py:
##########
@@ -672,6 +722,12 @@ def _get_url(
         # _get_embedded_data, _get_notification_content) funnels through this
         # method, so this is the single choke point.
         if chart is None and dashboard is None:
+            if (
+                user_friendly
+                and self._report_schedule.type == ReportScheduleType.ALERT
+                and not self._attachments_enabled()
+            ):
+                return ""

Review Comment:
   This one as well



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213587598


##########
superset/migrations/versions/2026-10-05_12-00_e4a7c2b9d1f3_add_run_as_and_report_config.py:
##########
@@ -0,0 +1,135 @@
+# 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.
+"""Add Run As columns to report_schedule and create the report_config table
+
+Part of SIP-209 (Improved Alerts & Reports).
+
+``report_schedule.run_as_fk`` and ``report_schedule.run_alert_query_as_fk`` are
+nullable foreign keys to ``ab_user``. They are intentionally left NULL so the
+existing ``ALERT_REPORTS_EXECUTORS`` resolution keeps being used until a value
+is set.
+
+``report_config`` is a key-value table holding the global Alerts & Reports
+configuration (attachments for alerts, minimum intervals and recipient
+restrictions). It starts empty: every setting falls back to the corresponding
+application config or feature flag until an admin saves a value.
+
+Revision ID: e4a7c2b9d1f3
+Revises: 00fab727cd0a
+Create Date: 2026-10-05 12:00:00.000000
+
+"""
+
+from sqlalchemy import Column, DateTime, Integer, String, Text
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_fks_for_table,
+    create_table,
+    drop_columns,
+    drop_fks_for_table,
+    drop_table,
+    table_has_column,
+)
+
+# revision identifiers, used by Alembic.
+revision = "e4a7c2b9d1f3"
+down_revision = "00fab727cd0a"
+
+REPORT_SCHEDULE_TABLE = "report_schedule"
+REPORT_CONFIG_TABLE = "report_config"
+
+RUN_AS_FK_NAME = "fk_report_schedule_run_as_fk_ab_user"
+RUN_ALERT_QUERY_AS_FK_NAME = "fk_report_schedule_run_alert_query_as_fk_ab_user"
+
+
+def upgrade() -> None:
+    add_columns(
+        REPORT_SCHEDULE_TABLE,
+        Column("run_as_fk", Integer, nullable=True),
+        Column("run_alert_query_as_fk", Integer, nullable=True),
+        # When an account is deleted, ``run_as_fk`` gets cleared. Without
+        # ``run_alert_query_as_fk``, this would automatically change the
+        # schedule to fallback to ``ALERT_REPORTS_EXECUTORS``.
+        Column("run_as_type", String(50), nullable=True),
+        # Similarly, ``run_alert_query_as_type`` is used to replicate
+        # ``run_as_fk`` into ``run_alert_query_as_fk``.
+        Column("run_alert_query_as_type", String(50), nullable=True),
+    )
+    create_fks_for_table(
+        foreign_key_name=RUN_AS_FK_NAME,
+        table_name=REPORT_SCHEDULE_TABLE,
+        referenced_table="ab_user",
+        local_cols=["run_as_fk"],
+        remote_cols=["id"],
+        ondelete="SET NULL",
+    )
+    create_fks_for_table(
+        foreign_key_name=RUN_ALERT_QUERY_AS_FK_NAME,
+        table_name=REPORT_SCHEDULE_TABLE,
+        referenced_table="ab_user",
+        local_cols=["run_alert_query_as_fk"],
+        remote_cols=["id"],
+        ondelete="SET NULL",
+    )
+
+    create_table(
+        REPORT_CONFIG_TABLE,
+        Column("id", UUIDType(binary=True), primary_key=True),
+        Column("key", String(255), nullable=False, unique=True),
+        Column("value", Text, nullable=True),
+        Column("created_on", DateTime, nullable=True),
+        Column("changed_on", DateTime, nullable=True),
+        Column("created_by_fk", Integer, nullable=True),
+        Column("changed_by_fk", Integer, nullable=True),
+    )

Review Comment:
   Ok, done!



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "villebro (via GitHub)" <gi...@apache.org>.
villebro commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4214457408


##########
superset/migrations/versions/2026-10-05_12-00_e4a7c2b9d1f3_add_run_as_and_report_config.py:
##########
@@ -0,0 +1,177 @@
+# 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.
+"""Add Run As columns to report_schedule
+
+Part of SIP-209 (Improved Alerts & Reports).
+
+``report_schedule.run_as_fk`` and ``report_schedule.run_alert_query_as_fk`` are
+nullable foreign keys to ``ab_user``. They are intentionally left NULL so the
+existing ``ALERT_REPORTS_EXECUTORS`` resolution keeps being used until a value
+is set.
+
+The global Alerts & Reports configuration is stored in the existing key-value
+table. An empty document leaves every setting on its application config or
+feature-flag fallback until an admin saves a value.
+
+Revision ID: e4a7c2b9d1f3
+Revises: 00fab727cd0a
+Create Date: 2026-10-05 12:00:00.000000
+
+"""
+
+from uuid import UUID
+
+from alembic import op
+from sqlalchemy import (
+    Column,
+    column,
+    delete,
+    insert,
+    Integer,
+    LargeBinary,
+    select,
+    String,
+    table,
+    update,
+)
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_fks_for_table,
+    drop_columns,
+    drop_fks_for_table,
+    table_has_column,
+)
+
+# revision identifiers, used by Alembic.
+revision = "e4a7c2b9d1f3"
+down_revision = "00fab727cd0a"
+
+REPORT_SCHEDULE_TABLE = "report_schedule"
+
+RUN_AS_FK_NAME = "fk_report_schedule_run_as_fk_ab_user"
+RUN_ALERT_QUERY_AS_FK_NAME = "fk_report_schedule_run_alert_query_as_fk_ab_user"
+CONFIG_UUID = UUID("d4f7d2f0-bbd7-4d03-b1da-09c70f5705ec")
+CONFIG_RESOURCE = "alert_report_config"
+CONFIG_TABLE = table(
+    "key_value",
+    column("resource", String),
+    column("uuid", UUIDType(binary=True)),
+    column("value", LargeBinary),
+)

Review Comment:
   nit: as we're no longer using a dedicated table, the constant should probably reflect the correct table
   ```suggestion
   KEY_VALUE_TABLE = table(
       "key_value",
       column("resource", String),
       column("uuid", UUIDType(binary=True)),
       column("value", LargeBinary),
   )
   ```



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44992:
URL: https://github.com/apache/superset/pull/44992#issuecomment-6003343641

   <!-- Bito Reply -->
   The issue is valid. When `report_format` is set to `NONE`, the `requires_attachment()` method returns `False`, causing the validation logic to bypass dashboard resolution and access checks, which leads to the test failures. To resolve this, the test assertions should be updated to account for this early return path when `report_format` is `NONE`.
   
   I have checked the available context and there are no other comments on this PR to address. Would you like me to implement the fix for this test case?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202647618


##########
superset/commands/report/update_config.py:
##########
@@ -0,0 +1,145 @@
+# 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.
+import logging
+from functools import partial
+from typing import Any
+
+from croniter import CroniterBadDateError
+
+from superset.commands.base import BaseCommand
+from superset.commands.report.exceptions import (
+    ReportConfigConflictError,
+    ReportConfigUpdateFailedError,
+)
+from superset.daos.report import ReportConfigDAO, ReportScheduleDAO
+from superset.reports.models import (
+    ReportConfigKey,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.reports.utils import cron_meets_minimum_interval, get_email_addresses
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateReportConfigCommand(BaseCommand):
+    """
+    Update the global Alerts & Reports configuration.
+
+    Recipient restrictions and minimum intervals are validated against every
+    existing schedule: when any of them would become invalid under the new
+    configuration the command fails and lists the impacted schedules, so admins
+    can fix them before tightening the policy. Enabling/disabling attachments
+    for alerts applies immediately to all alerts and is never a conflict.
+    """
+
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+        self._impacted: list[dict[str, Any]] = []
+
+    @transaction(on_error=partial(on_error, reraise=ReportConfigUpdateFailedError))
+    def run(self) -> dict[str, Any]:
+        self.validate()
+        ReportConfigDAO.upsert(self._properties)

Review Comment:
   Great catch!! Implemented it. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202740133


##########
superset/commands/report/update.py:
##########
@@ -65,6 +114,153 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,
+            "recipients": _normalize_recipients,
+        }
+        changed: set[str] = set()
+        for field in CONTENT_FIELDS & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _validate_executors(
+        self,
+        report_type: str,
+        changed_content_fields: set[str],
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Resolve the "Run As" fields (SIP-209) on update.
+
+        Fields absent from the payload keep their stored value. Admins may set
+        any active user or explicit executor type. Clearing content restores the
+        legacy application-configured executor;
+        clearing the query executor inherits the content identity.
+        Non-admins may only point the fields at themselves and, when the schedule
+        executes as another user,
+        may not change its content or recipients: doing so would let an editor
+        read data with someone else's credentials.
+        """
+        assert self._model is not None
+        has_run_as = bool({"run_as", "run_as_type"} & self._properties.keys())
+        has_query_as = bool(
+            {"run_alert_query_as", "run_alert_query_as_type"} & self._properties.keys()
+        )
+        run_as_id = self._properties.pop("run_as", None)
+        query_as_id = self._properties.pop("run_alert_query_as", None)
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):

Review Comment:
   I think the latter, because once the FF is off, people won't really be able to update `run_as` fields:
   * The UI won't show them
   * They're discarded from API payloads
   
   So validating `changed_content_fields` would just block users from updating the schedule. 
   
   I'll go ahead and push a new commit that would always clear the fields on this scenario so that the schedule is configured for "application default". This would match the behavior (with FF off, all schedules run with "application default").



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202893096


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -2327,310 +2613,461 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
               ),
               children: (
                 <>
-                  <StyledInputContainer>
-                    <div className="control-label">
-                      {t('Content type')}
-                      <span className="required">*</span>
-                    </div>
-                    <Select
-                      ariaLabel={t('Select content type')}
-                      onChange={onContentTypeChange}
-                      value={contentType}
-                      options={CONTENT_TYPE_OPTIONS}
-                      placeholder={t('Select content type')}
+                  {dynamicExecutorEnabled && !isAdmin && (
+                    <Alert
+                      type={restrictedExecutor ? 'warning' : 'info'}
+                      showIcon
+                      message={
+                        restrictedExecutor
+                          ? t('Content and recipient edits are restricted')
+                          : t('Content and permissions')
+                      }
+                      description={
+                        restrictedExecutor ? (
+                          <>
+                            <p>
+                              {t(

Review Comment:
   Passing a ternary to `t()` means the extractor never sees either sentence, so neither lands in the translation catalog and both stay English for a non-English user. Could each branch call `t('โ€ฆ')` with its own string literal instead?



##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -2327,310 +2613,461 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
               ),
               children: (
                 <>
-                  <StyledInputContainer>
-                    <div className="control-label">
-                      {t('Content type')}
-                      <span className="required">*</span>
-                    </div>
-                    <Select
-                      ariaLabel={t('Select content type')}
-                      onChange={onContentTypeChange}
-                      value={contentType}
-                      options={CONTENT_TYPE_OPTIONS}
-                      placeholder={t('Select content type')}
+                  {dynamicExecutorEnabled && !isAdmin && (
+                    <Alert
+                      type={restrictedExecutor ? 'warning' : 'info'}
+                      showIcon
+                      message={
+                        restrictedExecutor
+                          ? t('Content and recipient edits are restricted')
+                          : t('Content and permissions')
+                      }
+                      description={
+                        restrictedExecutor ? (
+                          <>
+                            <p>
+                              {t(
+                                isReport
+                                  ? 'You can edit the name and schedule, but changing the delivered content or recipients requires updating it to execute with your permissions. Only admins can select other users.'

Review Comment:
   This tells an editor they can change just the name and schedule, but the modal still re-sends the stored `database`/`sql`, and `UpdateReportScheduleCommand.validate` re-runs `validate_alert_query` as the editor whenever either key is present. For an alert whose query runs as another user and an editor who can't read its dataset, a name-only save would fail with a data-access error even though the condition didn't change. Should unchanged `sql`/`database` be left out of the payload (or skipped server-side) so this holds?



##########
superset/daos/report.py:
##########
@@ -392,3 +398,180 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:

Review Comment:
   The configuration-conflict scan depends on this query, but the command tests patch `find_with_email_recipients` and the DAO tests only cover `ReportConfigDAO`, so nothing runs this join/filter. If it ever skipped an inactive or bcc-only schedule, saving a stricter domain list would succeed with no conflict reported. Could a DB-backed test seed an inactive schedule with an external bcc plus a Slack-only schedule and assert `UpdateReportConfigCommand` reports only the first?



##########
superset/commands/report/alert.py:
##########
@@ -214,37 +216,41 @@ def _execute_query(self) -> pd.DataFrame:
         :raises AlertQueryError: SQL query is not valid
         :raises AlertQueryTimeout: The SQL query received a celery soft timeout
         """
-        sql_template = jinja_context.get_template_processor(
-            database=self._report_schedule.database
-        )
-
         try:
-            rendered_sql = sql_template.process_template(self._report_schedule.sql)
-            self._validate_rendered_sql(rendered_sql)
-            limited_rendered_sql = self._report_schedule.database.apply_limit_to_sql(
-                rendered_sql, ALERT_SQL_LIMIT
-            )
-
-            if app.config["MUTATE_ALERT_QUERY"]:
-                limited_rendered_sql = (
-                    self._report_schedule.database.mutate_sql_based_on_config(
-                        limited_rendered_sql
-                    )
+            user = get_dynamic_executor(self._report_schedule, alert_query=True)
+            if user is not None:
+                username = user.username
+            else:
+                executor, username = get_executor(  # pylint: disable=unused-variable
+                    executors=app.config["ALERT_REPORTS_EXECUTORS"],
+                    model=self._report_schedule,
                 )
-
-            executor, username = get_executor(  # pylint: disable=unused-variable
-                executors=app.config["ALERT_REPORTS_EXECUTORS"],
-                model=self._report_schedule,
-            )
-            user = security_manager.find_user(username)
+                user = security_manager.find_user(username)
             # A deleted/disabled executor user makes find_user return None. Raise
             # the dedicated error so the handler below re-surfaces it instead of
             # masking it as an opaque AlertQueryError (or letting the missing user
             # surface as a NoneType error from the downstream auth flow).
-            if user is None:
+            if user is None or not user.is_active:
                 raise ReportScheduleExecutorNotFoundError(username)
 
             with override_user(user):
+                sql_template = jinja_context.get_template_processor(

Review Comment:
   Executor resolution now runs before templating, and `test_execute_query_wraps_template_rendering_error` still uses a bare `Mock` schedule. `get_executor` iterates `model.editors`, which raises `TypeError` on a Mock, and the broad `except Exception` turns that into `AlertQueryError`, so the test passes without `process_template` ever being called. Could the fixture provide a resolvable executor and assert the `TemplateError` is the cause?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4189036612


##########
superset-frontend/src/features/alerts/ReportConfigurationModal.tsx:
##########
@@ -0,0 +1,485 @@
+/**
+ * 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.
+ */
+import { FunctionComponent, useEffect, useMemo, useState } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, styled, useTheme } from '@apache-superset/core/theme';
+import { SupersetClient } from '@superset-ui/core';
+import { getClientErrorObject } from '@superset-ui/core/query/getClientErrorObject';
+import { Alert } from '@apache-superset/core/components';
+import {
+  Button,
+  InfoTooltip,
+  Flex,
+  Input,
+  InputNumber,
+  Pagination,
+  Switch,
+} from '@superset-ui/core/components';
+import { StandardModal, ModalFormField } from 'src/components/Modal';
+import {
+  REPORT_CONFIGURATION_ENDPOINT,
+  useReportConfiguration,
+} from './hooks/useReportConfiguration';
+import type { ImpactedSchedule, ReportConfiguration } from './types';
+
+const SECONDS_PER_MINUTE = 60;
+const EMAIL_DOMAIN_REGEX =
+  /^(?!\*\..*\.\*$)(?:\*\.)?(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+(?:[a-zA-Z]{2,63}|\*)$/;
+
+export interface ReportConfigurationModalProps {
+  show: boolean;
+  onHide: () => void;
+  onSaved?: (configuration: ReportConfiguration) => void;
+  addSuccessToast: (msg: string) => void;
+  addDangerToast: (msg: string) => void;
+}
+
+interface ConfigurationFormState {
+  alerts_attach_reports: boolean;
+  date_format_in_email_subject: boolean;
+  alert_minimum_interval_minutes: number | null;
+  report_minimum_interval_minutes: number | null;
+  limit_recipients_to_users: boolean;
+  allowed_email_domains: string;
+}
+
+const StyledImpactedList = styled.ul`
+  ${({ theme }) => css`
+    margin: ${theme.sizeUnit}px 0 0;
+    padding-left: ${theme.sizeUnit * 4}px;
+    max-height: 200px;
+    overflow-y: auto;
+  `}
+`;
+
+const StyledInstruction = styled.span`
+  ${({ theme }) => css`
+    color: ${theme.colorTextTertiary};
+    font-size: ${theme.fontSizeSM}px;
+  `}
+`;
+
+const StyledDomainField = styled.div`
+  ${({ theme }) => css`
+    .control-label [data-test='info-tooltip-icon'] {
+      margin-left: ${theme.sizeUnit}px;
+    }
+  `}
+`;
+
+const secondsToMinutes = (seconds: number | null | undefined) =>
+  seconds == null ? null : seconds / SECONDS_PER_MINUTE;
+
+const toFormState = (
+  configuration: ReportConfiguration | null,
+): ConfigurationFormState => ({
+  alerts_attach_reports: configuration
+    ? Boolean(configuration.alerts_attach_reports)
+    : true,
+  date_format_in_email_subject:
+    configuration?.date_format_in_email_subject ?? false,
+  alert_minimum_interval_minutes: secondsToMinutes(
+    configuration?.alert_minimum_interval,
+  ),
+  report_minimum_interval_minutes: secondsToMinutes(
+    configuration?.report_minimum_interval,
+  ),
+  limit_recipients_to_users: configuration?.limit_recipients_to_users ?? false,
+  allowed_email_domains: (configuration?.allowed_email_domains ?? []).join(
+    ', ',
+  ),
+});
+
+export const normalizeDomain = (domain: string) =>
+  domain.trim().toLowerCase().replace(/^@/, '');
+
+const parseDomains = (value: string) =>
+  Array.from(new Set(value.split(',').map(normalizeDomain).filter(Boolean)));
+
+const describeImpact = (schedule: ImpactedSchedule) =>
+  schedule.reason === 'recipient'
+    ? t('recipient %s is not allowed', schedule.detail)
+    : t(
+        'schedule "%s" runs more often than the minimum interval',
+        schedule.detail,
+      );
+
+const ReportConfigurationModal: FunctionComponent<
+  ReportConfigurationModalProps
+> = ({ show, onHide, onSaved, addSuccessToast, addDangerToast }) => {
+  const theme = useTheme();
+  const { configuration, loading, error, refresh } =
+    useReportConfiguration(show);
+  const [form, setForm] = useState<ConfigurationFormState>(toFormState(null));
+  const [saving, setSaving] = useState(false);
+  const [impacted, setImpacted] = useState<ImpactedSchedule[]>([]);
+  const [conflictPage, setConflictPage] = useState(1);
+  const [saveError, setSaveError] = useState<string | null>(null);
+
+  useEffect(() => {
+    if (configuration) {
+      setForm(toFormState(configuration));
+    }
+  }, [configuration]);
+
+  useEffect(() => {
+    if (show) {
+      setImpacted([]);
+      setSaveError(null);
+    }
+  }, [show]);
+
+  const domains = useMemo(
+    () => parseDomains(form.allowed_email_domains),
+    [form.allowed_email_domains],
+  );
+  const invalidDomains = domains.filter(
+    domain => !EMAIL_DOMAIN_REGEX.test(domain),
+  );
+
+  const updateForm = <K extends keyof ConfigurationFormState>(
+    key: K,
+    value: ConfigurationFormState[K],
+  ) => {
+    setForm(current => ({ ...current, [key]: value }));
+    setImpacted([]);
+    setSaveError(null);
+  };
+
+  const onSave = async () => {
+    setSaving(true);
+    setImpacted([]);
+    setSaveError(null);
+    const payload: ReportConfiguration = {
+      alerts_attach_reports: form.alerts_attach_reports,
+      date_format_in_email_subject: form.date_format_in_email_subject,
+      alert_minimum_interval:
+        form.alert_minimum_interval_minutes === null
+          ? null
+          : Math.round(
+              form.alert_minimum_interval_minutes * SECONDS_PER_MINUTE,
+            ),
+      report_minimum_interval:
+        form.report_minimum_interval_minutes === null
+          ? null
+          : Math.round(
+              form.report_minimum_interval_minutes * SECONDS_PER_MINUTE,
+            ),
+      limit_recipients_to_users: form.limit_recipients_to_users,
+      allowed_email_domains: domains,
+    };
+    const initial = toFormState(configuration);
+    const changed: Partial<ReportConfiguration> = {};
+    if (form.alerts_attach_reports !== initial.alerts_attach_reports) {
+      changed.alerts_attach_reports = payload.alerts_attach_reports;
+    }
+    if (
+      form.date_format_in_email_subject !== initial.date_format_in_email_subject
+    ) {
+      changed.date_format_in_email_subject =
+        payload.date_format_in_email_subject;
+    }
+    if (
+      form.alert_minimum_interval_minutes !==
+      initial.alert_minimum_interval_minutes
+    ) {
+      changed.alert_minimum_interval = payload.alert_minimum_interval;
+    }
+    if (
+      form.report_minimum_interval_minutes !==
+      initial.report_minimum_interval_minutes
+    ) {
+      changed.report_minimum_interval = payload.report_minimum_interval;
+    }
+    if (form.limit_recipients_to_users !== initial.limit_recipients_to_users) {
+      changed.limit_recipients_to_users = payload.limit_recipients_to_users;
+    }
+    if (
+      JSON.stringify(domains) !==
+      JSON.stringify(parseDomains(initial.allowed_email_domains))
+    ) {
+      changed.allowed_email_domains = payload.allowed_email_domains;
+    }
+    try {
+      const response = await SupersetClient.put({
+        endpoint: REPORT_CONFIGURATION_ENDPOINT,
+        jsonPayload: changed,
+      });
+      const saved = (response.json?.result ?? payload) as ReportConfiguration;
+      addSuccessToast(t('Alerts & Reports configuration updated'));
+      onSaved?.(saved);
+      onHide();
+    } catch (err) {
+      const clientError = await getClientErrorObject(err);
+      const impactedSchedules = (
+        clientError as { impacted_schedules?: ImpactedSchedule[] }
+      ).impacted_schedules;
+      if (impactedSchedules?.length) {
+        setImpacted(impactedSchedules);
+        setConflictPage(1);
+        setSaveError(
+          clientError.message ||
+            t(
+              'Some existing alerts/reports conflict with the new configuration. Please update them first.',
+            ),
+        );
+      } else {
+        const message =
+          clientError.message ||
+          clientError.error ||
+          t('An error occurred while saving the configuration');
+        setSaveError(message);
+        addDangerToast(message);
+      }
+    } finally {
+      setSaving(false);
+    }
+  };
+
+  return (
+    <StandardModal
+      show={show}
+      width={440}
+      onHide={onHide}
+      onSave={onSave}
+      saveText={t('Save')}
+      saveDisabled={loading || error || invalidDomains.length > 0}
+      saveLoading={saving}
+      contentLoading={loading && !configuration}
+      title={t('Alerts & Reports configuration')}
+      isEditMode
+      wrapProps={{ 'data-test': 'report-configuration-modal' }}
+    >
+      <Flex vertical gap={theme.marginLG} style={{ padding: theme.paddingLG }}>
+        {error && (
+          <Alert
+            type="error"
+            showIcon
+            closable={false}
+            message={t('Unable to load the Alerts & Reports configuration.')}
+            description={
+              <Button buttonStyle="link" onClick={() => refresh()}>
+                {t('Retry')}
+              </Button>
+            }
+          />
+        )}
+        <Flex vertical gap={theme.margin}>
+          <Flex align="center" gap={theme.marginXS}>
+            <Switch
+              checked={form.alerts_attach_reports}
+              onChange={(checked: boolean) =>
+                updateForm('alerts_attach_reports', checked)
+              }
+              aria-label={t('Enable attachments for alerts')}
+            />
+            <Flex align="center" gap={theme.sizeUnit}>
+              <span>{t('Enable attachments for alerts')}</span>
+              <InfoTooltip
+                tooltip={t(
+                  'When disabled, alerts only send the message and link, without screenshots or data files. Applies to all alerts.',
+                )}
+              />
+            </Flex>
+          </Flex>
+          <Flex align="center" gap={theme.marginXS}>
+            <Switch
+              checked={form.limit_recipients_to_users}
+              onChange={(checked: boolean) =>
+                updateForm('limit_recipients_to_users', checked)
+              }
+              aria-label={t('Limit recipients to users')}
+            />
+            <Flex align="center" gap={theme.sizeUnit}>
+              <span>{t('Limit recipients to users')}</span>
+              <InfoTooltip
+                tooltip={t(
+                  'Only e-mail addresses of existing active users can be used as recipients.',
+                )}
+              />
+            </Flex>
+          </Flex>
+          <Flex align="center" gap={theme.marginXS}>
+            <Switch
+              checked={form.date_format_in_email_subject}
+              onChange={(checked: boolean) =>
+                updateForm('date_format_in_email_subject', checked)

Review Comment:
   **Suggestion:** The form stays editable while the PUT is pending; a change made after `onSave` builds its payload is discarded when the successful response closes the modal.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Rarely` ยท ๐Ÿท๏ธ `Race condition`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=66b19720cd9b42beb63e6c0fccf0a70c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=66b19720cd9b42beb63e6c0fccf0a70c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset-frontend/src/features/alerts/ReportConfigurationModal.tsx
   **Line:** 320:322
   **Comment:**
   	*Race Condition: The form stays editable while the PUT is pending; a change made after `onSave` builds its payload is discarded when the successful response closes the modal.
   
   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%2F44992&comment_hash=10138ae01d55a1400b06448b4e0253de682a55512d2c63ea3988909d06ba2888&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=10138ae01d55a1400b06448b4e0253de682a55512d2c63ea3988909d06ba2888&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/commands/report/update_config.py:
##########
@@ -0,0 +1,148 @@
+# 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.
+import logging
+from functools import partial
+from typing import Any
+
+from croniter import CroniterBadDateError
+
+from superset.commands.base import BaseCommand
+from superset.commands.report.exceptions import (
+    ReportConfigConflictError,
+    ReportConfigUpdateFailedError,
+)
+from superset.daos.report import ReportConfigDAO, ReportScheduleDAO
+from superset.reports.models import (
+    ReportConfigKey,
+    ReportSchedule,
+    ReportScheduleType,
+)
+from superset.reports.utils import cron_meets_minimum_interval, get_email_addresses
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateReportConfigCommand(BaseCommand):
+    """
+    Update the global Alerts & Reports configuration.
+
+    Recipient restrictions and minimum intervals are validated against every
+    existing schedule: when any of them would become invalid under the new
+    configuration the command fails and lists the impacted schedules, so admins
+    can fix them before tightening the policy. Enabling/disabling attachments
+    for alerts applies immediately to all alerts and is never a conflict.
+    """
+
+    def __init__(self, data: dict[str, Any]):
+        self._properties = data.copy()
+        self._impacted: list[dict[str, Any]] = []
+
+    @transaction(on_error=partial(on_error, reraise=ReportConfigUpdateFailedError))
+    def run(self) -> dict[str, Any]:
+        self.validate()
+        effective = ReportConfigDAO.get_effective_config()
+        if any(effective.get(key) != value for key, value in self._properties.items()):
+            ReportScheduleDAO.invalidate_pending_executions()
+        ReportConfigDAO.upsert(self._properties)

Review Comment:
   **Suggestion:** A concurrent schedule save can validate against the old interval and commit after this scan, leaving the stricter configuration active while that schedule runs too often.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Rarely` ยท ๐Ÿท๏ธ `Race condition`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=fcc6c1af1e0d420ca5e59e49cd360e72&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=fcc6c1af1e0d420ca5e59e49cd360e72&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/report/update_config.py
   **Line:** 57:61
   **Comment:**
   	*Race Condition: A concurrent schedule save can validate against the old interval and commit after this scan, leaving the stricter configuration active while that schedule runs too often.
   
   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%2F44992&comment_hash=8747511bcc40e2b9102d209da0c500b02f9b83a750d5bc34932b935f272cfb6c&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=8747511bcc40e2b9102d209da0c500b02f9b83a750d5bc34932b935f272cfb6c&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/commands/report/base.py:
##########
@@ -134,13 +148,33 @@ def _check_object_access(
                 raise ReportScheduleForbiddenError() from ex
         self._properties[kind] = obj
 
+    def requires_attachment(self) -> bool:
+        """Whether the effective schedule configuration requires attachment content."""
+        model = getattr(self, "_model", None)
+        report_type = self._properties.get(
+            "type", getattr(model, "type", ReportScheduleType.REPORT)
+        )
+        report_format = self._properties.get(
+            "report_format", getattr(model, "report_format", ReportDataFormat.PNG)
+        )
+        return report_type == ReportScheduleType.REPORT or (
+            report_format != ReportDataFormat.NONE
+            and bool(
+                ReportConfigDAO.get_effective_value(
+                    ReportConfigKey.ALERTS_ATTACH_REPORTS
+                )
+            )
+        )
+
     def validate_chart_dashboard(
         self, exceptions: list[ValidationError], update: bool = False
     ) -> None:
         """Validate chart or dashboard relation"""
         chart_id = self._properties.get("chart")
         dashboard_id = self._properties.get("dashboard")
         creation_method = self._properties.get("creation_method")
+        if not (requires_attachment := self.requires_attachment()):
+            return

Review Comment:
   **Suggestion:** When an alert does not require an attachment, supplied chart or dashboard IDs skip existence and access checks and remain raw IDs, so ORM relationship persistence can fail.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Rarely` ยท ๐Ÿท๏ธ `Security`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b1f890a155804fddbd5810d57060ccce&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=b1f890a155804fddbd5810d57060ccce&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/commands/report/base.py
   **Line:** 176:177
   **Comment:**
   	*Security: When an alert does not require an attachment, supplied chart or dashboard IDs skip existence and access checks and remain raw IDs, so ORM relationship persistence can fail.
   
   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%2F44992&comment_hash=e6b548be6df8697811f153cadd825f97cf3912eea43eeb07b31060876ae9dea2&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=e6b548be6df8697811f153cadd825f97cf3912eea43eeb07b31060876ae9dea2&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #44992:
URL: https://github.com/apache/superset/pull/44992#issuecomment-6003193747

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4192048355


##########
superset-frontend/src/features/alerts/ReportConfigurationModal.tsx:
##########
@@ -0,0 +1,485 @@
+/**
+ * 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.
+ */
+import { FunctionComponent, useEffect, useMemo, useState } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, styled, useTheme } from '@apache-superset/core/theme';
+import { SupersetClient } from '@superset-ui/core';
+import { getClientErrorObject } from '@superset-ui/core/query/getClientErrorObject';
+import { Alert } from '@apache-superset/core/components';
+import {
+  Button,
+  InfoTooltip,
+  Flex,
+  Input,
+  InputNumber,
+  Pagination,
+  Switch,
+} from '@superset-ui/core/components';
+import { StandardModal, ModalFormField } from 'src/components/Modal';
+import {
+  REPORT_CONFIGURATION_ENDPOINT,
+  useReportConfiguration,
+} from './hooks/useReportConfiguration';
+import type { ImpactedSchedule, ReportConfiguration } from './types';
+
+const SECONDS_PER_MINUTE = 60;
+const EMAIL_DOMAIN_REGEX =
+  /^(?!\*\..*\.\*$)(?:\*\.)?(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+(?:[a-zA-Z]{2,63}|\*)$/;
+
+export interface ReportConfigurationModalProps {
+  show: boolean;
+  onHide: () => void;
+  onSaved?: (configuration: ReportConfiguration) => void;
+  addSuccessToast: (msg: string) => void;
+  addDangerToast: (msg: string) => void;
+}
+
+interface ConfigurationFormState {
+  alerts_attach_reports: boolean;
+  date_format_in_email_subject: boolean;
+  alert_minimum_interval_minutes: number | null;
+  report_minimum_interval_minutes: number | null;
+  limit_recipients_to_users: boolean;
+  allowed_email_domains: string;
+}
+
+const StyledImpactedList = styled.ul`
+  ${({ theme }) => css`
+    margin: ${theme.sizeUnit}px 0 0;
+    padding-left: ${theme.sizeUnit * 4}px;
+    max-height: 200px;
+    overflow-y: auto;
+  `}
+`;
+
+const StyledInstruction = styled.span`
+  ${({ theme }) => css`
+    color: ${theme.colorTextTertiary};
+    font-size: ${theme.fontSizeSM}px;
+  `}
+`;
+
+const StyledDomainField = styled.div`
+  ${({ theme }) => css`
+    .control-label [data-test='info-tooltip-icon'] {
+      margin-left: ${theme.sizeUnit}px;
+    }
+  `}
+`;
+
+const secondsToMinutes = (seconds: number | null | undefined) =>
+  seconds == null ? null : seconds / SECONDS_PER_MINUTE;
+
+const toFormState = (
+  configuration: ReportConfiguration | null,
+): ConfigurationFormState => ({
+  alerts_attach_reports: configuration
+    ? Boolean(configuration.alerts_attach_reports)
+    : true,
+  date_format_in_email_subject:
+    configuration?.date_format_in_email_subject ?? false,
+  alert_minimum_interval_minutes: secondsToMinutes(
+    configuration?.alert_minimum_interval,
+  ),
+  report_minimum_interval_minutes: secondsToMinutes(
+    configuration?.report_minimum_interval,
+  ),
+  limit_recipients_to_users: configuration?.limit_recipients_to_users ?? false,
+  allowed_email_domains: (configuration?.allowed_email_domains ?? []).join(
+    ', ',
+  ),
+});
+
+export const normalizeDomain = (domain: string) =>
+  domain.trim().toLowerCase().replace(/^@/, '');
+
+const parseDomains = (value: string) =>
+  Array.from(new Set(value.split(',').map(normalizeDomain).filter(Boolean)));
+
+const describeImpact = (schedule: ImpactedSchedule) =>
+  schedule.reason === 'recipient'
+    ? t('recipient %s is not allowed', schedule.detail)
+    : t(
+        'schedule "%s" runs more often than the minimum interval',
+        schedule.detail,
+      );
+
+const ReportConfigurationModal: FunctionComponent<
+  ReportConfigurationModalProps
+> = ({ show, onHide, onSaved, addSuccessToast, addDangerToast }) => {
+  const theme = useTheme();
+  const { configuration, loading, error, refresh } =
+    useReportConfiguration(show);
+  const [form, setForm] = useState<ConfigurationFormState>(toFormState(null));
+  const [saving, setSaving] = useState(false);
+  const [impacted, setImpacted] = useState<ImpactedSchedule[]>([]);
+  const [conflictPage, setConflictPage] = useState(1);
+  const [saveError, setSaveError] = useState<string | null>(null);
+
+  useEffect(() => {
+    if (configuration) {
+      setForm(toFormState(configuration));
+    }
+  }, [configuration]);
+
+  useEffect(() => {
+    if (show) {
+      setImpacted([]);
+      setSaveError(null);
+    }
+  }, [show]);
+
+  const domains = useMemo(
+    () => parseDomains(form.allowed_email_domains),
+    [form.allowed_email_domains],
+  );
+  const invalidDomains = domains.filter(
+    domain => !EMAIL_DOMAIN_REGEX.test(domain),
+  );
+
+  const updateForm = <K extends keyof ConfigurationFormState>(
+    key: K,
+    value: ConfigurationFormState[K],
+  ) => {
+    setForm(current => ({ ...current, [key]: value }));
+    setImpacted([]);
+    setSaveError(null);
+  };
+
+  const onSave = async () => {
+    setSaving(true);
+    setImpacted([]);
+    setSaveError(null);
+    const payload: ReportConfiguration = {
+      alerts_attach_reports: form.alerts_attach_reports,
+      date_format_in_email_subject: form.date_format_in_email_subject,
+      alert_minimum_interval:
+        form.alert_minimum_interval_minutes === null
+          ? null
+          : Math.round(
+              form.alert_minimum_interval_minutes * SECONDS_PER_MINUTE,
+            ),
+      report_minimum_interval:
+        form.report_minimum_interval_minutes === null
+          ? null
+          : Math.round(
+              form.report_minimum_interval_minutes * SECONDS_PER_MINUTE,
+            ),
+      limit_recipients_to_users: form.limit_recipients_to_users,
+      allowed_email_domains: domains,
+    };
+    const initial = toFormState(configuration);
+    const changed: Partial<ReportConfiguration> = {};
+    if (form.alerts_attach_reports !== initial.alerts_attach_reports) {
+      changed.alerts_attach_reports = payload.alerts_attach_reports;
+    }
+    if (
+      form.date_format_in_email_subject !== initial.date_format_in_email_subject
+    ) {
+      changed.date_format_in_email_subject =
+        payload.date_format_in_email_subject;
+    }
+    if (
+      form.alert_minimum_interval_minutes !==
+      initial.alert_minimum_interval_minutes
+    ) {
+      changed.alert_minimum_interval = payload.alert_minimum_interval;
+    }
+    if (
+      form.report_minimum_interval_minutes !==
+      initial.report_minimum_interval_minutes
+    ) {
+      changed.report_minimum_interval = payload.report_minimum_interval;
+    }
+    if (form.limit_recipients_to_users !== initial.limit_recipients_to_users) {
+      changed.limit_recipients_to_users = payload.limit_recipients_to_users;
+    }
+    if (
+      JSON.stringify(domains) !==
+      JSON.stringify(parseDomains(initial.allowed_email_domains))
+    ) {
+      changed.allowed_email_domains = payload.allowed_email_domains;
+    }
+    try {
+      const response = await SupersetClient.put({
+        endpoint: REPORT_CONFIGURATION_ENDPOINT,
+        jsonPayload: changed,
+      });
+      const saved = (response.json?.result ?? payload) as ReportConfiguration;
+      addSuccessToast(t('Alerts & Reports configuration updated'));
+      onSaved?.(saved);
+      onHide();
+    } catch (err) {
+      const clientError = await getClientErrorObject(err);
+      const impactedSchedules = (
+        clientError as { impacted_schedules?: ImpactedSchedule[] }
+      ).impacted_schedules;
+      if (impactedSchedules?.length) {
+        setImpacted(impactedSchedules);
+        setConflictPage(1);
+        setSaveError(
+          clientError.message ||
+            t(
+              'Some existing alerts/reports conflict with the new configuration. Please update them first.',
+            ),
+        );
+      } else {
+        const message =
+          clientError.message ||
+          clientError.error ||
+          t('An error occurred while saving the configuration');
+        setSaveError(message);
+        addDangerToast(message);
+      }
+    } finally {
+      setSaving(false);
+    }
+  };
+
+  return (
+    <StandardModal
+      show={show}
+      width={440}
+      onHide={onHide}
+      onSave={onSave}
+      saveText={t('Save')}
+      saveDisabled={loading || error || invalidDomains.length > 0}
+      saveLoading={saving}
+      contentLoading={loading && !configuration}
+      title={t('Alerts & Reports configuration')}
+      isEditMode
+      wrapProps={{ 'data-test': 'report-configuration-modal' }}
+    >
+      <Flex vertical gap={theme.marginLG} style={{ padding: theme.paddingLG }}>
+        {error && (
+          <Alert
+            type="error"
+            showIcon
+            closable={false}
+            message={t('Unable to load the Alerts & Reports configuration.')}
+            description={
+              <Button buttonStyle="link" onClick={() => refresh()}>
+                {t('Retry')}
+              </Button>
+            }
+          />
+        )}
+        <Flex vertical gap={theme.margin}>
+          <Flex align="center" gap={theme.marginXS}>
+            <Switch
+              checked={form.alerts_attach_reports}
+              onChange={(checked: boolean) =>
+                updateForm('alerts_attach_reports', checked)
+              }
+              aria-label={t('Enable attachments for alerts')}
+            />
+            <Flex align="center" gap={theme.sizeUnit}>
+              <span>{t('Enable attachments for alerts')}</span>
+              <InfoTooltip
+                tooltip={t(
+                  'When disabled, alerts only send the message and link, without screenshots or data files. Applies to all alerts.',
+                )}
+              />
+            </Flex>
+          </Flex>
+          <Flex align="center" gap={theme.marginXS}>
+            <Switch
+              checked={form.limit_recipients_to_users}
+              onChange={(checked: boolean) =>
+                updateForm('limit_recipients_to_users', checked)
+              }
+              aria-label={t('Limit recipients to users')}
+            />
+            <Flex align="center" gap={theme.sizeUnit}>
+              <span>{t('Limit recipients to users')}</span>
+              <InfoTooltip
+                tooltip={t(
+                  'Only e-mail addresses of existing active users can be used as recipients.',
+                )}
+              />
+            </Flex>
+          </Flex>
+          <Flex align="center" gap={theme.marginXS}>
+            <Switch
+              checked={form.date_format_in_email_subject}
+              onChange={(checked: boolean) =>
+                updateForm('date_format_in_email_subject', checked)

Review Comment:
   Good catch! Just fixed in a new commit.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #44992:
URL: https://github.com/apache/superset/pull/44992#issuecomment-6022196302

   ### โš ๏ธ Possible DB migration conflict
   
   @Vitor-Avila the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
   
   To check and, if needed, fix this:
   
   1. Rebase this branch onto the latest `master`.
   2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
   3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
   
   See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202650600


##########
superset/reports/schemas.py:
##########
@@ -125,6 +127,46 @@
     "Creation method is used to inform the frontend whether the report/alert was "
     "created in the dashboard, chart, or alerts and reports UI."
 )
+run_as_description = (
+    "ID of the user whose credentials (RBAC permissions, database OAuth2 tokens) "
+    "are used when rendering the content (screenshot, PDF, CSV, XLSX or text). "
+    "Admins can set any active user; non-admins can only set themselves. Only"
+    "honored when the ALERT_REPORT_DYNAMIC_EXECUTOR feature flag is enabled. "
+    "Admins can set this and run_as_type to null to use ALERT_REPORTS_EXECUTORS."
+)
+run_alert_query_as_description = (
+    "ID of the user whose credentials are used when running the alert condition "
+    "SQL query, useful when the audience of the alert does not have access to the "
+    "database. Null inherits the content executor at execution time."
+)
+
+
+_RUN_AS_FIELD_KEYS = (
+    "run_as",
+    "run_alert_query_as",
+    "run_as_type",
+    "run_alert_query_as_type",
+)
+_REPORT_EXECUTOR_TYPES = [
+    ExecutorType.FIXED_USER,
+]
+
+
+class RunAsFieldStripMixin:
+    """Drop the "Run As" fields from the raw payload when the dynamic executor
+    feature (``ALERT_REPORT_DYNAMIC_EXECUTOR``) is disabled, so callers on the
+    legacy path never store an executor by accident."""
+
+    @pre_load
+    def strip_run_as_fields_if_disabled(
+        self,
+        data: dict[str, Any],
+        **kwargs: Any,
+    ) -> dict[str, Any]:
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):

Review Comment:
   Sure thing! Test coverage added.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Antonio-RiveroMartnez (via GitHub)" <gi...@apache.org>.
Antonio-RiveroMartnez commented on PR #44992:
URL: https://github.com/apache/superset/pull/44992#issuecomment-6064496422

   ## Review โ€” 1 blocker, 2 improvements
   
   **Verdict:** The executor and permission model looks solid to me. The only thing I'd want resolved before merge is a silent change to TEXT-alert content that lands even with `ALERT_REPORT_DYNAMIC_EXECUTOR` off.
   
   ### Blockers
   1. **TEXT alerts with a chart lose their embedded table when alert attachments are off.** `superset/commands/report/execute.py:1599-1604`
      On master (`execute.py:1544-1548`), a chart-backed `TEXT` schedule always called `_get_embedded_data()`. This PR adds a `self._attachments_enabled()` check in front of that. For alerts, the check (`execute.py:483-488`) requires `alerts_attach_reports_enabled()`, which falls back to `ALERTS_ATTACH_REPORTS`.
      So after upgrading, any deployment that runs with `ALERTS_ATTACH_REPORTS = False`, or that saves "Enable attachments for alerts" as off, stops sending the table in TEXT alerts. That happens with the new FF off and with no configuration saved. The PR description says FF-off behavior is unchanged. Neither `UPDATING.md` nor `alerts-reports.mdx:29` says the inline text table is affected; the docs only mention PNG/PDF/CSV/XLSX. This matches @sadpandajoe's unanswered comment on that line.
      Either exempt `ReportDataFormat.TEXT` from the global gate, or, if this is intended, say so explicitly in UPDATING.md and the docs.
   
   ### Improvements
   1. **Config save is a read-merge-write with no lock, and it fails if the stored row is missing.** `superset/daos/report.py:508-525`
      I know this was deferred in https://github.com/apache/superset/pull/44992#discussion_r4215527223. I'm raising it once more because the fix is very small, and it would also fix a second problem in the same code.
      - **Lost updates.** `upsert()` reads the document without a lock, merges the submitted keys, and overwrites the whole document. If two admins save at the same time, one change is lost. If the lost change is `allowed_email_domains` or `limit_recipients_to_users`, recipient delivery is unrestricted again without anyone noticing. Unlike the single-value `shared_entries.py` store, this is the first key_value entry that holds several settings merged into one document. The lock is already available: `KeyValueDAO.get_entry(..., for_update=True)` (`daos/key_value.py:42-54`), as used in `commands/distributed_lock/release.py:112`.
      - **Missing row.** The write goes through `KeyValueDAO.update_entry`, which raises `KeyValueUpdateFailedError` when the row isn't there (`daos/key_value.py:184`). Reads tolerate a missing row (`daos/report.py:459-460`), so the config can be read but never saved on a database without the migration seed (e.g. `create_all`, test fixtures, or a deleted row). It also returns a **500**, not the intended 422: `on_error` only translates `SQLAlchemyError` (`utils/decorators.py:236`), and `KeyValueUpdateFailedError` is an `UpdateFailedError` with `status = 500`.
      - **Suggested fix.** In one transaction: a locking read, then update the row if it exists or create it if it doesn't.
   2. **Factory reset can fail on the retained config row's audit FK.** `superset/commands/security/reset.py:66-83`
      Reset keeps the `ALERT_REPORT_CONFIG` key_value row but deletes every non-Admin user. `KeyValueEntry.changed_by_fk` is a plain FK to `ab_user.id` with no `ON DELETE SET NULL` (`key_value/models.py:40`).
      This is a narrow case: someone saves the config while they're an Admin, later loses the Admin role, and then a reset runs. On a database that enforces FKs, deleting that user fails. Nulling `created_by_fk` / `changed_by_fk` on the retained row before deleting users would avoid it.
   ### Nits
   - `superset/reports/schemas.py:133`: `run_as_description` is missing a space (`"...Only" "honored..."`), so the OpenAPI text reads "Onlyhonored".
   
   ### Considered and dropped
   - **Migration conflict bot warning.** Dropped: `down_revision = "00fab727cd0a"` matches master's current head, and nothing else on master revises it.
   - **`sharded-jest-tests (2)` failure.** Dropped as unrelated: the failing test is in `src/dashboard/components/gridComponents/Chart/Chart.test.tsx` ("Export to full Excel"), and this PR touches nothing under `src/dashboard`.
   - **Non-admin escalation through Run as.** I checked these paths and found no gap:
     - selecting another user (`commands/report/base.py:493-495`)
     - clearing the query executor so it inherits another identity (`update.py:302-323`)
     - changing content or recipients while another identity is still in place (`update.py:275-300`)
     - subscription recipient rewriting, which happens before the protected-field comparison (`update.py:389-419`)
     - deleted or inactive executors, which fail closed rather than falling back to defaults (`reports/utils.py:77-81`, `execute.py:147-180`)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4191840333


##########
tests/unit_tests/commands/report/run_as_test.py:
##########
@@ -0,0 +1,750 @@
+# 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 the per-schedule "Run As" executor validation (SIP-209) in the
+create and update report schedule commands.
+"""
+
+from typing import Any
+from unittest.mock import Mock
+
+import pytest
+from marshmallow import ValidationError
+from pytest_mock import MockerFixture
+
+from superset.commands.report.create import CreateReportScheduleCommand
+from superset.commands.report.exceptions import (
+    ReportScheduleFormatRequiredError,
+    ReportScheduleInvalidError,
+    ReportScheduleRecipientNotAllowedError,
+    ReportScheduleRunAlertQueryAsNotAllowedError,
+    ReportScheduleRunAsContentForbiddenError,
+    ReportScheduleRunAsForbiddenError,
+    ReportScheduleRunAsNotFoundError,
+)
+from superset.commands.report.update import UpdateReportScheduleCommand
+from superset.reports.models import ReportDataFormat, ReportScheduleType
+
+CREATE = "superset.commands.report.create"
+UPDATE = "superset.commands.report.update"
+BASE = "superset.commands.report.base"
+
+
+def _user(user_id: int, active: bool = True) -> Mock:
+    user = Mock()
+    user.id = user_id
+    user.is_active = active
+    user.username = f"user{user_id}"
+    return user
+
+
+CURRENT_USER = _user(1)
+OTHER_USER = _user(2)
+USERS = {1: CURRENT_USER, 2: OTHER_USER, 3: _user(3, active=False)}
+
+
+def _stub_security(mocker: MockerFixture, *, is_admin: bool) -> Mock:
+    security_manager = Mock()
+    security_manager.is_admin.return_value = is_admin
+    security_manager.get_user_by_id.side_effect = lambda pk: USERS.get(pk)
+    mocker.patch(f"{BASE}.security_manager", security_manager)
+    mocker.patch(f"{BASE}.get_user", return_value=CURRENT_USER)
+    return security_manager
+
+
+def _errors(exc: pytest.ExceptionInfo[ReportScheduleInvalidError]) -> list[type]:
+    return [type(e) for e in exc.value._exceptions]
+
+
+# ---------------------------------------------------------------------------
+# Create
+# ---------------------------------------------------------------------------
+
+
+def _stub_create_deps(
+    mocker: MockerFixture, *, feature_enabled: bool, stub_policy: bool = True
+) -> None:
+    mocker.patch.object(CreateReportScheduleCommand, "_populate_recipients")
+    mocker.patch(
+        f"{CREATE}.ReportScheduleDAO.validate_update_uniqueness", return_value=True
+    )
+    mocker.patch(
+        f"{CREATE}.ReportScheduleDAO.validate_unique_creation_method",
+        return_value=True,
+    )
+    mocker.patch.object(CreateReportScheduleCommand, "validate_report_frequency")
+    mocker.patch.object(CreateReportScheduleCommand, "validate_chart_dashboard")
+    mocker.patch.object(CreateReportScheduleCommand, "_validate_report_extra")
+    if stub_policy:
+        mocker.patch.object(CreateReportScheduleCommand, "validate_recipients_policy")
+    mocker.patch(f"{CREATE}.populate_subjects")
+    mocker.patch(f"{CREATE}.is_feature_enabled", return_value=feature_enabled)
+
+
+def _create_command(**overrides: Any) -> CreateReportScheduleCommand:
+    command = CreateReportScheduleCommand({})
+    command._properties = {
+        "type": ReportScheduleType.REPORT,
+        "name": "Test",
+        "crontab": "0 9 * * *",
+        "creation_method": "alerts_reports",
+        **overrides,
+    }
+    return command
+
+
+def test_create_feature_disabled_drops_run_as_fields(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False)
+    security_manager = _stub_security(mocker, is_admin=True)
+
+    command = _create_command(run_as=2, run_alert_query_as=2)
+    command.validate()
+
+    assert "run_as" not in command._properties
+    assert "run_alert_query_as" not in command._properties
+    security_manager.get_user_by_id.assert_not_called()
+
+
+def test_create_defaults_run_as_to_current_user(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command()
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+    # Reports never carry an alert query executor.
+    assert "run_alert_query_as" not in command._properties
+
+
+def test_admin_can_create_with_application_default_executor(
+    mocker: MockerFixture,
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command(run_as=None, run_as_type=None)
+    command.validate()
+
+    assert command._properties["run_as"] is None
+    assert command._properties["run_as_type"] is None
+
+
+def test_create_alert_defaults_query_executor_to_run_as(
+    mocker: MockerFixture,
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+
+    command = _create_command(type=ReportScheduleType.ALERT, database=1, run_as=2)
+    command.validate()
+
+    assert command._properties["run_as"] is OTHER_USER
+    assert command._properties["run_alert_query_as"] is None
+
+
+def test_create_alert_with_distinct_query_executor(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+
+    command = _create_command(
+        type=ReportScheduleType.ALERT, database=1, run_as=1, run_alert_query_as=2
+    )
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+    assert command._properties["run_alert_query_as"] is OTHER_USER
+
+
+def test_create_non_admin_cannot_impersonate_another_user(
+    mocker: MockerFixture,
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=False)
+
+    command = _create_command(run_as=2)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_create_non_admin_may_set_themselves(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=False)
+
+    command = _create_command(run_as=1)
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+
+
+def test_create_rejects_missing_or_inactive_user(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    for user_id in (3, 999):
+        command = _create_command(run_as=user_id)
+        with pytest.raises(ReportScheduleInvalidError) as exc:
+            command.validate()
+        assert ReportScheduleRunAsNotFoundError in _errors(exc)
+
+
+def test_create_report_rejects_alert_query_executor(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command(run_alert_query_as=1)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAlertQueryAsNotAllowedError in _errors(exc)
+
+
+def test_create_report_rejects_no_attachment_format(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command(report_format=ReportDataFormat.NONE)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleFormatRequiredError in _errors(exc)
+
+
+def test_create_alert_allows_no_attachment_format(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+
+    command = _create_command(
+        type=ReportScheduleType.ALERT, database=1, report_format=ReportDataFormat.NONE
+    )
+    command.validate()
+
+
+def test_create_enforces_recipient_policy(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False, stub_policy=False)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(
+        f"{BASE}.ReportConfigDAO.find_disallowed_addresses",
+        return_value=["x@other.org"],
+    )
+
+    command = _create_command(
+        recipients=[
+            {
+                "type": "Email",
+                "recipient_config_json": {"target": "x@other.org"},
+            }
+        ]
+    )
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRecipientNotAllowedError in _errors(exc)
+
+
+# ---------------------------------------------------------------------------
+# Update
+# ---------------------------------------------------------------------------
+
+
+def _make_model(
+    *,
+    model_type: ReportScheduleType = ReportScheduleType.REPORT,
+    run_as: Mock | None = None,
+    run_alert_query_as: Mock | None = None,
+) -> Mock:
+    model = Mock()
+    model.type = model_type
+    model.database_id = 5 if model_type == ReportScheduleType.ALERT else None
+    model.creation_method = "alerts_reports"
+    model.name = "test_schedule"
+    model.crontab = "0 9 * * *"
+    model.last_state = "noop"
+    model.editors = []
+    model.retry_on_failure = False
+    model.send_failed_reports = False
+    model.chart_id = None
+    model.dashboard_id = 10
+    model.custom_width = None
+    model.extra_json = '{"dashboard": {"anchor": ""}}'
+    model.recipients = []
+    model.report_format = "PNG"
+    model.sql = None
+    model.validator_config_json = "{}"
+    model.validator_type = None
+    model.run_as_type = "fixed_user" if run_as else None
+    model.run_alert_query_as_type = "fixed_user" if run_alert_query_as else None
+    model.run_as = run_as
+    model.run_as_fk = run_as.id if run_as else None
+    model.run_alert_query_as = run_alert_query_as
+    model.run_alert_query_as_fk = run_alert_query_as.id if run_alert_query_as else None
+    return model
+
+
+def _stub_update_deps(
+    mocker: MockerFixture, model: Mock, *, is_admin: bool, feature_enabled: bool = True
+) -> None:
+    mocker.patch(f"{UPDATE}.ReportScheduleDAO.find_by_id", return_value=model)
+    mocker.patch(
+        f"{UPDATE}.ReportScheduleDAO.validate_update_uniqueness", return_value=True
+    )
+    mocker.patch(f"{UPDATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_chart_dashboard")
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_report_frequency")
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_alert_query")
+    mocker.patch.object(UpdateReportScheduleCommand, "_validate_report_extra")
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_recipients_policy")
+    mocker.patch(f"{UPDATE}.compute_subjects")
+    mocker.patch(f"{UPDATE}.is_feature_enabled", return_value=feature_enabled)
+    mocker.patch(f"{UPDATE}.get_user_id", return_value=CURRENT_USER.id)
+    update_security_manager = Mock()
+    update_security_manager.is_admin.return_value = is_admin
+    mocker.patch(f"{UPDATE}.security_manager", update_security_manager)
+    _stub_security(mocker, is_admin=is_admin)
+
+
+def test_update_feature_disabled_drops_run_as_fields(mocker: MockerFixture) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=True, feature_enabled=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": 2, "run_alert_query_as": 2})
+    command.validate()
+
+    assert "run_as" not in command._properties
+    assert "run_alert_query_as" not in command._properties
+
+
+def test_update_admin_sets_and_clears_run_as(mocker: MockerFixture) -> None:
+    model = _make_model(run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": 2})
+    command.validate()
+    assert command._properties["run_as"] is OTHER_USER
+
+    # Explicit null reverts to the legacy ALERT_REPORTS_EXECUTORS resolution.
+    command = UpdateReportScheduleCommand(1, {"run_as": None})
+    command.validate()
+    assert command._properties["run_as"] is None
+    assert command._properties["run_as_type"] is None
+
+
+def test_update_non_admin_null_resolves_to_themselves(mocker: MockerFixture) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": None})
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+
+
+def test_update_non_admin_cannot_point_at_another_user(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": 2})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_update_non_admin_can_change_metadata_of_schedule_run_by_other(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    # Unchanged content fields sent back by the UI do not count as changes.
+    command = UpdateReportScheduleCommand(
+        1,
+        {
+            "active": False,
+            "name": "renamed",
+            "dashboard": 10,
+            "chart": None,
+            "report_format": "PNG",
+            "extra": {"dashboard": {"anchor": ""}},
+            "recipients": [],
+        },
+    )
+    command.validate()
+
+
+def test_update_non_admin_cannot_change_content_of_schedule_run_by_other(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"dashboard": 11})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAsContentForbiddenError in _errors(exc)
+
+
+def test_update_non_admin_can_change_content_after_taking_over(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"dashboard": 11, "run_as": 1})
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+
+
+def test_update_admin_can_change_content_of_schedule_run_by_other(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    UpdateReportScheduleCommand(1, {"dashboard": 11}).validate()
+
+
+def test_update_report_clears_stale_alert_query_executor(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=CURRENT_USER, run_alert_query_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"name": "renamed"})
+    command.validate()
+
+    assert command._properties["run_alert_query_as"] is None
+
+
+def test_update_report_rejects_alert_query_executor(mocker: MockerFixture) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": 2})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAlertQueryAsNotAllowedError in _errors(exc)
+
+
+def test_update_alert_query_executor_is_validated(mocker: MockerFixture) -> None:
+    model = _make_model(model_type=ReportScheduleType.ALERT, run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": 2})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": 1})
+    command.validate()
+    assert command._properties["run_alert_query_as"] is CURRENT_USER
+
+
+def test_update_report_rejects_no_attachment_format(mocker: MockerFixture) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.NONE})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleFormatRequiredError in _errors(exc)
+
+
+@pytest.mark.parametrize(
+    "executor_type",
+    ["creator", "creator_editor", "modifier", "modifier_editor", "editor"],
+)
+def test_admin_cannot_create_typed_executor(
+    mocker: MockerFixture, executor_type: str
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+    command = _create_command(run_as_type=executor_type)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ValidationError in _errors(exc)
+
+
+@pytest.mark.parametrize(
+    "executor_type",
+    ["creator", "creator_editor", "modifier", "modifier_editor", "editor"],
+)
+def test_non_admin_cannot_select_typed_executor(
+    mocker: MockerFixture, executor_type: str
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=False)
+    command = _create_command(run_as_type=executor_type)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_clear_content_executor_restores_application_default(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+    command = UpdateReportScheduleCommand(1, {"run_as": None})
+    command.validate()
+    assert command._properties["run_as_type"] is None
+    assert command._properties["run_as"] is None
+
+
+def test_clear_query_executor_inherits_content(mocker: MockerFixture) -> None:
+    model = _make_model(
+        model_type=ReportScheduleType.ALERT,
+        run_as=OTHER_USER,
+        run_alert_query_as=CURRENT_USER,
+    )
+    _stub_update_deps(mocker, model, is_admin=True)
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": None})
+    command.validate()
+    assert command._properties["run_alert_query_as"] is None
+    assert command._properties["run_alert_query_as_type"] is None
+
+
+@pytest.mark.parametrize("active", [False, True])
+def test_enabling_attachment_validates_existing_content_user(
+    active: bool, mocker: MockerFixture
+) -> None:
+    from superset.reports.models import ReportSchedule
+
+    mocker.patch(f"{UPDATE}.is_feature_enabled", return_value=True)
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.PNG})
+    command._model = ReportSchedule(
+        report_format=ReportDataFormat.NONE, run_as_type="fixed_user"
+    )
+    command._model.run_as = _user(2, active=active)
+    errors: list[ValidationError] = []
+    command._validate_attachment_executor(errors)
+    assert bool(errors) is not active
+    if errors:
+        assert isinstance(errors[0], ReportScheduleRunAsNotFoundError)
+
+
+def test_enabling_attachment_rejects_deleted_content_user(
+    mocker: MockerFixture,
+) -> None:
+    from superset.reports.models import ReportSchedule
+
+    mocker.patch(f"{UPDATE}.is_feature_enabled", return_value=True)
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.PNG})
+    command._model = ReportSchedule(
+        report_format=ReportDataFormat.NONE, run_as_type="fixed_user"
+    )
+    errors: list[ValidationError] = []
+    command._validate_attachment_executor(errors)
+    assert isinstance(errors[0], ReportScheduleRunAsNotFoundError)
+
+
+@pytest.mark.parametrize("field", ["run_as", "run_alert_query_as"])
+@pytest.mark.parametrize(
+    "selection",
+    [
+        "creator",
+        "creator_editor",
+        "modifier",
+        "modifier_editor",
+        "editor",
+        "other_user",
+    ],
+)
+def test_non_admin_update_cannot_choose_other_execution_identity(
+    field: str,
+    selection: str,
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(model_type=ReportScheduleType.ALERT, run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+    command = UpdateReportScheduleCommand(
+        1,
+        {
+            field: OTHER_USER.id if selection == "other_user" else None,
+            f"{field}_type": "fixed_user" if selection == "other_user" else selection,
+        },
+    )
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_non_admin_takes_over_both_alert_executors_before_content_edit(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(
+        model_type=ReportScheduleType.ALERT,
+        run_as=OTHER_USER,
+        run_alert_query_as=OTHER_USER,
+    )
+    _stub_update_deps(mocker, model, is_admin=False)
+    command = UpdateReportScheduleCommand(
+        1,
+        {
+            "dashboard": 11,
+            "run_as": CURRENT_USER.id,
+            "run_as_type": "fixed_user",
+            "run_alert_query_as": CURRENT_USER.id,
+            "run_alert_query_as_type": "fixed_user",
+        },
+    )
+    command.validate()
+    assert command._properties["run_as"] is CURRENT_USER
+    assert command._properties["run_alert_query_as"] is CURRENT_USER
+
+
+def test_non_admin_legacy_content_edits_require_explicit_self(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=False)
+    metadata = UpdateReportScheduleCommand(1, {"name": "renamed"})
+    metadata.validate()
+    assert "run_as" not in metadata._properties
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        UpdateReportScheduleCommand(1, {"dashboard": 11}).validate()
+    assert ReportScheduleRunAsContentForbiddenError in _errors(exc)
+    own = UpdateReportScheduleCommand(
+        1, {"dashboard": 11, "run_as": CURRENT_USER.id, "run_as_type": "fixed_user"}
+    )
+    own.validate()
+    assert own._properties["run_as"] is CURRENT_USER
+
+
+@pytest.mark.parametrize(
+    ("report_type", "report_format", "global_enabled", "requires_asset"),
+    [
+        (ReportScheduleType.ALERT, ReportDataFormat.NONE, True, False),
+        (ReportScheduleType.ALERT, ReportDataFormat.PNG, False, False),
+        (ReportScheduleType.ALERT, ReportDataFormat.PNG, True, True),
+        (ReportScheduleType.REPORT, ReportDataFormat.PNG, False, True),
+    ],
+)
+def test_create_attachment_asset_requirement(
+    report_type: str,
+    report_format: str,
+    global_enabled: bool,
+    requires_asset: bool,
+    mocker: MockerFixture,
+) -> None:
+    from superset.commands.report.base import BaseReportScheduleCommand
+    from superset.commands.report.exceptions import (
+        ReportScheduleEitherChartOrDashboardError,
+    )
+
+    _stub_create_deps(mocker, feature_enabled=False)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch.object(
+        CreateReportScheduleCommand,
+        "validate_chart_dashboard",
+        BaseReportScheduleCommand.validate_chart_dashboard,
+    )
+    mocker.patch(
+        f"{BASE}.ReportConfigDAO.get_effective_value", return_value=global_enabled
+    )
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+    command = _create_command(type=report_type, report_format=report_format, database=1)
+    if requires_asset:
+        with pytest.raises(ReportScheduleInvalidError) as exc:
+            command.validate()
+        assert ReportScheduleEitherChartOrDashboardError in _errors(exc)
+    else:
+        command.validate()
+
+
+@pytest.mark.parametrize("include_asset", [False, True])
+def test_enabling_attachment_requires_asset_on_update(
+    include_asset: bool, mocker: MockerFixture
+) -> None:
+    from superset.commands.report.base import BaseReportScheduleCommand
+    from superset.commands.report.exceptions import (
+        ReportScheduleEitherChartOrDashboardError,
+    )
+
+    model = _make_model(model_type=ReportScheduleType.ALERT, run_as=CURRENT_USER)
+    model.report_format = ReportDataFormat.NONE
+    model.dashboard_id = 10 if include_asset else None
+    _stub_update_deps(mocker, model, is_admin=True)
+    mocker.patch.object(
+        UpdateReportScheduleCommand,
+        "validate_chart_dashboard",
+        BaseReportScheduleCommand.validate_chart_dashboard,
+    )
+    mocker.patch(f"{BASE}.ReportConfigDAO.get_effective_value", return_value=True)
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.PNG})
+    if include_asset:
+        command.validate()
+    else:
+        with pytest.raises(ReportScheduleInvalidError) as exc:
+            command.validate()
+        assert ReportScheduleEitherChartOrDashboardError in _errors(exc)
+
+
+def test_attachment_free_alert_keeps_supplied_asset_and_validates_access(
+    mocker: MockerFixture,
+) -> None:
+    from superset.commands.report.base import BaseReportScheduleCommand
+    from superset.commands.report.exceptions import ReportScheduleForbiddenError
+    from superset.exceptions import SupersetSecurityException
+
+    _stub_create_deps(mocker, feature_enabled=False)
+    manager = _stub_security(mocker, is_admin=True)
+    mocker.patch.object(
+        CreateReportScheduleCommand,
+        "validate_chart_dashboard",
+        BaseReportScheduleCommand.validate_chart_dashboard,
+    )
+    dashboard = Mock()
+    mocker.patch(f"{BASE}.DashboardDAO.find_by_id", return_value=dashboard)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+    command = _create_command(
+        type=ReportScheduleType.ALERT,
+        database=1,
+        report_format=ReportDataFormat.NONE,
+        dashboard=10,
+    )
+    command.validate()
+    assert command._properties["dashboard"] is dashboard
+    assert command._properties["report_format"] == ReportDataFormat.NONE
+    manager.raise_for_access.assert_called_once_with(dashboard=dashboard)

Review Comment:
   Test fixed. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4191876377


##########
superset/commands/report/base.py:
##########
@@ -134,13 +148,33 @@ def _check_object_access(
                 raise ReportScheduleForbiddenError() from ex
         self._properties[kind] = obj
 
+    def requires_attachment(self) -> bool:
+        """Whether the effective schedule configuration requires attachment content."""
+        model = getattr(self, "_model", None)
+        report_type = self._properties.get(
+            "type", getattr(model, "type", ReportScheduleType.REPORT)
+        )
+        report_format = self._properties.get(
+            "report_format", getattr(model, "report_format", ReportDataFormat.PNG)
+        )
+        return report_type == ReportScheduleType.REPORT or (
+            report_format != ReportDataFormat.NONE
+            and bool(
+                ReportConfigDAO.get_effective_value(
+                    ReportConfigKey.ALERTS_ATTACH_REPORTS
+                )
+            )
+        )
+
     def validate_chart_dashboard(
         self, exceptions: list[ValidationError], update: bool = False
     ) -> None:
         """Validate chart or dashboard relation"""
         chart_id = self._properties.get("chart")
         dashboard_id = self._properties.get("dashboard")
         creation_method = self._properties.get("creation_method")
+        if not (requires_attachment := self.requires_attachment()):
+            return

Review Comment:
   Already addressed



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4200312893


##########
superset/commands/report/update.py:
##########
@@ -42,17 +47,61 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(

Review Comment:
   @sadpandajoe it's a good question. I had these fields in there initially, but my original thought was that changes to DB/SQL/validation would only change when the alert is triggered, not really the actual attachment that's being sent. I didn't think about the `last_value_row_json`, tho. I'll look into this. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202649434


##########
superset/commands/report/base.py:
##########
@@ -345,45 +393,118 @@ def validate_report_frequency(
         report_type: str,
     ) -> None:
         """
-        Validates if the report scheduled frequency doesn't exceed a limit
-        configured in `config.py`.
+        Validates if the report scheduled frequency doesn't exceed the minimum
+        interval in effect.
 
         :param cron_schedule: The cron schedule configured.
         :param report_type: The report type (Alert/Report).
         """
         config_key = (
-            "ALERT_MINIMUM_INTERVAL"
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL
             if report_type == ReportScheduleType.ALERT
-            else "REPORT_MINIMUM_INTERVAL"
+            else ReportConfigKey.REPORT_MINIMUM_INTERVAL
         )
-        minimum_interval = app.config.get(config_key, 0)
-        if callable(minimum_interval):
-            minimum_interval = minimum_interval()
+        minimum_interval = ReportConfigDAO.get_effective_value(config_key)

Review Comment:
   Added coverage for this one as well. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202644547


##########
superset/commands/report/update.py:
##########
@@ -88,6 +284,14 @@ def validate(self) -> None:  # noqa: C901
 
         exceptions: list[ValidationError] = []
 
+        # Snapshot content changes before validators replace ids with objects.
+        # Only needed for the "Run As" authorization rules (SIP-209).
+        changed_content_fields = (

Review Comment:
   True. Addressing this one now. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4215731178


##########
superset/commands/security/reset.py:
##########
@@ -62,7 +63,10 @@ def run(self) -> None:
             db.session.delete(database)
         db.session.query(Dashboard).delete()
         db.session.query(Slice).delete()
-        db.session.query(KeyValueEntry).delete()
+        config_uuid = FIXED_RESOURCE_KEYS[KeyValueResource.ALERT_REPORT_CONFIG]
+        db.session.query(KeyValueEntry).filter(
+            KeyValueEntry.uuid.is_(None) | (KeyValueEntry.uuid != config_uuid)

Review Comment:
   Preserving the configuration row keeps its `changed_by_fk`/`created_by_fk` pointing at the admin who saved it, and those `ab_user` FKs have no `ON DELETE`. If that user was later demoted from Admin, the reset deletes them below while the retained row still references them, so the reset can fail on an FK-enforcing database (and no test runs this command with a config row present). Should the preserved row's audit columns be cleared before the users are deleted?



##########
superset/commands/report/execute.py:
##########
@@ -1542,7 +1597,8 @@ def _get_notification_content(self) -> NotificationContent:  # noqa: C901
                 )
 
         if (
-            self._report_schedule.chart
+            self._attachments_enabled()

Review Comment:
   On master the embedded table for a `TEXT` alert with a chart was built regardless of the attachments setting, but with this gate a deployment running with attachments disabled (`ALERTS_ATTACH_REPORTS` off) silently stops receiving that table after upgrade, even with `ALERT_REPORT_DYNAMIC_EXECUTOR` off. The PR description says flag-off behavior is unchanged, so is dropping the embedded data for those existing alerts intended, or should this branch stay ungated?



##########
tests/unit_tests/reports/utils_test.py:
##########
@@ -0,0 +1,222 @@
+# 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 unittest.mock import Mock
+
+import pytest
+from pytest_mock import MockerFixture
+
+from superset.commands.report.exceptions import ReportScheduleExecutorNotFoundError
+from superset.reports.models import ReportRecipientType
+from superset.reports.utils import (
+    cron_meets_minimum_interval,
+    find_disallowed_addresses,
+    get_dynamic_executor,
+    get_email_addresses,
+    get_email_domain,
+)
+
+
+def test_get_email_addresses_from_dict_payload_includes_cc_and_bcc() -> None:
+    recipients = [
+        {
+            "type": ReportRecipientType.EMAIL,
+            "recipient_config_json": {
+                "target": "a@foo.com",
+                "ccTarget": "b@bar.org",
+                "bccTarget": "c@baz.net",
+            },
+        },
+        {"type": ReportRecipientType.SLACK, "recipient_config_json": {"target": "#c"}},
+    ]
+    assert get_email_addresses(recipients) == ["a@foo.com", "b@bar.org", "c@baz.net"]
+
+
+def test_get_email_addresses_from_model_with_json_string() -> None:
+    recipient = Mock()
+    recipient.type = ReportRecipientType.EMAIL
+    recipient.recipient_config_json = '{"target": "a@foo.com;b@bar.org"}'
+    broken = Mock()
+    broken.type = ReportRecipientType.EMAIL
+    broken.recipient_config_json = "not json"
+    assert get_email_addresses([recipient, broken]) == ["a@foo.com", "b@bar.org"]
+    assert get_email_addresses(None) == []
+
+
+def test_whitespace_separated_recipient_cannot_bypass_domain_policy() -> None:
+    recipient = Mock(
+        type=ReportRecipientType.EMAIL,
+        recipient_config_json=(
+            '{"target": "external@outside.org internal@example.com"}'
+        ),
+    )
+
+    addresses = get_email_addresses([recipient])
+
+    assert addresses == ["external@outside.org", "internal@example.com"]
+    assert find_disallowed_addresses(
+        addresses, allowed_domains=["example.com"], known_emails=None
+    ) == ["external@outside.org"]
+
+
+def test_get_email_domain() -> None:
+    assert get_email_domain("Bob@Example.COM") == "example.com"
+    assert get_email_domain("not-an-email") is None
+
+
+def test_find_disallowed_addresses_domain_allowlist() -> None:
+    disallowed = find_disallowed_addresses(
+        ["ok@example.com", "OK2@EXAMPLE.com", "nope@other.org", "nope@other.org"],
+        allowed_domains=["Example.com"],
+        known_emails=None,
+    )
+    assert disallowed == ["nope@other.org"]
+
+
+def test_find_disallowed_addresses_users_only() -> None:
+    disallowed = find_disallowed_addresses(
+        ["user@example.com", "ghost@example.com"],
+        allowed_domains=None,
+        known_emails={"user@example.com"},
+    )
+    assert disallowed == ["ghost@example.com"]
+
+
+def test_find_disallowed_addresses_no_policy() -> None:
+    assert (
+        find_disallowed_addresses(
+            ["anyone@anywhere.io"], allowed_domains=[], known_emails=None
+        )
+        == []
+    )
+
+
+@pytest.mark.parametrize(
+    ("cron", "minimum_interval", "expected"),
+    [
+        ("* * * * *", 0, True),
+        ("* * * * *", 119, True),
+        ("* * * * *", 300, False),
+        ("*/5 * * * *", 300, True),
+        ("*/5 * * * *", 600, False),
+        ("0 * * * *", 3600, True),
+        ("0 */2 * * *", 3600 * 3, False),
+        ("0 0 * * *", 3600 * 24, True),
+    ],
+)
+def test_cron_meets_minimum_interval(
+    cron: str, minimum_interval: int, expected: bool
+) -> None:
+    assert cron_meets_minimum_interval(cron, minimum_interval) is expected
+
+
+def test_get_dynamic_executor_disabled(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=False)
+    schedule = Mock(
+        run_as=Mock(),
+        run_alert_query_as=Mock(),
+        run_as_type=None,

Review Comment:
   Both executor types are `None` here, so `get_dynamic_executor` returns `None` even if the `ALERT_REPORT_DYNAMIC_EXECUTOR` guard in `superset/reports/utils.py` is removed; the same gap exists in `test_get_executor_user_ignores_run_as_when_feature_disabled`, which sets `run_as` but never `run_as_type`. A schedule saved with `fixed_user` executors then run with the flag turned off would pick up the stored identity without any test failing. Could these set `run_as_type`/`run_alert_query_as_type` to `fixed_user` so the flag check is what produces `None`?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4224422238


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -985,10 +1072,63 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
       extra: contentType === ContentType.Dashboard ? currentAlert?.extra : {},
     };
 
+    if (!isReport && !attachmentControlsVisible && !isEditMode) {
+      data.report_format = 'NONE';
+    }
+    if (!attachmentControlsVisible && isEditMode) {
+      // Hidden settings stay stored; only the format controls attachment delivery.
+      delete data.chart;
+      delete data.dashboard;
+      delete data.extra;
+      delete data.custom_width;
+      delete data.force_screenshot;
+    }
+
     if (data.recipients && !data.recipients.length) {
       delete data.recipients;
     }
 
+    // Preserve existing identities unless an admin chooses or the user takes over.
+    delete data.run_as;
+    delete data.run_alert_query_as;
+    delete data.run_as_type;
+    delete data.run_alert_query_as_type;
+    if (dynamicExecutorEnabled && isAdmin) {
+      data.run_as_type = currentAlert?.run_as_type ?? null;

Review Comment:
   I'd say this is expected: most other flows in Superset are like that (`PUT` including all payload). Also, the error will flag to the admin right away this schedule needs fixing. 



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4214194303


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -985,10 +1072,64 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
       extra: contentType === ContentType.Dashboard ? currentAlert?.extra : {},
     };
 
+    if (!isReport && !attachmentControlsVisible && !isEditMode) {
+      data.report_format = 'NONE';
+    }
+    if (!attachmentControlsVisible && isEditMode) {
+      // Hidden settings stay stored; only the format controls attachment delivery.
+      delete data.chart;
+      delete data.dashboard;
+      delete data.extra;
+      delete data.custom_width;
+      delete data.force_screenshot;
+      delete data.include_cta;

Review Comment:
   The "Include a link back to Superset" checkbox lives inside the attachment-controls block, and saving without those controls deletes `include_cta` from the payload. So if an editor unchecks the link and then turns the attachment off (or attachments are globally off for alerts), the unchecked choice is silently dropped and the notifications keep the chart link. `include_cta` is stored independently of the format and is read in the executor regardless of attachments, so should this be left in the payload and the checkbox kept outside the attachment-only block?



##########
superset/commands/report/update.py:
##########
@@ -193,6 +489,18 @@ def validate(self) -> None:  # noqa: C901
             include_viewers=False,
         )
 
+        self.validate_report_format(
+            report_type,
+            self._properties.get("report_format", self._model.report_format),
+            exceptions,
+        )
+        if "recipients" in self._properties:
+            self.validate_recipients_policy(exceptions)

Review Comment:
   The PUT path's recipient-policy check has no test that would fail if this call were removed. `run_as_test.py` stubs `validate_recipients_policy` on `UpdateReportScheduleCommand`, and the API recipient-update tests run with no allowlist, while the only unstubbed policy test (`test_create_enforces_recipient_policy`) covers create. Could you add an update-command test with a stored allowlist and a recipient outside it, asserting the invalid-error contains `ReportScheduleRecipientNotAllowedError` and the stored recipients are unchanged?



##########
superset/reports/schemas.py:
##########
@@ -628,6 +743,106 @@ def validate_custom_width(
             )
 
 
+def validate_email_domain(value: str) -> None:
+    if not EMAIL_DOMAIN_REGEX.match(value.strip()):
+        raise ValidationError(_("Invalid e-mail domain: %(domain)s", domain=value))
+
+
+class ReportConfigurationSchema(Schema):
+    """
+    Global Alerts & Reports configuration (SIP-209).
+
+    Every field is optional on update: absent fields keep their stored value and
+    ``null`` clears a setting without restoring its legacy fallback.
+    """
+
+    alerts_attach_reports = fields.Boolean(
+        metadata={
+            "description": "Whether alerts deliver their attachment (screenshot, "
+            "PDF, CSV or XLSX). When disabled, alerts only send the message and "
+            "link. Falls back to the FF until a row has first been saved."
+        },
+        required=False,
+        allow_none=True,
+    )
+    date_format_in_email_subject = fields.Boolean(
+        metadata={
+            "description": "Render strftime date placeholders in email subjects. "
+            "Falls back to the DATE_FORMAT_IN_EMAIL_SUBJECT FF until first saved."
+        },
+        required=False,
+        allow_none=True,
+    )
+    alert_minimum_interval = fields.Integer(
+        metadata={
+            "description": "Minimum interval between alert executions, in seconds. "
+            "Values below 120 do not restrict schedules. Falls back to "
+            "ALERT_MINIMUM_INTERVAL only before this setting has been saved.",
+            "example": 3600,
+        },
+        required=False,
+        allow_none=True,
+        validate=[Range(min=0, error=lazy_gettext("Value must be 0 or greater"))],
+    )
+    report_minimum_interval = fields.Integer(
+        metadata={
+            "description": "Minimum interval between report executions, in seconds. "
+            "Values below 120 do not restrict schedules. Falls back to "
+            "REPORT_MINIMUM_INTERVAL only before this setting has been saved.",
+            "example": 3600,
+        },
+        required=False,
+        allow_none=True,
+        validate=[Range(min=0, error=lazy_gettext("Value must be 0 or greater"))],
+    )
+    limit_recipients_to_users = fields.Boolean(
+        metadata={
+            "description": "When enabled, only e-mail addresses of existing active "
+            "users are accepted as recipients."
+        },
+        required=False,
+        allow_none=True,
+    )
+    allowed_email_domains = fields.List(
+        fields.String(validate=validate_email_domain),
+        metadata={
+            "description": "E-mail domains accepted as recipients. An empty list "
+            "allows any domain.",
+            "example": ["example.com", "superset.com"],
+        },
+        required=False,
+        allow_none=True,
+    )
+
+    @pre_load
+    def normalize_domains(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
+        domains = data.get("allowed_email_domains")

Review Comment:
   `normalize_domains` calls `data.get(...)` before Marshmallow checks that the body is an object, so an admin `PUT /configuration/` with a JSON body of `[]` or `null` raises `AttributeError`. The endpoint only catches `ValidationError`, so that surfaces as a 500 instead of the documented 400. Would a guard like `if not isinstance(data, dict): return data` here let the normal type validation produce the 400?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4214616067


##########
superset/daos/report.py:
##########
@@ -392,3 +404,187 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) with at least one e-mail recipient.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .join(
+                ReportRecipients,
+                ReportRecipients.report_schedule_id == ReportSchedule.id,
+            )
+            .filter(ReportRecipients.type == ReportRecipientType.EMAIL)
+            .options(selectinload(ReportSchedule.recipients))
+            .distinct()
+            .all()
+        )
+
+    @staticmethod
+    def find_by_type(report_type: ReportScheduleType) -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) of the given type.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.type == report_type)
+            .all()
+        )
+
+
+class ReportConfigDAO:
+    """
+    Access to the global Alerts & Reports configuration in ``key_value``.
+
+    One versioned document stores only settings explicitly saved by an admin.
+    Missing settings resolve to legacy application config or feature flag values.
+    """
+
+    VERSION: Literal[1] = 1
+
+    @staticmethod
+    def get_stored_values() -> dict[str, Any]:
+        """
+        Return explicitly saved settings from the versioned document.
+
+        A stored null is distinct from a missing setting key.
+        """
+        document: ReportConfigDocument | None = KeyValueDAO.get_value(
+            KeyValueResource.ALERT_REPORT_CONFIG,
+            FIXED_RESOURCE_KEYS[KeyValueResource.ALERT_REPORT_CONFIG],
+            JsonKeyValueCodec(),
+        )
+        if document is None:
+            return {}
+        return dict(document["settings"])
+
+    @staticmethod
+    def get_fallback_value(key: ReportConfigKey) -> Any:
+        """Return the legacy application config / feature flag value for ``key``."""
+        if key == ReportConfigKey.ALERTS_ATTACH_REPORTS:
+            return feature_flag_manager.is_feature_enabled("ALERTS_ATTACH_REPORTS")
+        if key == ReportConfigKey.DATE_FORMAT_IN_EMAIL_SUBJECT:
+            return feature_flag_manager.is_feature_enabled(
+                "DATE_FORMAT_IN_EMAIL_SUBJECT"
+            )
+        if key in (
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL,
+            ReportConfigKey.REPORT_MINIMUM_INTERVAL,
+        ):
+            value = current_app.config.get(key.upper(), 0)
+            return value() if callable(value) else value
+        # These are new configs, no legacy fallback
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return False
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return []
+        return None
+
+    @staticmethod
+    def get_effective_value(key: ReportConfigKey) -> Any:
+        """
+        Return the value in effect for ``key``: the stored value when present,
+        otherwise the legacy fallback.
+        """
+        if key in (stored := ReportConfigDAO.get_stored_values()):
+            return stored[key]
+        return ReportConfigDAO.get_fallback_value(key)
+
+    @staticmethod
+    def get_effective_config() -> dict[str, Any]:
+        """Return the value in effect for every ``ReportConfigKey``."""
+        stored = ReportConfigDAO.get_stored_values()
+        return {
+            key.value: (
+                stored[key]
+                if key in stored
+                else ReportConfigDAO.get_fallback_value(key)
+            )
+            for key in ReportConfigKey
+        }
+
+    @staticmethod
+    def upsert(values: dict[str, Any]) -> None:
+        """
+        Merge submitted settings into the shared document without committing.
+        Only absent keys inherit application configuration; null stays explicit.
+        """
+        stored = ReportConfigDAO.get_stored_values()

Review Comment:
   `upsert` reads the stored document, merges the submitted keys in Python, then writes the whole value back with no lock or version check. Two admins saving different settings at the same time can both read the same snapshot, so the later write drops the earlier one while both requests return 200. For example, one saves `allowed_email_domains=["example.com"]` and the other saves only `date_format_in_email_subject`; if the second commits last, the allowlist silently disappears and delivery goes back to unrestricted. This is separate from the first-insert collision, since the row already exists here. Could the read-merge-write be serialized (e.g. `SELECT ... FOR UPDATE` on the row) or guarded by a compare-and-swap on the stored value?



##########
tests/unit_tests/commands/report/executor_test.py:
##########
@@ -0,0 +1,554 @@
+# 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.
+"""
+Execution-time behavior introduced by SIP-209: the per-schedule "Run As"
+executor, the runtime "attachments for alerts" setting and the recipient
+policy enforcement.
+"""
+
+from datetime import datetime
+from unittest.mock import Mock
+from uuid import uuid4
+
+import pytest
+from pytest_mock import MockerFixture
+
+from superset.commands.report.alert import AlertCommand
+from superset.commands.report.exceptions import (
+    ReportScheduleExecutorNotFoundError,
+    ReportScheduleRecipientsNotAllowedError,
+)
+from superset.commands.report.execute import (
+    alerts_attach_reports_enabled,
+    BaseReportState,
+    get_executor_user,
+    resolve_executor_user,
+)
+from superset.reports.models import ReportConfigKey, ReportSchedule
+from superset.tasks.exceptions import ExecutorNotFoundError
+
+
+def _user(username: str, active: bool = True) -> Mock:
+    user = Mock()
+    user.username = username
+    user.is_active = active
+    return user
+
+
+def test_get_executor_user_prefers_run_as_when_enabled(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    get_executor = mocker.patch("superset.commands.report.execute.get_executor")
+    run_as = _user("explicit")
+    model = ReportSchedule()
+    model.run_as = run_as
+    model.run_as_type = "fixed_user"
+    model.run_alert_query_as = None
+
+    assert get_executor_user(model) == (run_as, "explicit")
+    assert resolve_executor_user(model) == (run_as, "explicit")
+    get_executor.assert_not_called()
+
+
+def test_get_executor_user_inactive_run_as_is_reported(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    model = ReportSchedule()
+    model.run_as = _user("gone", active=False)
+    model.run_as_type = "fixed_user"
+    model.run_alert_query_as = None
+
+    assert get_executor_user(model) == (None, "gone")
+    with pytest.raises(ReportScheduleExecutorNotFoundError, match="gone"):
+        resolve_executor_user(model)
+
+
+def test_get_executor_user_falls_back_to_legacy_resolution(
+    mocker: MockerFixture,
+) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    mocker.patch(
+        "superset.commands.report.execute.get_executor",
+        return_value=("editor", "legacy"),
+    )
+    legacy = _user("legacy")
+    mocker.patch(
+        "superset.commands.report.execute.security_manager.find_user",
+        return_value=legacy,
+    )
+    model = ReportSchedule()
+    model.run_as = _user("stale")
+    model.run_as_type = None
+    model.run_alert_query_as = None
+
+    assert get_executor_user(model) == (legacy, "legacy")
+
+
+def test_missing_legacy_executor_has_no_username(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=False)
+    mocker.patch(
+        "superset.commands.report.execute.get_executor",
+        side_effect=ExecutorNotFoundError(),
+    )
+    model = ReportSchedule()
+
+    assert get_executor_user(model) == (None, None)
+    with pytest.raises(
+        ReportScheduleExecutorNotFoundError,
+        match="Scheduled task executor not found",
+    ):
+        resolve_executor_user(model)
+
+
+def test_get_executor_user_ignores_run_as_when_feature_disabled(
+    mocker: MockerFixture,
+) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=False)
+    mocker.patch(
+        "superset.commands.report.execute.get_executor",
+        return_value=("editor", "legacy"),
+    )
+    legacy = _user("legacy")
+    mocker.patch(
+        "superset.commands.report.execute.security_manager.find_user",
+        return_value=legacy,
+    )
+    model = ReportSchedule()
+    model.run_as = _user("explicit")
+
+    assert get_executor_user(model) == (legacy, "legacy")
+
+
+def test_alert_query_uses_alert_query_executor(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    get_executor = mocker.patch("superset.commands.report.alert.get_executor")
+    mocker.patch("superset.commands.report.alert.security_manager.raise_for_access")
+    override_user = mocker.patch("superset.commands.report.alert.override_user")
+    template_processor = Mock()
+    template_processor.process_template.return_value = "SELECT 1"
+    mocker.patch(
+        "superset.commands.report.alert.jinja_context.get_template_processor",
+        return_value=template_processor,
+    )
+    mocker.patch.object(AlertCommand, "_validate_rendered_sql")
+    mocker.patch.dict(
+        "flask.current_app.config", {"MUTATE_ALERT_QUERY": False}, clear=False
+    )
+
+    query_user = _user("query_user")
+    schedule = Mock(run_as_type="fixed_user", run_alert_query_as_type="fixed_user")
+    schedule.id = 1
+    schedule.sql = "SELECT 1"
+    schedule.run_as = _user("content_user")
+    schedule.run_alert_query_as = query_user
+    schedule.database.apply_limit_to_sql.return_value = "SELECT 1 LIMIT 2"
+
+    AlertCommand(schedule, uuid4())._execute_query()
+
+    override_user.assert_called_once_with(query_user)
+    get_executor.assert_not_called()
+
+
+def test_alert_query_inactive_executor_raises(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    template_processor = Mock()
+    template_processor.process_template.return_value = "SELECT 1"
+    mocker.patch(
+        "superset.commands.report.alert.jinja_context.get_template_processor",
+        return_value=template_processor,
+    )
+    mocker.patch.object(AlertCommand, "_validate_rendered_sql")
+    mocker.patch.dict(
+        "flask.current_app.config", {"MUTATE_ALERT_QUERY": False}, clear=False
+    )
+    schedule = Mock(run_as_type="fixed_user", run_alert_query_as_type=None)
+    schedule.id = 1
+    schedule.sql = "SELECT 1"
+    schedule.run_as = _user("gone", active=False)
+    schedule.run_alert_query_as = None
+
+    with pytest.raises(ReportScheduleExecutorNotFoundError, match="gone"):
+        AlertCommand(schedule, uuid4())._execute_query()
+
+
+@pytest.mark.parametrize(
+    ("stored", "flag", "expected"),
+    [
+        (None, True, True),
+        (None, False, False),
+        (True, False, True),
+        (False, True, False),
+    ],
+)
+def test_alerts_attach_reports_enabled(
+    mocker: MockerFixture, stored: bool | None, flag: bool, expected: bool
+) -> None:
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.get_effective_value",
+        return_value=stored if stored is not None else flag,
+    )
+    feature_flag_manager = mocker.patch(
+        "superset.commands.report.execute.feature_flag_manager"
+    )
+    feature_flag_manager.is_feature_enabled.return_value = flag
+
+    assert alerts_attach_reports_enabled() is expected
+
+
+def _policy(allowed_domains: list[str], limit_to_users: bool):
+    def effective(key: ReportConfigKey):
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return allowed_domains
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return limit_to_users
+        return None
+
+    return effective
+
+
+def test_send_refuses_disallowed_recipients(mocker: MockerFixture) -> None:
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.get_effective_value",
+        side_effect=_policy(["example.com"], False),
+    )
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.find_disallowed_addresses",
+        return_value=["x@other.org"],
+    )
+    schedule = Mock(spec=ReportSchedule)
+    schedule.recipients = []

Review Comment:
   This test sets `schedule.recipients = []` and forces `find_disallowed_addresses` to return `x@other.org`, so it never exercises how `_validate_recipients_policy` extracts addresses from the schedule. If that call were changed to pass `[]` instead of the schedule's recipients, this test would still pass, and a `bccTarget` outside the allowlist would be delivered. Could this use a real `ReportRecipients` config (e.g. `target="internal@example.com"`, `bccTarget="external@outside.org"`) with extraction and domain checking unstubbed, and assert that `ReportScheduleRecipientsNotAllowedError` names the external address before any content is generated?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213564858


##########
superset/commands/security/reset.py:
##########
@@ -62,7 +63,10 @@ def run(self) -> None:
             db.session.delete(database)
         db.session.query(Dashboard).delete()
         db.session.query(Slice).delete()
-        db.session.query(KeyValueEntry).delete()
+        config_uuid = FIXED_RESOURCE_KEYS[KeyValueResource.ALERT_REPORT_CONFIG]
+        db.session.query(KeyValueEntry).filter(
+            KeyValueEntry.uuid.is_(None) | (KeyValueEntry.uuid != config_uuid)
+        ).delete()

Review Comment:
   The `ENABLE_FACTORY_RESET_COMMAND` clears the `key_value` table. Updated the logic to preserve these configuration (as the command typically wouldn't impact them). 
   
   I included `KeyValueEntry.uuid.is_(None)` just because technically `UUID` is `nullable=False`, so in the event there are entries without a UUID value, it would be deleted before, so deleting it here for consistency.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202685386


##########
superset/commands/report/base.py:
##########
@@ -345,45 +393,118 @@ def validate_report_frequency(
         report_type: str,
     ) -> None:
         """
-        Validates if the report scheduled frequency doesn't exceed a limit
-        configured in `config.py`.
+        Validates if the report scheduled frequency doesn't exceed the minimum
+        interval in effect.
 
         :param cron_schedule: The cron schedule configured.
         :param report_type: The report type (Alert/Report).
         """
         config_key = (
-            "ALERT_MINIMUM_INTERVAL"
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL
             if report_type == ReportScheduleType.ALERT
-            else "REPORT_MINIMUM_INTERVAL"
+            else ReportConfigKey.REPORT_MINIMUM_INTERVAL
         )
-        minimum_interval = app.config.get(config_key, 0)
-        if callable(minimum_interval):
-            minimum_interval = minimum_interval()
+        minimum_interval = ReportConfigDAO.get_effective_value(config_key)
 
+        if minimum_interval is None:
+            return
         if not isinstance(minimum_interval, int):
             logger.error(
                 "Invalid value for %s: %s", config_key, minimum_interval, exc_info=True
             )
             return
 
-        # Since configuration is in minutes, we only need to validate
-        # in case `minimum_interval` is <= 120 (2min)
-        if minimum_interval < 120:
-            return
-
-        iterations = 60 if minimum_interval <= 3660 else 24
         try:
-            schedule = croniter(cron_schedule)
-            current_exec = next(schedule)
-
-            for _i in range(iterations):
-                next_exec = next(schedule)
-                diff, current_exec = next_exec - current_exec, next_exec
-                if int(diff) < minimum_interval:
-                    raise ReportScheduleFrequencyNotAllowed(
-                        report_type=report_type, minimum_interval=minimum_interval
-                    )
+            if not cron_meets_minimum_interval(cron_schedule, minimum_interval):
+                raise ReportScheduleFrequencyNotAllowed(
+                    report_type=report_type, minimum_interval=minimum_interval
+                )
         except CroniterBadDateError as ex:
             raise ReportScheduleCrontabNotValidError(
                 cron_schedule=cron_schedule
             ) from ex
+
+    def validate_report_format(
+        self,
+        report_type: str,
+        report_format: str | None,
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Reports always deliver content: the "no attachment" format is only
+        allowed on alerts.
+        """
+        if (
+            report_type == ReportScheduleType.REPORT
+            and report_format == ReportDataFormat.NONE
+        ):
+            exceptions.append(ReportScheduleFormatRequiredError())
+
+    def validate_recipients_policy(self, exceptions: list[ValidationError]) -> None:
+        """
+        Validate the e-mail recipients in the payload against the global
+        recipient policy (allowed domains and/or existing users only).
+        """
+        recipients = self._properties.get("recipients")
+        if not recipients:
+            return
+        disallowed = ReportConfigDAO.find_disallowed_addresses(
+            get_email_addresses(recipients)
+        )
+        if disallowed:
+            exceptions.append(ReportScheduleRecipientNotAllowedError(disallowed))
+
+    def validate_run_as(
+        self,
+        field_name: str,
+        user_id: int | None,
+        exceptions: list[ValidationError],
+        *,
+        default_to_current_user: bool,
+    ) -> User | None:
+        """Validate a specific user or an admin-selected application default.
+
+        A blank query executor inherits the content executor. A blank content
+        executor selected by an admin uses the legacy application configuration.
+        """
+        is_admin = security_manager.is_admin()
+        current_user = get_user()
+        type_field = f"{field_name}_type"
+        executor_type = self._properties.pop(type_field, None)
+        if executor_type is not None and executor_type != ExecutorType.FIXED_USER:
+            if not is_admin:
+                exceptions.append(ReportScheduleRunAsForbiddenError(field_name))
+                return None
+            exceptions.append(
+                ValidationError(
+                    _("Choose Application default or a specific user"),
+                    field_name=field_name,
+                )
+            )
+            return None
+
+        if user_id is None and executor_type != ExecutorType.FIXED_USER:
+            if field_name == "run_alert_query_as":

Review Comment:
   Another great catch! Fixing it



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4195397484


##########
superset/daos/report.py:
##########
@@ -392,3 +399,215 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def invalidate_pending_executions(schedule_ids: list[int] | None = None) -> None:
+        """Fence queued retries and running attempts after a configuration save.
+
+        The caller's transaction holds row locks only while saving metadata.
+        Preserve execution windows so old cron messages cannot replay the work.
+        """
+        query = db.session.query(ReportSchedule).filter(
+            ReportSchedule.last_state.in_([ReportState.WORKING, ReportState.RETRYING])
+        )
+        if schedule_ids is not None:
+            query = query.filter(ReportSchedule.id.in_(schedule_ids))
+        for schedule in query.populate_existing().with_for_update().all():
+            if schedule.execution_owner:
+                db.session.query(ReportExecutionLog).filter(
+                    ReportExecutionLog.report_schedule_id == schedule.id,
+                    ReportExecutionLog.uuid == UUID(schedule.execution_owner),
+                    ReportExecutionLog.state.in_(
+                        [ReportState.WORKING, ReportState.RETRYING]
+                    ),
+                ).update(
+                    {
+                        ReportExecutionLog.state: ReportState.ERROR,
+                        ReportExecutionLog.end_dttm: datetime.utcnow(),
+                        ReportExecutionLog.error_message: (
+                            "Execution cancelled: configuration changed"
+                        ),
+                    },
+                    synchronize_session=False,
+                )
+            schedule.execution_owner = str(uuid4())
+            schedule.last_state = ReportState.ERROR
+            schedule.last_eval_dttm = datetime.utcnow()
+            schedule.retry_attempt = 0
+            schedule.retry_scheduled_dttm = None
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) with at least one e-mail recipient.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .join(
+                ReportRecipients,
+                ReportRecipients.report_schedule_id == ReportSchedule.id,
+            )
+            .filter(ReportRecipients.type == ReportRecipientType.EMAIL)
+            .options(selectinload(ReportSchedule.recipients))
+            .distinct()
+            .all()
+        )
+
+    @staticmethod
+    def find_by_type(report_type: ReportScheduleType) -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) of the given type.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.type == report_type)
+            .all()
+        )
+
+
+class ReportConfigDAO:
+    """
+    Access to the global Alerts & Reports configuration (``report_config``).
+
+    Values are stored as JSON-encoded key-value rows. A key without a row is
+    "not configured" and resolves to the legacy application config or feature
+    flag through :meth:`get_effective_value`, which keeps deployments that never
+    open the configuration UI behaving exactly as before.
+    """
+
+    @staticmethod
+    def get_stored_values() -> dict[str, Any]:
+        """
+        Return the raw stored configuration, keyed by :class:`ReportConfigKey`.
+
+        Read and decoding failures propagate: unavailable policy is not an
+        unrestricted policy. A stored null remains distinct from a missing row.
+        """
+        rows = db.session.query(ReportConfig).all()
+        return {
+            row.key: json.loads(row.value) if row.value is not None else None
+            for row in rows
+        }
+
+    @staticmethod
+    def get_fallback_value(key: ReportConfigKey) -> Any:
+        """Return the legacy application config / feature flag value for ``key``."""
+        if key == ReportConfigKey.ALERTS_ATTACH_REPORTS:
+            return feature_flag_manager.is_feature_enabled("ALERTS_ATTACH_REPORTS")
+        if key == ReportConfigKey.DATE_FORMAT_IN_EMAIL_SUBJECT:
+            return feature_flag_manager.is_feature_enabled(
+                "DATE_FORMAT_IN_EMAIL_SUBJECT"
+            )
+        if key in (
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL,
+            ReportConfigKey.REPORT_MINIMUM_INTERVAL,
+        ):
+            value = current_app.config.get(key.upper(), 0)
+            return value() if callable(value) else value
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return False
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return []
+        return None
+
+    @staticmethod
+    def get_effective_value(key: ReportConfigKey) -> Any:
+        """
+        Return the value in effect for ``key``: the stored value when present,
+        otherwise the legacy fallback.
+        """
+        if key in (stored := ReportConfigDAO.get_stored_values()):
+            return stored[key]
+        return ReportConfigDAO.get_fallback_value(key)
+
+    @staticmethod
+    def get_effective_config() -> dict[str, Any]:
+        """Return the value in effect for every :class:`ReportConfigKey`."""
+        stored = ReportConfigDAO.get_stored_values()
+        return {
+            key.value: (
+                stored[key]
+                if key in stored
+                else ReportConfigDAO.get_fallback_value(key)
+            )
+            for key in ReportConfigKey
+        }
+
+    @staticmethod
+    def upsert(values: dict[str, Any]) -> None:
+        """
+        Store values, retaining an explicit null as a configured value.
+        Only keys without a row inherit application configuration. Does not commit.
+        """
+        rows = {row.key: row for row in db.session.query(ReportConfig).all()}
+        for key, value in values.items():
+            key = str(ReportConfigKey(key))
+            row = rows.get(key)
+            if row is None:
+                row = ReportConfig(key=key)
+                db.session.add(row)

Review Comment:
   I think that's OK. The unique `key` constraint should fail the second attempt, which can then be retried.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4203207742


##########
superset/reports/utils.py:
##########
@@ -0,0 +1,190 @@
+# 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.
+"""
+Helpers shared by the Alerts & Reports commands, DAO and execution engine.
+
+Recipient and interval helpers are shared by save-time and execution-time
+validation.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from typing import Any, TYPE_CHECKING
+
+from croniter import croniter
+
+from superset import is_feature_enabled
+from superset.commands.report.exceptions import ReportScheduleExecutorNotFoundError
+from superset.reports.models import ReportRecipientType
+from superset.tasks.types import ExecutorType
+from superset.utils import json
+
+if TYPE_CHECKING:
+    from flask_appbuilder.security.sqla.models import User
+
+    from superset.reports.models import ReportSchedule
+
+# Recipient fields inside ``recipient_config_json`` holding e-mail addresses.
+EMAIL_RECIPIENT_FIELDS = ("target", "ccTarget", "bccTarget")
+_EMAIL_SEPARATOR_RE = re.compile(r"[,;]")
+
+# Simple hostname validation for the allowed e-mail domains configuration.
+EMAIL_DOMAIN_REGEX = re.compile(
+    r"^(?!\*\..*\.\*$)(?:\*\.)?(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+"
+    r"(?:[a-zA-Z]{2,63}|\*)$"
+)
+
+
+def get_dynamic_executor(
+    report_schedule: ReportSchedule,
+    *,
+    alert_query: bool = False,
+) -> User | None:
+    """
+    Return the user explicitly configured to execute ``report_schedule``.
+
+    When ``alert_query`` is set, a typed query executor is preferred; an unset
+    query type inherits the content selection. An unset content type returns
+    ``None`` so callers use ``ALERT_REPORTS_EXECUTORS``. The type marker is
+    authoritative even if a stale user relationship is present.
+
+    The returned user may be inactive; callers decide how to surface that.
+    """
+    if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):
+        return None
+    field = "run_as"
+    if alert_query and report_schedule.run_alert_query_as_type is not None:
+        field = "run_alert_query_as"
+    executor_type = getattr(report_schedule, f"{field}_type")
+    if executor_type is None:
+        return None
+    if executor_type != ExecutorType.FIXED_USER:
+        raise ReportScheduleExecutorNotFoundError(str(executor_type))
+    user = getattr(report_schedule, field)
+    if user is None:
+        raise ReportScheduleExecutorNotFoundError("deleted user")
+    return user
+
+
+def split_email_addresses(value: str | None) -> list[str]:

Review Comment:
   Fixed



##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -418,6 +418,111 @@ ALERT_REPORTS_EXECUTORS = [FixedExecutor("admin")]
 
 Please refer to `ExecutorType` in the codebase for other executor types.
 
+#### Per-schedule "Run As" executor
+
+`ALERT_REPORTS_EXECUTORS` is a global, server-side setting that is invisible to the people
+configuring alerts and reports, which makes permission problems hard to diagnose and is
+especially painful for databases authenticated with OAuth2, where the impersonated account
+must hold a valid token. [SIP-209](https://github.com/apache/superset/issues/39642)
+introduces an explicit, per-schedule alternative behind the `ALERT_REPORT_DYNAMIC_EXECUTOR`
+[feature flag](/admin-docs/configuration/configuring-superset#feature-flags):
+
+```python
+FEATURE_FLAGS = {
+    "ALERT_REPORTS": True,
+    "ALERT_REPORT_DYNAMIC_EXECUTOR": True,
+}
+```
+
+When the flag is enabled:
+
+- Every alert/report gets a **Run as** field recording which user's RBAC permissions and
+  database credentials are used to render the content. Alerts get an additional
+  **Run alert query as** field for the alert condition SQL, so the audience of an alert
+  does not need direct database access.
+- Admins can select **Application default** or **Specific user**:
+  * **Application default:** resolves through `ALERT_REPORTS_EXECUTORS` value.
+  * **Specific user:** User picker option.
+  Non-admins can only select themselves. They see no user search and the API rejects
+  selecting another user. Reports scheduled from a dashboard or chart always execute
+  as the subscribing user.

Review Comment:
   good catch as well!



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4203210366


##########
superset/daos/report.py:
##########
@@ -392,3 +398,180 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:

Review Comment:
   done!



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4224336420


##########
superset/commands/report/execute.py:
##########
@@ -1542,7 +1597,8 @@ def _get_notification_content(self) -> NotificationContent:  # noqa: C901
                 )
 
         if (
-            self._report_schedule.chart
+            self._attachments_enabled()

Review Comment:
   Called this out in `UPDATING.md` now. Expected change Skip attachments means no data query, and just focus on the notification. Including the chart as a text would still fire a chart query that could affect the notification.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4189030557


##########
tests/unit_tests/commands/report/run_as_test.py:
##########
@@ -0,0 +1,750 @@
+# 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 the per-schedule "Run As" executor validation (SIP-209) in the
+create and update report schedule commands.
+"""
+
+from typing import Any
+from unittest.mock import Mock
+
+import pytest
+from marshmallow import ValidationError
+from pytest_mock import MockerFixture
+
+from superset.commands.report.create import CreateReportScheduleCommand
+from superset.commands.report.exceptions import (
+    ReportScheduleFormatRequiredError,
+    ReportScheduleInvalidError,
+    ReportScheduleRecipientNotAllowedError,
+    ReportScheduleRunAlertQueryAsNotAllowedError,
+    ReportScheduleRunAsContentForbiddenError,
+    ReportScheduleRunAsForbiddenError,
+    ReportScheduleRunAsNotFoundError,
+)
+from superset.commands.report.update import UpdateReportScheduleCommand
+from superset.reports.models import ReportDataFormat, ReportScheduleType
+
+CREATE = "superset.commands.report.create"
+UPDATE = "superset.commands.report.update"
+BASE = "superset.commands.report.base"
+
+
+def _user(user_id: int, active: bool = True) -> Mock:
+    user = Mock()
+    user.id = user_id
+    user.is_active = active
+    user.username = f"user{user_id}"
+    return user
+
+
+CURRENT_USER = _user(1)
+OTHER_USER = _user(2)
+USERS = {1: CURRENT_USER, 2: OTHER_USER, 3: _user(3, active=False)}
+
+
+def _stub_security(mocker: MockerFixture, *, is_admin: bool) -> Mock:
+    security_manager = Mock()
+    security_manager.is_admin.return_value = is_admin
+    security_manager.get_user_by_id.side_effect = lambda pk: USERS.get(pk)
+    mocker.patch(f"{BASE}.security_manager", security_manager)
+    mocker.patch(f"{BASE}.get_user", return_value=CURRENT_USER)
+    return security_manager
+
+
+def _errors(exc: pytest.ExceptionInfo[ReportScheduleInvalidError]) -> list[type]:
+    return [type(e) for e in exc.value._exceptions]
+
+
+# ---------------------------------------------------------------------------
+# Create
+# ---------------------------------------------------------------------------
+
+
+def _stub_create_deps(
+    mocker: MockerFixture, *, feature_enabled: bool, stub_policy: bool = True
+) -> None:
+    mocker.patch.object(CreateReportScheduleCommand, "_populate_recipients")
+    mocker.patch(
+        f"{CREATE}.ReportScheduleDAO.validate_update_uniqueness", return_value=True
+    )
+    mocker.patch(
+        f"{CREATE}.ReportScheduleDAO.validate_unique_creation_method",
+        return_value=True,
+    )
+    mocker.patch.object(CreateReportScheduleCommand, "validate_report_frequency")
+    mocker.patch.object(CreateReportScheduleCommand, "validate_chart_dashboard")
+    mocker.patch.object(CreateReportScheduleCommand, "_validate_report_extra")
+    if stub_policy:
+        mocker.patch.object(CreateReportScheduleCommand, "validate_recipients_policy")
+    mocker.patch(f"{CREATE}.populate_subjects")
+    mocker.patch(f"{CREATE}.is_feature_enabled", return_value=feature_enabled)
+
+
+def _create_command(**overrides: Any) -> CreateReportScheduleCommand:
+    command = CreateReportScheduleCommand({})
+    command._properties = {
+        "type": ReportScheduleType.REPORT,
+        "name": "Test",
+        "crontab": "0 9 * * *",
+        "creation_method": "alerts_reports",
+        **overrides,
+    }
+    return command
+
+
+def test_create_feature_disabled_drops_run_as_fields(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False)
+    security_manager = _stub_security(mocker, is_admin=True)
+
+    command = _create_command(run_as=2, run_alert_query_as=2)
+    command.validate()
+
+    assert "run_as" not in command._properties
+    assert "run_alert_query_as" not in command._properties
+    security_manager.get_user_by_id.assert_not_called()
+
+
+def test_create_defaults_run_as_to_current_user(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command()
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+    # Reports never carry an alert query executor.
+    assert "run_alert_query_as" not in command._properties
+
+
+def test_admin_can_create_with_application_default_executor(
+    mocker: MockerFixture,
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command(run_as=None, run_as_type=None)
+    command.validate()
+
+    assert command._properties["run_as"] is None
+    assert command._properties["run_as_type"] is None
+
+
+def test_create_alert_defaults_query_executor_to_run_as(
+    mocker: MockerFixture,
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+
+    command = _create_command(type=ReportScheduleType.ALERT, database=1, run_as=2)
+    command.validate()
+
+    assert command._properties["run_as"] is OTHER_USER
+    assert command._properties["run_alert_query_as"] is None
+
+
+def test_create_alert_with_distinct_query_executor(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+
+    command = _create_command(
+        type=ReportScheduleType.ALERT, database=1, run_as=1, run_alert_query_as=2
+    )
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+    assert command._properties["run_alert_query_as"] is OTHER_USER
+
+
+def test_create_non_admin_cannot_impersonate_another_user(
+    mocker: MockerFixture,
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=False)
+
+    command = _create_command(run_as=2)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_create_non_admin_may_set_themselves(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=False)
+
+    command = _create_command(run_as=1)
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+
+
+def test_create_rejects_missing_or_inactive_user(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    for user_id in (3, 999):
+        command = _create_command(run_as=user_id)
+        with pytest.raises(ReportScheduleInvalidError) as exc:
+            command.validate()
+        assert ReportScheduleRunAsNotFoundError in _errors(exc)
+
+
+def test_create_report_rejects_alert_query_executor(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command(run_alert_query_as=1)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAlertQueryAsNotAllowedError in _errors(exc)
+
+
+def test_create_report_rejects_no_attachment_format(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False)
+    _stub_security(mocker, is_admin=True)
+
+    command = _create_command(report_format=ReportDataFormat.NONE)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleFormatRequiredError in _errors(exc)
+
+
+def test_create_alert_allows_no_attachment_format(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+
+    command = _create_command(
+        type=ReportScheduleType.ALERT, database=1, report_format=ReportDataFormat.NONE
+    )
+    command.validate()
+
+
+def test_create_enforces_recipient_policy(mocker: MockerFixture) -> None:
+    _stub_create_deps(mocker, feature_enabled=False, stub_policy=False)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch(
+        f"{BASE}.ReportConfigDAO.find_disallowed_addresses",
+        return_value=["x@other.org"],
+    )
+
+    command = _create_command(
+        recipients=[
+            {
+                "type": "Email",
+                "recipient_config_json": {"target": "x@other.org"},
+            }
+        ]
+    )
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRecipientNotAllowedError in _errors(exc)
+
+
+# ---------------------------------------------------------------------------
+# Update
+# ---------------------------------------------------------------------------
+
+
+def _make_model(
+    *,
+    model_type: ReportScheduleType = ReportScheduleType.REPORT,
+    run_as: Mock | None = None,
+    run_alert_query_as: Mock | None = None,
+) -> Mock:
+    model = Mock()
+    model.type = model_type
+    model.database_id = 5 if model_type == ReportScheduleType.ALERT else None
+    model.creation_method = "alerts_reports"
+    model.name = "test_schedule"
+    model.crontab = "0 9 * * *"
+    model.last_state = "noop"
+    model.editors = []
+    model.retry_on_failure = False
+    model.send_failed_reports = False
+    model.chart_id = None
+    model.dashboard_id = 10
+    model.custom_width = None
+    model.extra_json = '{"dashboard": {"anchor": ""}}'
+    model.recipients = []
+    model.report_format = "PNG"
+    model.sql = None
+    model.validator_config_json = "{}"
+    model.validator_type = None
+    model.run_as_type = "fixed_user" if run_as else None
+    model.run_alert_query_as_type = "fixed_user" if run_alert_query_as else None
+    model.run_as = run_as
+    model.run_as_fk = run_as.id if run_as else None
+    model.run_alert_query_as = run_alert_query_as
+    model.run_alert_query_as_fk = run_alert_query_as.id if run_alert_query_as else None
+    return model
+
+
+def _stub_update_deps(
+    mocker: MockerFixture, model: Mock, *, is_admin: bool, feature_enabled: bool = True
+) -> None:
+    mocker.patch(f"{UPDATE}.ReportScheduleDAO.find_by_id", return_value=model)
+    mocker.patch(
+        f"{UPDATE}.ReportScheduleDAO.validate_update_uniqueness", return_value=True
+    )
+    mocker.patch(f"{UPDATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_chart_dashboard")
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_report_frequency")
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_alert_query")
+    mocker.patch.object(UpdateReportScheduleCommand, "_validate_report_extra")
+    mocker.patch.object(UpdateReportScheduleCommand, "validate_recipients_policy")
+    mocker.patch(f"{UPDATE}.compute_subjects")
+    mocker.patch(f"{UPDATE}.is_feature_enabled", return_value=feature_enabled)
+    mocker.patch(f"{UPDATE}.get_user_id", return_value=CURRENT_USER.id)
+    update_security_manager = Mock()
+    update_security_manager.is_admin.return_value = is_admin
+    mocker.patch(f"{UPDATE}.security_manager", update_security_manager)
+    _stub_security(mocker, is_admin=is_admin)
+
+
+def test_update_feature_disabled_drops_run_as_fields(mocker: MockerFixture) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=True, feature_enabled=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": 2, "run_alert_query_as": 2})
+    command.validate()
+
+    assert "run_as" not in command._properties
+    assert "run_alert_query_as" not in command._properties
+
+
+def test_update_admin_sets_and_clears_run_as(mocker: MockerFixture) -> None:
+    model = _make_model(run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": 2})
+    command.validate()
+    assert command._properties["run_as"] is OTHER_USER
+
+    # Explicit null reverts to the legacy ALERT_REPORTS_EXECUTORS resolution.
+    command = UpdateReportScheduleCommand(1, {"run_as": None})
+    command.validate()
+    assert command._properties["run_as"] is None
+    assert command._properties["run_as_type"] is None
+
+
+def test_update_non_admin_null_resolves_to_themselves(mocker: MockerFixture) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": None})
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+
+
+def test_update_non_admin_cannot_point_at_another_user(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_as": 2})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_update_non_admin_can_change_metadata_of_schedule_run_by_other(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    # Unchanged content fields sent back by the UI do not count as changes.
+    command = UpdateReportScheduleCommand(
+        1,
+        {
+            "active": False,
+            "name": "renamed",
+            "dashboard": 10,
+            "chart": None,
+            "report_format": "PNG",
+            "extra": {"dashboard": {"anchor": ""}},
+            "recipients": [],
+        },
+    )
+    command.validate()
+
+
+def test_update_non_admin_cannot_change_content_of_schedule_run_by_other(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"dashboard": 11})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAsContentForbiddenError in _errors(exc)
+
+
+def test_update_non_admin_can_change_content_after_taking_over(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"dashboard": 11, "run_as": 1})
+    command.validate()
+
+    assert command._properties["run_as"] is CURRENT_USER
+
+
+def test_update_admin_can_change_content_of_schedule_run_by_other(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    UpdateReportScheduleCommand(1, {"dashboard": 11}).validate()
+
+
+def test_update_report_clears_stale_alert_query_executor(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=CURRENT_USER, run_alert_query_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"name": "renamed"})
+    command.validate()
+
+    assert command._properties["run_alert_query_as"] is None
+
+
+def test_update_report_rejects_alert_query_executor(mocker: MockerFixture) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": 2})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleRunAlertQueryAsNotAllowedError in _errors(exc)
+
+
+def test_update_alert_query_executor_is_validated(mocker: MockerFixture) -> None:
+    model = _make_model(model_type=ReportScheduleType.ALERT, run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": 2})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": 1})
+    command.validate()
+    assert command._properties["run_alert_query_as"] is CURRENT_USER
+
+
+def test_update_report_rejects_no_attachment_format(mocker: MockerFixture) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=True)
+
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.NONE})
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+
+    assert ReportScheduleFormatRequiredError in _errors(exc)
+
+
+@pytest.mark.parametrize(
+    "executor_type",
+    ["creator", "creator_editor", "modifier", "modifier_editor", "editor"],
+)
+def test_admin_cannot_create_typed_executor(
+    mocker: MockerFixture, executor_type: str
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=True)
+    command = _create_command(run_as_type=executor_type)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ValidationError in _errors(exc)
+
+
+@pytest.mark.parametrize(
+    "executor_type",
+    ["creator", "creator_editor", "modifier", "modifier_editor", "editor"],
+)
+def test_non_admin_cannot_select_typed_executor(
+    mocker: MockerFixture, executor_type: str
+) -> None:
+    _stub_create_deps(mocker, feature_enabled=True)
+    _stub_security(mocker, is_admin=False)
+    command = _create_command(run_as_type=executor_type)
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_clear_content_executor_restores_application_default(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(run_as=OTHER_USER)
+    _stub_update_deps(mocker, model, is_admin=True)
+    command = UpdateReportScheduleCommand(1, {"run_as": None})
+    command.validate()
+    assert command._properties["run_as_type"] is None
+    assert command._properties["run_as"] is None
+
+
+def test_clear_query_executor_inherits_content(mocker: MockerFixture) -> None:
+    model = _make_model(
+        model_type=ReportScheduleType.ALERT,
+        run_as=OTHER_USER,
+        run_alert_query_as=CURRENT_USER,
+    )
+    _stub_update_deps(mocker, model, is_admin=True)
+    command = UpdateReportScheduleCommand(1, {"run_alert_query_as": None})
+    command.validate()
+    assert command._properties["run_alert_query_as"] is None
+    assert command._properties["run_alert_query_as_type"] is None
+
+
+@pytest.mark.parametrize("active", [False, True])
+def test_enabling_attachment_validates_existing_content_user(
+    active: bool, mocker: MockerFixture
+) -> None:
+    from superset.reports.models import ReportSchedule
+
+    mocker.patch(f"{UPDATE}.is_feature_enabled", return_value=True)
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.PNG})
+    command._model = ReportSchedule(
+        report_format=ReportDataFormat.NONE, run_as_type="fixed_user"
+    )
+    command._model.run_as = _user(2, active=active)
+    errors: list[ValidationError] = []
+    command._validate_attachment_executor(errors)
+    assert bool(errors) is not active
+    if errors:
+        assert isinstance(errors[0], ReportScheduleRunAsNotFoundError)
+
+
+def test_enabling_attachment_rejects_deleted_content_user(
+    mocker: MockerFixture,
+) -> None:
+    from superset.reports.models import ReportSchedule
+
+    mocker.patch(f"{UPDATE}.is_feature_enabled", return_value=True)
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.PNG})
+    command._model = ReportSchedule(
+        report_format=ReportDataFormat.NONE, run_as_type="fixed_user"
+    )
+    errors: list[ValidationError] = []
+    command._validate_attachment_executor(errors)
+    assert isinstance(errors[0], ReportScheduleRunAsNotFoundError)
+
+
+@pytest.mark.parametrize("field", ["run_as", "run_alert_query_as"])
+@pytest.mark.parametrize(
+    "selection",
+    [
+        "creator",
+        "creator_editor",
+        "modifier",
+        "modifier_editor",
+        "editor",
+        "other_user",
+    ],
+)
+def test_non_admin_update_cannot_choose_other_execution_identity(
+    field: str,
+    selection: str,
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(model_type=ReportScheduleType.ALERT, run_as=CURRENT_USER)
+    _stub_update_deps(mocker, model, is_admin=False)
+    command = UpdateReportScheduleCommand(
+        1,
+        {
+            field: OTHER_USER.id if selection == "other_user" else None,
+            f"{field}_type": "fixed_user" if selection == "other_user" else selection,
+        },
+    )
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        command.validate()
+    assert ReportScheduleRunAsForbiddenError in _errors(exc)
+
+
+def test_non_admin_takes_over_both_alert_executors_before_content_edit(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model(
+        model_type=ReportScheduleType.ALERT,
+        run_as=OTHER_USER,
+        run_alert_query_as=OTHER_USER,
+    )
+    _stub_update_deps(mocker, model, is_admin=False)
+    command = UpdateReportScheduleCommand(
+        1,
+        {
+            "dashboard": 11,
+            "run_as": CURRENT_USER.id,
+            "run_as_type": "fixed_user",
+            "run_alert_query_as": CURRENT_USER.id,
+            "run_alert_query_as_type": "fixed_user",
+        },
+    )
+    command.validate()
+    assert command._properties["run_as"] is CURRENT_USER
+    assert command._properties["run_alert_query_as"] is CURRENT_USER
+
+
+def test_non_admin_legacy_content_edits_require_explicit_self(
+    mocker: MockerFixture,
+) -> None:
+    model = _make_model()
+    _stub_update_deps(mocker, model, is_admin=False)
+    metadata = UpdateReportScheduleCommand(1, {"name": "renamed"})
+    metadata.validate()
+    assert "run_as" not in metadata._properties
+    with pytest.raises(ReportScheduleInvalidError) as exc:
+        UpdateReportScheduleCommand(1, {"dashboard": 11}).validate()
+    assert ReportScheduleRunAsContentForbiddenError in _errors(exc)
+    own = UpdateReportScheduleCommand(
+        1, {"dashboard": 11, "run_as": CURRENT_USER.id, "run_as_type": "fixed_user"}
+    )
+    own.validate()
+    assert own._properties["run_as"] is CURRENT_USER
+
+
+@pytest.mark.parametrize(
+    ("report_type", "report_format", "global_enabled", "requires_asset"),
+    [
+        (ReportScheduleType.ALERT, ReportDataFormat.NONE, True, False),
+        (ReportScheduleType.ALERT, ReportDataFormat.PNG, False, False),
+        (ReportScheduleType.ALERT, ReportDataFormat.PNG, True, True),
+        (ReportScheduleType.REPORT, ReportDataFormat.PNG, False, True),
+    ],
+)
+def test_create_attachment_asset_requirement(
+    report_type: str,
+    report_format: str,
+    global_enabled: bool,
+    requires_asset: bool,
+    mocker: MockerFixture,
+) -> None:
+    from superset.commands.report.base import BaseReportScheduleCommand
+    from superset.commands.report.exceptions import (
+        ReportScheduleEitherChartOrDashboardError,
+    )
+
+    _stub_create_deps(mocker, feature_enabled=False)
+    _stub_security(mocker, is_admin=True)
+    mocker.patch.object(
+        CreateReportScheduleCommand,
+        "validate_chart_dashboard",
+        BaseReportScheduleCommand.validate_chart_dashboard,
+    )
+    mocker.patch(
+        f"{BASE}.ReportConfigDAO.get_effective_value", return_value=global_enabled
+    )
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+    command = _create_command(type=report_type, report_format=report_format, database=1)
+    if requires_asset:
+        with pytest.raises(ReportScheduleInvalidError) as exc:
+            command.validate()
+        assert ReportScheduleEitherChartOrDashboardError in _errors(exc)
+    else:
+        command.validate()
+
+
+@pytest.mark.parametrize("include_asset", [False, True])
+def test_enabling_attachment_requires_asset_on_update(
+    include_asset: bool, mocker: MockerFixture
+) -> None:
+    from superset.commands.report.base import BaseReportScheduleCommand
+    from superset.commands.report.exceptions import (
+        ReportScheduleEitherChartOrDashboardError,
+    )
+
+    model = _make_model(model_type=ReportScheduleType.ALERT, run_as=CURRENT_USER)
+    model.report_format = ReportDataFormat.NONE
+    model.dashboard_id = 10 if include_asset else None
+    _stub_update_deps(mocker, model, is_admin=True)
+    mocker.patch.object(
+        UpdateReportScheduleCommand,
+        "validate_chart_dashboard",
+        BaseReportScheduleCommand.validate_chart_dashboard,
+    )
+    mocker.patch(f"{BASE}.ReportConfigDAO.get_effective_value", return_value=True)
+    command = UpdateReportScheduleCommand(1, {"report_format": ReportDataFormat.PNG})
+    if include_asset:
+        command.validate()
+    else:
+        with pytest.raises(ReportScheduleInvalidError) as exc:
+            command.validate()
+        assert ReportScheduleEitherChartOrDashboardError in _errors(exc)
+
+
+def test_attachment_free_alert_keeps_supplied_asset_and_validates_access(
+    mocker: MockerFixture,
+) -> None:
+    from superset.commands.report.base import BaseReportScheduleCommand
+    from superset.commands.report.exceptions import ReportScheduleForbiddenError
+    from superset.exceptions import SupersetSecurityException
+
+    _stub_create_deps(mocker, feature_enabled=False)
+    manager = _stub_security(mocker, is_admin=True)
+    mocker.patch.object(
+        CreateReportScheduleCommand,
+        "validate_chart_dashboard",
+        BaseReportScheduleCommand.validate_chart_dashboard,
+    )
+    dashboard = Mock()
+    mocker.patch(f"{BASE}.DashboardDAO.find_by_id", return_value=dashboard)
+    mocker.patch(f"{CREATE}.DatabaseDAO.find_by_id", return_value=Mock())
+    mocker.patch.object(CreateReportScheduleCommand, "validate_alert_query")
+    command = _create_command(
+        type=ReportScheduleType.ALERT,
+        database=1,
+        report_format=ReportDataFormat.NONE,
+        dashboard=10,
+    )
+    command.validate()
+    assert command._properties["dashboard"] is dashboard
+    assert command._properties["report_format"] == ReportDataFormat.NONE
+    manager.raise_for_access.assert_called_once_with(dashboard=dashboard)

Review Comment:
   **Suggestion:** For `report_format=NONE`, `requires_attachment()` is false and validation returns before resolving the dashboard or checking access, so this test fails at these assertions.
   
   **Assessment:** ๐ŸŸ  `Major` ยท ๐Ÿ” `Occurrence: Often` ยท ๐Ÿท๏ธ `Api mismatch`
   
   [![Use CodeAnt Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [![Fix in Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=a10fdde8a90445eea73a0ef17a2beb61&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [![Fix in VSCode Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=a10fdde8a90445eea73a0ef17a2beb61&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <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/run_as_test.py
   **Line:** 736:739
   **Comment:**
   	*Api Mismatch: For `report_format=NONE`, `requires_attachment()` is false and validation returns before resolving the dashboard or checking access, so this test fails at these assertions.
   
   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%2F44992&comment_hash=a524cf3deb17eaeffddadb61d43282679a4f6b22848e40745d5f1db9b948b8c4&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F44992&comment_hash=a524cf3deb17eaeffddadb61d43282679a4f6b22848e40745d5f1db9b948b8c4&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila merged PR #44992:
URL: https://github.com/apache/superset/pull/44992


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4222828924


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -985,10 +1072,63 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
       extra: contentType === ContentType.Dashboard ? currentAlert?.extra : {},
     };
 
+    if (!isReport && !attachmentControlsVisible && !isEditMode) {
+      data.report_format = 'NONE';
+    }
+    if (!attachmentControlsVisible && isEditMode) {
+      // Hidden settings stay stored; only the format controls attachment delivery.
+      delete data.chart;
+      delete data.dashboard;
+      delete data.extra;
+      delete data.custom_width;
+      delete data.force_screenshot;
+    }
+
     if (data.recipients && !data.recipients.length) {
       delete data.recipients;
     }
 
+    // Preserve existing identities unless an admin chooses or the user takes over.
+    delete data.run_as;
+    delete data.run_alert_query_as;
+    delete data.run_as_type;
+    delete data.run_alert_query_as_type;
+    if (dynamicExecutorEnabled && isAdmin) {
+      data.run_as_type = currentAlert?.run_as_type ?? null;

Review Comment:
   With the flag on, an admin editing an existing report always re-sends the stored `run_as`/`run_as_type` (and the query executor just below) even if nothing about the executor changed. `validate_run_as` then re-validates that user, so if the stored executor has since been deactivated, an admin who only renames the report or changes its schedule gets "User does not exist or is inactive" and can't save, while the same PUT without the executor fields would succeed. Could these fields be sent only when the admin actually changed the selection, so unrelated edits keep the stored value?



##########
tests/unit_tests/commands/report/executor_test.py:
##########
@@ -0,0 +1,613 @@
+# 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.
+"""
+Execution-time behavior introduced by SIP-209: the per-schedule "Run As"
+executor, the runtime "attachments for alerts" setting and the recipient
+policy enforcement.
+"""
+
+from datetime import datetime
+from unittest.mock import Mock
+from uuid import uuid4
+
+import pytest
+from pytest_mock import MockerFixture
+
+from superset.commands.report.alert import AlertCommand
+from superset.commands.report.exceptions import (
+    ReportScheduleExecutorNotFoundError,
+    ReportScheduleRecipientsNotAllowedError,
+)
+from superset.commands.report.execute import (
+    alerts_attach_reports_enabled,
+    BaseReportState,
+    get_executor_user,
+    resolve_executor_user,
+)
+from superset.reports.models import (
+    ReportConfigKey,
+    ReportRecipients,
+    ReportRecipientType,
+    ReportSchedule,
+)
+from superset.tasks.exceptions import ExecutorNotFoundError
+
+
+def _user(username: str, active: bool = True) -> Mock:
+    user = Mock()
+    user.username = username
+    user.is_active = active
+    return user
+
+
+def test_get_executor_user_prefers_run_as_when_enabled(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    get_executor = mocker.patch("superset.commands.report.execute.get_executor")
+    run_as = _user("explicit")
+    model = ReportSchedule()
+    model.run_as = run_as
+    model.run_as_type = "fixed_user"
+    model.run_alert_query_as = None
+
+    assert get_executor_user(model) == (run_as, "explicit")
+    assert resolve_executor_user(model) == (run_as, "explicit")
+    get_executor.assert_not_called()
+
+
+def test_get_executor_user_inactive_run_as_is_reported(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    model = ReportSchedule()
+    model.run_as = _user("gone", active=False)
+    model.run_as_type = "fixed_user"
+    model.run_alert_query_as = None
+
+    assert get_executor_user(model) == (None, "gone")
+    with pytest.raises(ReportScheduleExecutorNotFoundError, match="gone"):
+        resolve_executor_user(model)
+
+
+def test_get_executor_user_falls_back_to_legacy_resolution(
+    mocker: MockerFixture,
+) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    mocker.patch(
+        "superset.commands.report.execute.get_executor",
+        return_value=("editor", "legacy"),
+    )
+    legacy = _user("legacy")
+    mocker.patch(
+        "superset.commands.report.execute.security_manager.find_user",
+        return_value=legacy,
+    )
+    model = ReportSchedule()
+    model.run_as = _user("stale")
+    model.run_as_type = None
+    model.run_alert_query_as = None
+
+    assert get_executor_user(model) == (legacy, "legacy")
+
+
+def test_missing_legacy_executor_has_no_username(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=False)
+    mocker.patch(
+        "superset.commands.report.execute.get_executor",
+        side_effect=ExecutorNotFoundError(),
+    )
+    model = ReportSchedule()
+
+    assert get_executor_user(model) == (None, None)
+    with pytest.raises(
+        ReportScheduleExecutorNotFoundError,
+        match="Scheduled task executor not found",
+    ):
+        resolve_executor_user(model)
+
+
+def test_get_executor_user_ignores_run_as_when_feature_disabled(
+    mocker: MockerFixture,
+) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=False)
+    mocker.patch(
+        "superset.commands.report.execute.get_executor",
+        return_value=("editor", "legacy"),
+    )
+    legacy = _user("legacy")
+    mocker.patch(
+        "superset.commands.report.execute.security_manager.find_user",
+        return_value=legacy,
+    )
+    model = ReportSchedule()
+    model.run_as = _user("explicit")
+    model.run_as_type = "fixed_user"
+
+    assert get_executor_user(model) == (legacy, "legacy")
+
+
+def test_alert_query_uses_alert_query_executor(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    get_executor = mocker.patch("superset.commands.report.alert.get_executor")
+    mocker.patch("superset.commands.report.alert.security_manager.raise_for_access")
+    override_user = mocker.patch("superset.commands.report.alert.override_user")
+    template_processor = Mock()
+    template_processor.process_template.return_value = "SELECT 1"
+    mocker.patch(
+        "superset.commands.report.alert.jinja_context.get_template_processor",
+        return_value=template_processor,
+    )
+    mocker.patch.object(AlertCommand, "_validate_rendered_sql")
+    mocker.patch.dict(
+        "flask.current_app.config", {"MUTATE_ALERT_QUERY": False}, clear=False
+    )
+
+    query_user = _user("query_user")
+    schedule = Mock(run_as_type="fixed_user", run_alert_query_as_type="fixed_user")
+    schedule.id = 1
+    schedule.sql = "SELECT 1"
+    schedule.run_as = _user("content_user")
+    schedule.run_alert_query_as = query_user
+    schedule.database.apply_limit_to_sql.return_value = "SELECT 1 LIMIT 2"
+
+    AlertCommand(schedule, uuid4())._execute_query()
+
+    override_user.assert_called_once_with(query_user)
+    get_executor.assert_not_called()
+
+
+def test_alert_query_inactive_executor_raises(mocker: MockerFixture) -> None:
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    template_processor = Mock()
+    template_processor.process_template.return_value = "SELECT 1"
+    mocker.patch(
+        "superset.commands.report.alert.jinja_context.get_template_processor",
+        return_value=template_processor,
+    )
+    mocker.patch.object(AlertCommand, "_validate_rendered_sql")
+    mocker.patch.dict(
+        "flask.current_app.config", {"MUTATE_ALERT_QUERY": False}, clear=False
+    )
+    schedule = Mock(run_as_type="fixed_user", run_alert_query_as_type=None)
+    schedule.id = 1
+    schedule.sql = "SELECT 1"
+    schedule.run_as = _user("gone", active=False)
+    schedule.run_alert_query_as = None
+
+    with pytest.raises(ReportScheduleExecutorNotFoundError, match="gone"):
+        AlertCommand(schedule, uuid4())._execute_query()
+
+
+@pytest.mark.parametrize(
+    ("stored", "flag", "expected"),
+    [
+        (None, True, True),
+        (None, False, False),
+        (True, False, True),
+        (False, True, False),
+    ],
+)
+def test_alerts_attach_reports_enabled(
+    mocker: MockerFixture, stored: bool | None, flag: bool, expected: bool
+) -> None:
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.get_effective_value",
+        return_value=stored if stored is not None else flag,
+    )
+    feature_flag_manager = mocker.patch(
+        "superset.commands.report.execute.feature_flag_manager"
+    )
+    feature_flag_manager.is_feature_enabled.return_value = flag
+
+    assert alerts_attach_reports_enabled() is expected
+
+
+def _policy(allowed_domains: list[str], limit_to_users: bool):
+    def effective(key: ReportConfigKey):
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return allowed_domains
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return limit_to_users
+        return None
+
+    return effective
+
+
+def test_send_refuses_disallowed_recipients(mocker: MockerFixture) -> None:
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.get_effective_value",
+        side_effect=_policy(["example.com"], False),
+    )
+    schedule = Mock(spec=ReportSchedule)
+    schedule.recipients = [
+        ReportRecipients(
+            type=ReportRecipientType.EMAIL,
+            recipient_config_json=(
+                '{"target": "internal@example.com", '
+                '"bccTarget": "external@outside.org"}'
+            ),
+        )
+    ]
+    schedule.working_timeout = None
+    state = BaseReportState(schedule, datetime.utcnow(), uuid4())
+    get_content = mocker.patch.object(state, "_get_notification_content")
+    send = mocker.patch.object(state, "_send")
+
+    with pytest.raises(
+        ReportScheduleRecipientsNotAllowedError, match="external@outside.org"
+    ):
+        state.send()
+
+    get_content.assert_not_called()
+    send.assert_not_called()
+
+
+def test_send_skips_policy_when_unrestricted(mocker: MockerFixture) -> None:
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.get_effective_value",
+        side_effect=_policy([], False),
+    )
+    find_disallowed = mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.find_disallowed_addresses"
+    )
+    schedule = Mock(spec=ReportSchedule)
+    schedule.recipients = ["recipient"]
+    schedule.working_timeout = None
+    state = BaseReportState(schedule, datetime.utcnow(), uuid4())
+    content = Mock()
+    mocker.patch.object(state, "_get_notification_content", return_value=content)
+    send = mocker.patch.object(state, "_send")
+
+    state.send()
+
+    find_disallowed.assert_not_called()
+    send.assert_called_once_with(content, ["recipient"])
+
+
+@pytest.mark.parametrize("alert_query", [False, True])
+def test_deleted_specific_user_never_falls_back(
+    mocker: MockerFixture, alert_query: bool
+) -> None:
+    from superset.reports.utils import get_dynamic_executor
+
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    legacy = mocker.patch("superset.commands.report.execute.get_executor")
+    schedule = ReportSchedule(run_as_type="fixed_user")
+    with pytest.raises(ReportScheduleExecutorNotFoundError):
+        get_dynamic_executor(schedule, alert_query=alert_query)
+    assert get_executor_user(schedule)[0] is None
+    legacy.assert_not_called()
+
+
+def test_alert_template_and_database_share_query_identity(
+    mocker: MockerFixture,
+) -> None:
+    from flask import g
+
+    from superset.utils.core import get_user
+
+    content_user = _user("content")
+    query_user = _user("query")
+    mocker.patch.object(g, "user", content_user, create=True)
+    mocker.patch("superset.reports.utils.is_feature_enabled", return_value=True)
+    mocker.patch("superset.commands.report.alert.security_manager.raise_for_access")
+    mocker.patch.object(AlertCommand, "_validate_rendered_sql")
+    mocker.patch.dict("flask.current_app.config", {"MUTATE_ALERT_QUERY": True})
+    schedule = Mock(
+        run_as=content_user,
+        run_alert_query_as=query_user,
+        run_as_type="fixed_user",
+        run_alert_query_as_type="fixed_user",
+    )
+    schedule.sql = "SELECT '{{ current_username() }}'"
+
+    def render(sql: str) -> str:
+        assert get_user() is query_user
+        return "SELECT 'query'"
+
+    def processor(**kwargs: object) -> Mock:
+        assert get_user() is query_user
+        return Mock(process_template=render)
+
+    def mutate(sql: str) -> str:
+        assert get_user() is query_user
+        return sql
+
+    def query(**kwargs: object) -> Mock:
+        assert get_user() is query_user
+        return Mock()
+
+    mocker.patch(
+        "superset.commands.report.alert.jinja_context.get_template_processor",
+        side_effect=processor,
+    )
+    schedule.database.apply_limit_to_sql.side_effect = lambda sql, limit: sql
+    schedule.database.mutate_sql_based_on_config.side_effect = mutate
+    schedule.database.get_df.side_effect = query
+    AlertCommand(schedule, uuid4())._execute_query()
+    schedule.database.get_df.assert_called_once_with(sql="SELECT 'query'")
+    assert get_user() is content_user
+
+
+def test_retry_notices_skip_disallowed_recipients_but_notify_editors(
+    mocker: MockerFixture,
+) -> None:
+    from superset.subjects.types import SubjectType
+
+    schedule = Mock(spec=ReportSchedule)
+    schedule.working_timeout = None
+    schedule.retry_notify_owners = True
+    schedule.retry_notify_recipients = True
+    schedule.editors = [
+        Mock(type=SubjectType.USER, user=Mock(email="editor@outside.org"))
+    ]
+    schedule.recipients = [Mock()]
+    schedule.name = "Daily"
+    state = BaseReportState(schedule, datetime.utcnow(), uuid4())
+    mocker.patch.object(
+        state,
+        "_validate_recipients_policy",
+        side_effect=ReportScheduleRecipientsNotAllowedError(["recipient@outside.org"]),
+    )
+    mocker.patch.object(state, "_get_log_data", return_value={})
+    mocker.patch.object(state, "_get_url", return_value="https://example.com")
+    send = mocker.patch.object(state, "_send")
+    state.send_retry_notification(1, 3, "failed")
+    recipients = send.call_args.args[1]
+    assert len(recipients) == 1
+    assert "editor@outside.org" in recipients[0].recipient_config_json
+    send.reset_mock()
+    with pytest.raises(ReportScheduleRecipientsNotAllowedError):
+        state.send_final_failure_report("failed")
+    send.assert_not_called()
+
+
+def test_cleared_attachment_setting_does_not_restore_feature_flag(
+    mocker: MockerFixture,
+) -> None:
+    mocker.patch(
+        "superset.commands.report.execute.ReportConfigDAO.get_effective_value",
+        return_value=None,
+    )
+    assert alerts_attach_reports_enabled() is False
+
+
+@pytest.mark.parametrize(
+    "exception",
+    [
+        ReportScheduleExecutorNotFoundError("deleted"),
+        ReportScheduleRecipientsNotAllowedError(["blocked@example.com"]),
+    ],
+)
+def test_configuration_errors_never_retry(
+    exception: Exception, mocker: MockerFixture
+) -> None:
+    schedule = ReportSchedule(retry_on_failure=True, retry_attempt=2)
+    state = BaseReportState(schedule, datetime.now(), str(uuid4()))
+    reset = mocker.patch.object(state, "_reset_retry_counter")
+    assert state._handle_retry_or_error(str(exception), exception) is False

Review Comment:
   This test never enables `ALERT_REPORTS_RETRY`, whose default is off, so `_handle_retry_or_error` would also return False at the disabled-feature check. If the configuration-error early return were removed, this would still pass while a deleted executor or blocked recipient could start scheduling retries with the flag on. Could the test turn the flag on with remaining retry budget and also assert `_schedule_retry` is not called?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4224321313


##########
superset/daos/report.py:
##########
@@ -392,3 +404,187 @@ def bulk_delete_logs(model: ReportSchedule, from_date: datetime) -> int | None:
             )
             .delete(synchronize_session="fetch")
         )
+
+    @staticmethod
+    def find_with_email_recipients() -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) with at least one e-mail recipient.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .join(
+                ReportRecipients,
+                ReportRecipients.report_schedule_id == ReportSchedule.id,
+            )
+            .filter(ReportRecipients.type == ReportRecipientType.EMAIL)
+            .options(selectinload(ReportSchedule.recipients))
+            .distinct()
+            .all()
+        )
+
+    @staticmethod
+    def find_by_type(report_type: ReportScheduleType) -> list[ReportSchedule]:
+        """
+        Find every schedule (active or not) of the given type.
+        """
+        return (
+            db.session.query(ReportSchedule)
+            .filter(ReportSchedule.type == report_type)
+            .all()
+        )
+
+
+class ReportConfigDAO:
+    """
+    Access to the global Alerts & Reports configuration in ``key_value``.
+
+    One versioned document stores only settings explicitly saved by an admin.
+    Missing settings resolve to legacy application config or feature flag values.
+    """
+
+    VERSION: Literal[1] = 1
+
+    @staticmethod
+    def get_stored_values() -> dict[str, Any]:
+        """
+        Return explicitly saved settings from the versioned document.
+
+        A stored null is distinct from a missing setting key.
+        """
+        document: ReportConfigDocument | None = KeyValueDAO.get_value(
+            KeyValueResource.ALERT_REPORT_CONFIG,
+            FIXED_RESOURCE_KEYS[KeyValueResource.ALERT_REPORT_CONFIG],
+            JsonKeyValueCodec(),
+        )
+        if document is None:
+            return {}
+        return dict(document["settings"])
+
+    @staticmethod
+    def get_fallback_value(key: ReportConfigKey) -> Any:
+        """Return the legacy application config / feature flag value for ``key``."""
+        if key == ReportConfigKey.ALERTS_ATTACH_REPORTS:
+            return feature_flag_manager.is_feature_enabled("ALERTS_ATTACH_REPORTS")
+        if key == ReportConfigKey.DATE_FORMAT_IN_EMAIL_SUBJECT:
+            return feature_flag_manager.is_feature_enabled(
+                "DATE_FORMAT_IN_EMAIL_SUBJECT"
+            )
+        if key in (
+            ReportConfigKey.ALERT_MINIMUM_INTERVAL,
+            ReportConfigKey.REPORT_MINIMUM_INTERVAL,
+        ):
+            value = current_app.config.get(key.upper(), 0)
+            return value() if callable(value) else value
+        # These are new configs, no legacy fallback
+        if key == ReportConfigKey.LIMIT_RECIPIENTS_TO_USERS:
+            return False
+        if key == ReportConfigKey.ALLOWED_EMAIL_DOMAINS:
+            return []
+        return None
+
+    @staticmethod
+    def get_effective_value(key: ReportConfigKey) -> Any:
+        """
+        Return the value in effect for ``key``: the stored value when present,
+        otherwise the legacy fallback.
+        """
+        if key in (stored := ReportConfigDAO.get_stored_values()):
+            return stored[key]
+        return ReportConfigDAO.get_fallback_value(key)
+
+    @staticmethod
+    def get_effective_config() -> dict[str, Any]:
+        """Return the value in effect for every ``ReportConfigKey``."""
+        stored = ReportConfigDAO.get_stored_values()
+        return {
+            key.value: (
+                stored[key]
+                if key in stored
+                else ReportConfigDAO.get_fallback_value(key)
+            )
+            for key in ReportConfigKey
+        }
+
+    @staticmethod
+    def upsert(values: dict[str, Any]) -> None:
+        """
+        Merge submitted settings into the shared document without committing.
+        Only absent keys inherit application configuration; null stays explicit.
+        """
+        stored = ReportConfigDAO.get_stored_values()

Review Comment:
   ok, ended up pushing an update with a lock



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4209911335


##########
superset/commands/report/update.py:
##########
@@ -65,6 +131,194 @@ def run(self) -> Model:
         self.validate()
         return ReportScheduleDAO.update(self._model, self._properties)
 
+    def _compare_fields(
+        self,
+        keys: frozenset[str],
+        current: dict[str, Any],
+        normalizers: dict[str, Callable[[Any], Any]],
+    ) -> set[str]:
+        """
+        Return submitted fields whose normalized values differ from the stored values
+        """
+        changed: set[str] = set()
+        for field in keys & set(self._properties):
+            value = self._properties[field]
+            normalizer = normalizers.get(field)
+            if normalizer:
+                value = normalizer(value)
+            if value != current[field]:
+                changed.add(field)
+        return changed
+
+    def _changed_content_fields(self) -> set[str]:
+        """
+        Return the content fields whose payload value differs from the stored
+        one. Must run before other validators replace ids with model objects.
+        """
+        assert self._model is not None
+        model = self._model
+        current: dict[str, Any] = {
+            "chart": model.chart_id,
+            "dashboard": model.dashboard_id,
+            "extra": _normalize_json(model.extra_json),
+            "recipients": _normalize_recipients(model.recipients),
+            "report_format": model.report_format,
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "extra": _normalize_json,
+            "recipients": _normalize_recipients,
+        }
+        return self._compare_fields(CONTENT_FIELDS, current, normalizers)
+
+    def _changed_condition_fields(self) -> set[str]:
+        """Return alert-condition fields that differ from the stored values."""
+        assert self._model is not None
+        current = {
+            "database": self._model.database_id,
+            "sql": self._model.sql,
+            "validator_type": self._model.validator_type,
+            "validator_config_json": _normalize_json(self._model.validator_config_json),
+        }
+        normalizers: dict[str, Callable[[Any], Any]] = {
+            "validator_config_json": _normalize_json,
+        }
+        return self._compare_fields(ALERT_CONDITION_FIELDS, current, normalizers)
+
+    def _validate_executors(
+        self,
+        report_type: str,
+        changed_content_fields: set[str],
+        changed_condition_fields: set[str],
+        exceptions: list[ValidationError],
+    ) -> None:
+        """
+        Resolve the "Run As" fields (SIP-209) on update.
+
+        Fields absent from the payload keep their stored value. Admins may set
+        any active user or explicit executor type. Clearing content restores the
+        legacy application-configured executor;
+        clearing the query executor inherits the content identity.
+        Non-admins may only point the fields at themselves and, when the schedule
+        executes as another user,
+        may not change its content or recipients: doing so would let an editor
+        read data with someone else's credentials.
+        """
+        assert self._model is not None
+        has_run_as = bool({"run_as", "run_as_type"} & self._properties.keys())
+        has_query_as = bool(
+            {"run_alert_query_as", "run_alert_query_as_type"} & self._properties.keys()
+        )
+        run_as_id = self._properties.pop("run_as", None)
+        query_as_id = self._properties.pop("run_alert_query_as", None)
+        if not is_feature_enabled("ALERT_REPORT_DYNAMIC_EXECUTOR"):
+            self._properties.pop("run_as_type", None)
+            self._properties.pop("run_alert_query_as_type", None)
+            return
+
+        run_as = (
+            self.validate_run_as(
+                "run_as", run_as_id, exceptions, default_to_current_user=False
+            )
+            if has_run_as
+            else self._model.run_as
+        )
+
+        query_as = None
+        if report_type == ReportScheduleType.REPORT:
+            if has_query_as and (
+                query_as_id is not None
+                or self._properties.get("run_alert_query_as_type") is not None
+            ):
+                exceptions.append(ReportScheduleRunAlertQueryAsNotAllowedError())
+            else:
+                self._properties["run_alert_query_as"] = None
+                self._properties["run_alert_query_as_type"] = None
+        elif has_query_as:
+            query_as = self.validate_run_as(
+                "run_alert_query_as",
+                query_as_id,
+                exceptions,
+                default_to_current_user=False,
+            )
+        else:
+            query_as = self._model.run_alert_query_as
+
+        if security_manager.is_admin():
+            return
+        current_user_id = get_user_id()
+        executes_as_other_user = any(
+            user is not None and user.id != current_user_id
+            for user in (run_as, query_as)
+        )
+        typed_executor = any(
+            self._properties.get(field, getattr(self._model, field))
+            not in (None, ExecutorType.FIXED_USER)
+            for field in ("run_as_type", "run_alert_query_as_type")
+        )
+        content_type = self._properties.get("run_as_type", self._model.run_as_type)
+        unresolved_executor = (
+            content_type is None
+            or (content_type == ExecutorType.FIXED_USER and run_as is None)
+            or (
+                report_type == ReportScheduleType.ALERT
+                and query_as is None
+                and self._properties.get(
+                    "run_alert_query_as_type", self._model.run_alert_query_as_type
+                )
+                == ExecutorType.FIXED_USER
+            )
+        )
+        if (
+            executes_as_other_user or typed_executor or unresolved_executor
+        ) and changed_content_fields:
+            exceptions.append(ReportScheduleRunAsContentForbiddenError())
+

Review Comment:
   Ok, ended up re-adding `report_format` to the `CONTENT_FIELDS`. It actually allows some sort of content change in 2 scenarios:
   * Changing an Alert from `ReportFormat.NONE` to anything else would now include an attachment; 
   * Updating the `report_format` for a table chart with server-side pagination enabled to CSV could expose additional data. 
   
   Added logic to cover this flow through the subscription modal as well for feature parity.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "villebro (via GitHub)" <gi...@apache.org>.
villebro commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4210166275


##########
superset/migrations/versions/2026-10-05_12-00_e4a7c2b9d1f3_add_run_as_and_report_config.py:
##########
@@ -0,0 +1,135 @@
+# 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.
+"""Add Run As columns to report_schedule and create the report_config table
+
+Part of SIP-209 (Improved Alerts & Reports).
+
+``report_schedule.run_as_fk`` and ``report_schedule.run_alert_query_as_fk`` are
+nullable foreign keys to ``ab_user``. They are intentionally left NULL so the
+existing ``ALERT_REPORTS_EXECUTORS`` resolution keeps being used until a value
+is set.
+
+``report_config`` is a key-value table holding the global Alerts & Reports
+configuration (attachments for alerts, minimum intervals and recipient
+restrictions). It starts empty: every setting falls back to the corresponding
+application config or feature flag until an admin saves a value.
+
+Revision ID: e4a7c2b9d1f3
+Revises: 00fab727cd0a
+Create Date: 2026-10-05 12:00:00.000000
+
+"""
+
+from sqlalchemy import Column, DateTime, Integer, String, Text
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_fks_for_table,
+    create_table,
+    drop_columns,
+    drop_fks_for_table,
+    drop_table,
+    table_has_column,
+)
+
+# revision identifiers, used by Alembic.
+revision = "e4a7c2b9d1f3"
+down_revision = "00fab727cd0a"
+
+REPORT_SCHEDULE_TABLE = "report_schedule"
+REPORT_CONFIG_TABLE = "report_config"
+
+RUN_AS_FK_NAME = "fk_report_schedule_run_as_fk_ab_user"
+RUN_ALERT_QUERY_AS_FK_NAME = "fk_report_schedule_run_alert_query_as_fk_ab_user"
+
+
+def upgrade() -> None:
+    add_columns(
+        REPORT_SCHEDULE_TABLE,
+        Column("run_as_fk", Integer, nullable=True),
+        Column("run_alert_query_as_fk", Integer, nullable=True),
+        # When an account is deleted, ``run_as_fk`` gets cleared. Without
+        # ``run_alert_query_as_fk``, this would automatically change the
+        # schedule to fallback to ``ALERT_REPORTS_EXECUTORS``.
+        Column("run_as_type", String(50), nullable=True),
+        # Similarly, ``run_alert_query_as_type`` is used to replicate
+        # ``run_as_fk`` into ``run_alert_query_as_fk``.
+        Column("run_alert_query_as_type", String(50), nullable=True),
+    )
+    create_fks_for_table(
+        foreign_key_name=RUN_AS_FK_NAME,
+        table_name=REPORT_SCHEDULE_TABLE,
+        referenced_table="ab_user",
+        local_cols=["run_as_fk"],
+        remote_cols=["id"],
+        ondelete="SET NULL",
+    )
+    create_fks_for_table(
+        foreign_key_name=RUN_ALERT_QUERY_AS_FK_NAME,
+        table_name=REPORT_SCHEDULE_TABLE,
+        referenced_table="ab_user",
+        local_cols=["run_alert_query_as_fk"],
+        remote_cols=["id"],
+        ondelete="SET NULL",
+    )
+
+    create_table(
+        REPORT_CONFIG_TABLE,
+        Column("id", UUIDType(binary=True), primary_key=True),
+        Column("key", String(255), nullable=False, unique=True),
+        Column("value", Text, nullable=True),
+        Column("created_on", DateTime, nullable=True),
+        Column("changed_on", DateTime, nullable=True),
+        Column("created_by_fk", Integer, nullable=True),
+        Column("changed_by_fk", Integer, nullable=True),
+    )

Review Comment:
   I still feel we should make these types of configs generic. I understand it requires an extra upfront push, but once it's done, it will make it much easier for other features to introduce similar configs without having to bloat the metastore with yet another reinvented config table.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202645786


##########
superset/commands/report/update.py:
##########
@@ -42,17 +47,61 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(

Review Comment:
   Updated logic to cover this.



##########
superset/commands/report/update.py:
##########
@@ -42,17 +47,61 @@
 from superset.exceptions import SupersetSecurityException
 from superset.reports.models import (
     ReportCreationMethod,
+    ReportDataFormat,
     ReportRecipientType,
     ReportSchedule,
     ReportScheduleType,
     ReportState,
 )
+from superset.tasks.exceptions import ExecutorNotFoundError
+from superset.tasks.types import ExecutorType
+from superset.tasks.utils import get_executor
 from superset.utils import json
-from superset.utils.core import get_user_email
+from superset.utils.core import get_user, get_user_email, get_user_id
 from superset.utils.decorators import on_error, transaction
 
 logger = logging.getLogger(__name__)
 
+# Payload fields that change the delivered asset, its rendering, or its recipients.
+# When a schedule executes as another user, only admins may change these.
+CONTENT_FIELDS: frozenset[str] = frozenset(
+    {
+        "chart",
+        "dashboard",
+        "extra",
+        "recipients",
+        "report_format",
+    }
+)
+
+
+def _normalize_json(value: Any) -> str:
+    """Canonical JSON string for a dict/JSON-string value (for comparisons)."""
+    if isinstance(value, str):
+        try:
+            value = json.loads(value)
+        except json.JSONDecodeError:
+            return value
+    if value is None:
+        value = {}
+    if not isinstance(value, (dict, list)):
+        return str(value)
+    return json.dumps(value, sort_keys=True)
+
+
+def _normalize_recipients(recipients: Any) -> list[tuple[str, str]]:
+    """Canonical, order-independent representation of a recipients list."""
+    normalized: list[tuple[str, str]] = []
+    for recipient in recipients or []:
+        if isinstance(recipient, dict):
+            recipient_type = recipient.get("type")
+            config = recipient.get("recipient_config_json")
+        else:
+            recipient_type = recipient.type
+            config = recipient.recipient_config_json
+        normalized.append((str(recipient_type), _normalize_json(config)))

Review Comment:
   Great catch as well. Improved this flow.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4199928434


##########
docs/admin_docs/configuration/alerts-reports.mdx:
##########
@@ -418,6 +418,108 @@ ALERT_REPORTS_EXECUTORS = [FixedExecutor("admin")]
 
 Please refer to `ExecutorType` in the codebase for other executor types.
 
+#### Per-schedule "Run As" executor
+
+`ALERT_REPORTS_EXECUTORS` is a global, server-side setting that is invisible to the people
+configuring alerts and reports, which makes permission problems hard to diagnose and is
+especially painful for databases authenticated with OAuth2, where the impersonated account
+must hold a valid token. [SIP-209](https://github.com/apache/superset/issues/39642)
+introduces an explicit, per-schedule alternative behind the `ALERT_REPORT_DYNAMIC_EXECUTOR`
+[feature flag](/admin-docs/configuration/configuring-superset#feature-flags):
+
+```python
+FEATURE_FLAGS = {
+    "ALERT_REPORTS": True,
+    "ALERT_REPORT_DYNAMIC_EXECUTOR": True,
+}
+```
+
+When the flag is enabled:
+
+- Every alert/report gets a **Run as** field recording which user's RBAC permissions and
+  database credentials are used to render the content. Alerts get an additional
+  **Run alert query as** field for the alert condition SQL, so the audience of an alert
+  does not need direct database access.
+- Admins can select **Application default** or **Specific user**:
+  * **Application default:** resolves through `ALERT_REPORTS_EXECUTORS` value.
+  * **Specific user:** User picker option.
+  Non-admins can only select themselves. They see no user search and the API rejects
+  selecting another user. Reports scheduled from a dashboard or chart always execute
+  as the subscribing user.
+- When a non-admin edits an alert/report configured to run as someone else, they can
+  change its metadata, type, and condition (database, SQL, and validator), but not its
+  selected chart/dashboard, filters, attachment format, or recipients. To change those,
+  they must first set **Run as** to their own account via the **Execute using my permissions**
+  button (or ask an admin). For alerts, this action selects the current user for both content
+  and SQL condition execution. Legacy schedules without an explicit ``run_as`` user also
+  require this switch before a non-admin changes the delivered asset or recipients.
+- Untouched legacy schedules continue using `ALERT_REPORTS_EXECUTORS`. **Application
+  default** preserves this behavior in the Run as selector, including when an admin
+  clears an explicit executor.
+- A selected user that is deleted remains recorded as a **Specific user** selection.
+  Resolving a deleted or inactive user fails rather than switching to a legacy executor.
+  Alert SQL templates, SQL mutation hooks, authorization and database access all use
+  the query executor's identity.
+
+It's possible to set a custom "Run As" tooltip value via the `ALERT_REPORTS_RUN_AS_TOOLTIP`
+config in `superset_config.py`. This is useful if you want to provide further context on what
+the "Application default" means. **It does not change the feature behavior**.
+`ALERT_REPORTS_EXECUTORS` is deprecated in favor of this field and will be removed once the
+feature graduates from the flag.
+
+### Alerts & Reports configuration
+
+Admins can manage the global Alerts & Reports settings at runtime from the **Configuration**
+button on the Alerts & Reports list page (also available through
+`GET`/`PUT /api/v1/report/configuration/`). Values are stored in the `report_config` table;
+a setting that was never saved falls back to the corresponding `superset_config.py` value or
+feature flag.
+
+| Setting | Fallback | Description |
+| --- | --- | --- |
+| Enable attachments for alerts | `ALERTS_ATTACH_REPORTS` FF | Whether alerts deliver their attachment. Applies to subsequent attempts; saving a change cancels pending attempts. |

Review Comment:
   Oh, totally. I had some logic to drop retries but ended up removing because it would be inconsistent with other changes. Will fix this in a new commit and resolve this one. Great catch!



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4202848505


##########
superset/commands/report/alert.py:
##########
@@ -214,37 +216,41 @@ def _execute_query(self) -> pd.DataFrame:
         :raises AlertQueryError: SQL query is not valid
         :raises AlertQueryTimeout: The SQL query received a celery soft timeout
         """
-        sql_template = jinja_context.get_template_processor(
-            database=self._report_schedule.database
-        )
-
         try:
-            rendered_sql = sql_template.process_template(self._report_schedule.sql)
-            self._validate_rendered_sql(rendered_sql)
-            limited_rendered_sql = self._report_schedule.database.apply_limit_to_sql(
-                rendered_sql, ALERT_SQL_LIMIT
-            )
-
-            if app.config["MUTATE_ALERT_QUERY"]:
-                limited_rendered_sql = (
-                    self._report_schedule.database.mutate_sql_based_on_config(
-                        limited_rendered_sql
-                    )
+            user = get_dynamic_executor(self._report_schedule, alert_query=True)
+            if user is not None:
+                username = user.username
+            else:
+                executor, username = get_executor(  # pylint: disable=unused-variable
+                    executors=app.config["ALERT_REPORTS_EXECUTORS"],
+                    model=self._report_schedule,
                 )
-
-            executor, username = get_executor(  # pylint: disable=unused-variable
-                executors=app.config["ALERT_REPORTS_EXECUTORS"],
-                model=self._report_schedule,
-            )
-            user = security_manager.find_user(username)
+                user = security_manager.find_user(username)
             # A deleted/disabled executor user makes find_user return None. Raise
             # the dedicated error so the handler below re-surfaces it instead of
             # masking it as an opaque AlertQueryError (or letting the missing user
             # surface as a NoneType error from the downstream auth flow).
-            if user is None:
+            if user is None or not user.is_active:
                 raise ReportScheduleExecutorNotFoundError(username)
 
             with override_user(user):

Review Comment:
   hmmmm this one is a bit tricky, @sadpandajoe. Added the `try/finally` in `core.py` directly, let me know your thoughts (could affect other parts. of the app).



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4213587598


##########
superset/migrations/versions/2026-10-05_12-00_e4a7c2b9d1f3_add_run_as_and_report_config.py:
##########
@@ -0,0 +1,135 @@
+# 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.
+"""Add Run As columns to report_schedule and create the report_config table
+
+Part of SIP-209 (Improved Alerts & Reports).
+
+``report_schedule.run_as_fk`` and ``report_schedule.run_alert_query_as_fk`` are
+nullable foreign keys to ``ab_user``. They are intentionally left NULL so the
+existing ``ALERT_REPORTS_EXECUTORS`` resolution keeps being used until a value
+is set.
+
+``report_config`` is a key-value table holding the global Alerts & Reports
+configuration (attachments for alerts, minimum intervals and recipient
+restrictions). It starts empty: every setting falls back to the corresponding
+application config or feature flag until an admin saves a value.
+
+Revision ID: e4a7c2b9d1f3
+Revises: 00fab727cd0a
+Create Date: 2026-10-05 12:00:00.000000
+
+"""
+
+from sqlalchemy import Column, DateTime, Integer, String, Text
+from sqlalchemy_utils import UUIDType
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_fks_for_table,
+    create_table,
+    drop_columns,
+    drop_fks_for_table,
+    drop_table,
+    table_has_column,
+)
+
+# revision identifiers, used by Alembic.
+revision = "e4a7c2b9d1f3"
+down_revision = "00fab727cd0a"
+
+REPORT_SCHEDULE_TABLE = "report_schedule"
+REPORT_CONFIG_TABLE = "report_config"
+
+RUN_AS_FK_NAME = "fk_report_schedule_run_as_fk_ab_user"
+RUN_ALERT_QUERY_AS_FK_NAME = "fk_report_schedule_run_alert_query_as_fk_ab_user"
+
+
+def upgrade() -> None:
+    add_columns(
+        REPORT_SCHEDULE_TABLE,
+        Column("run_as_fk", Integer, nullable=True),
+        Column("run_alert_query_as_fk", Integer, nullable=True),
+        # When an account is deleted, ``run_as_fk`` gets cleared. Without
+        # ``run_alert_query_as_fk``, this would automatically change the
+        # schedule to fallback to ``ALERT_REPORTS_EXECUTORS``.
+        Column("run_as_type", String(50), nullable=True),
+        # Similarly, ``run_alert_query_as_type`` is used to replicate
+        # ``run_as_fk`` into ``run_alert_query_as_fk``.
+        Column("run_alert_query_as_type", String(50), nullable=True),
+    )
+    create_fks_for_table(
+        foreign_key_name=RUN_AS_FK_NAME,
+        table_name=REPORT_SCHEDULE_TABLE,
+        referenced_table="ab_user",
+        local_cols=["run_as_fk"],
+        remote_cols=["id"],
+        ondelete="SET NULL",
+    )
+    create_fks_for_table(
+        foreign_key_name=RUN_ALERT_QUERY_AS_FK_NAME,
+        table_name=REPORT_SCHEDULE_TABLE,
+        referenced_table="ab_user",
+        local_cols=["run_alert_query_as_fk"],
+        remote_cols=["id"],
+        ondelete="SET NULL",
+    )
+
+    create_table(
+        REPORT_CONFIG_TABLE,
+        Column("id", UUIDType(binary=True), primary_key=True),
+        Column("key", String(255), nullable=False, unique=True),
+        Column("value", Text, nullable=True),
+        Column("created_on", DateTime, nullable=True),
+        Column("changed_on", DateTime, nullable=True),
+        Column("created_by_fk", Integer, nullable=True),
+        Column("changed_by_fk", Integer, nullable=True),
+    )

Review Comment:
   Ended up leveraging `key_value`.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: SIP-209 Improved Alerts & Reports [superset]

Posted by "Vitor-Avila (via GitHub)" <gi...@apache.org>.
Vitor-Avila commented on code in PR #44992:
URL: https://github.com/apache/superset/pull/44992#discussion_r4207498574


##########
superset-frontend/src/features/alerts/AlertReportModal.tsx:
##########
@@ -2327,310 +2613,461 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
               ),
               children: (
                 <>
-                  <StyledInputContainer>
-                    <div className="control-label">
-                      {t('Content type')}
-                      <span className="required">*</span>
-                    </div>
-                    <Select
-                      ariaLabel={t('Select content type')}
-                      onChange={onContentTypeChange}
-                      value={contentType}
-                      options={CONTENT_TYPE_OPTIONS}
-                      placeholder={t('Select content type')}
+                  {dynamicExecutorEnabled && !isAdmin && (
+                    <Alert
+                      type={restrictedExecutor ? 'warning' : 'info'}
+                      showIcon
+                      message={
+                        restrictedExecutor
+                          ? t('Content and recipient edits are restricted')
+                          : t('Content and permissions')
+                      }
+                      description={
+                        restrictedExecutor ? (
+                          <>
+                            <p>
+                              {t(
+                                isReport
+                                  ? 'You can edit the name and schedule, but changing the delivered content or recipients requires updating it to execute with your permissions. Only admins can select other users.'

Review Comment:
   Fixed



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org