Skip to content

fix(reports): enable alert retries with execution safeguards - #44336

Merged
EnxDev merged 12 commits into
apache:masterfrom
fitzee:fitzee/report-retry-parity
Sep 21, 2026
Merged

EnxDev merged 12 commits into
apache:masterfrom
fitzee:fitzee/report-retry-parity

Conversation

@fitzee

@fitzee fitzee commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR

Enable whole-execution retries for alerts, and protect alert/report execution against duplicate or obsolete attempts. Additional screenshot validation and detection-policy changes have been removed from this PR and moved to #44465. Master's existing rendering and capture-rejection checks remain unchanged. Both PRs target master independently.

SUMMARY

This builds on the merged retry foundation (#42481 and #43553). Alerts gain retry configuration in the API and UI. Each retry re-evaluates the condition; if it no longer fires, it completes without notifying recipients.

An atomic execution claim and owner token prevent duplicate or superseded attempts from proceeding. Alert and report failures can leave the claimed WORKING state safely. Ownership is checked in a short committed transaction before each recipient; no schedule-row lock is held across transport I/O. Whole-execution retries stop once delivery starts, since a failed send may already have been accepted. Retry exhaustion avoids duplicate notices. Recipient-facing failure notifications omit provider diagnostics; ordinary editor-only error emails retain HTML-sanitized diagnostic text.

Disabling retries terminalizes a matching queued retry using an owner/window-guarded update, without letting stale messages cancel newer work. Stale retry admission uses the same maximum-delay threshold as recovery. Alerts retain their per-schedule Celery timeout rather than the global report deadline. Rendered alert attachments get a separate finite browser budget, capped by remaining alert time, while sharing sticky rejection state. Data-only alerts retain their existing lenient query-context bootstrap capture contract.

The larger diff includes concurrency, migration, notification and state-machine regression tests. These safeguards belong with alert retry support; final-image validation, PDF provenance, classifier changes and capture diagnostics do not and are excluded.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Alerts gain the existing Error handling / Enable Retries panel, previously restricted to reports. No other UI redesign.

TESTING INSTRUCTIONS

  • Latest review fixes: 692 unit tests passed across report commands, notifications, scheduler timeout handling and execution contexts, including real PostgreSQL ownership tests.
  • Latest review fixes: 146 PostgreSQL report/dashboard integration tests passed.
  • All changed-file pre-commit hooks passed, including frontend type checks, mypy, Ruff and pylint.
  • Previously verified on this branch before the capture-only split: 99 alert/report modal tests, SQLite migration upgrade/downgrade/re-upgrade, and full PostgreSQL migration upgrade. The split does not change the UI or migration.
  • Earlier validation also covered 770 backend unit tests and 170 PostgreSQL report/scheduler/ownership integration tests; the latest targeted run above is the evidence for these review fixes.

Manual canary: upgrade the metadata DB, enable ALERT_REPORTS_RETRY, and opt an alert and report into retries. Induce a pre-delivery failure and confirm retries retain the original window. Make the alert condition false before its retry and confirm no alert is sent. Replay an obsolete retry and confirm admission is refused. Simulate a partial delivery failure and confirm the whole execution is not replayed.

ADDITIONAL INFORMATION

  • Has associated issue
  • Required feature flag: ALERT_REPORTS_RETRY
  • Changes UI
  • Includes DB Migration (SIP-59 review required)
    • Adds nullable execution_owner and execution_window columns; no schedule data rewrite.
    • SQLite upgrade/downgrade and PostgreSQL upgrade tested. MySQL verification remains outstanding; DDL locking and duration depend on database/version.
    • Pause scheduling and drain active executions AND queued retries before replacing workers together. Mixed-version workers are unsupported. Two-argument legacy retries without ownership evidence are discarded and logged; older one-argument retries are indistinguishable from fresh cron tasks and must be drained. Rerun affected schedules.
    • Rollback requires draining workers before downgrading ownership columns.
  • Introduces new feature: alert retry opt-in using existing retry settings
  • Removes existing feature or API

This is not exactly-once delivery or guaranteed recovery after worker termination. Ownership recovery cannot recall a send already in flight. Live scheduled-report canaries remain required before rollout. No capture-detection changes are bundled here.

@github-actions github-actions Bot added risk:db-migration PRs that require a DB migration doc Namespace | Anything related to documentation labels Sep 16, 2026
@netlify

netlify Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit dfec854
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6ab12b0e392253000832766a
😎 Deploy Preview https://deploy-preview-44336--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.75824% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.67%. Comparing base (fc01645) to head (dfec854).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
superset/commands/report/execute.py 87.73% 6 Missing and 7 partials ⚠️
superset/commands/report/execution_claim.py 96.55% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44336      +/-   ##
==========================================
+ Coverage   80.65%   80.67%   +0.02%     
==========================================
  Files        2942     2943       +1     
  Lines      175691   175844     +153     
  Branches    40788    40818      +30     
==========================================
+ Hits       141704   141870     +166     
+ Misses      31325    31312      -13     
  Partials     2662     2662              
Flag Coverage Δ
hive 37.12% <16.48%> (-0.04%) ⬇️
javascript 76.11% <ø> (-0.01%) ⬇️
mysql 56.36% <68.68%> (-0.01%) ⬇️
postgres 56.38% <70.87%> (-0.02%) ⬇️
presto 39.00% <16.48%> (-0.04%) ⬇️
python 85.00% <91.20%> (+0.03%) ⬆️
sqlite 56.09% <68.68%> (-0.01%) ⬇️
unit 76.91% <84.61%> (+0.14%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

Copy link
Copy Markdown
Contributor

🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️❗ @fitzee Your base branch master has also updated superset/migrations.

Please consider rebasing your branch and resolving potential db migration conflicts.

@github-actions

Copy link
Copy Markdown
Contributor

🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️❗ @fitzee Your base branch master has also updated superset/migrations.

Please consider rebasing your branch and resolving potential db migration conflicts.

1 similar comment
@github-actions

Copy link
Copy Markdown
Contributor

🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️ 🙅‍♂️❗ @fitzee Your base branch master has also updated superset/migrations.

Please consider rebasing your branch and resolving potential db migration conflicts.

… head

Re-point 93d1b4a76c02 down_revision from e2f3a1b9c640 to 60f94cd6cd11,
the current single Alembic head on master. Prevents a divergent
migration head once this PR merges.
@github-actions github-actions Bot added the requires:rebase Requires rebasing on top of current master label Sep 19, 2026
@fitzee
fitzee marked this pull request as ready for review September 20, 2026 22:48
Comment thread UPDATING.md Outdated
Comment on lines +33 to +34
Retries queued by the old task signature are discarded rather than replayed without
ownership evidence. Restart scheduling after migration and worker replacement.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Legacy retry tasks containing only the schedule ID are treated as fresh executions, so they are not reliably discarded and may replay after the stale-window threshold.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Comment mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** UPDATING.md
**Line:** 33:34
**Comment:**
	*Comment Mismatch: Legacy retry tasks containing only the schedule ID are treated as fresh executions, so they are not reliably discarded and may replay after the stale-window threshold.

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
👍 | 👎

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of ba4ae23.

The migration guidance now explicitly states that legacy one-argument retry messages cannot be reliably discarded and must be drained before the upgrade. It also instructs rerunning affected schedules because discarded retries are not replayed automatically.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Corrected in ba4ae23. The previous wording was too broad: two-argument legacy retries are identified and discarded, but older one-argument retries are indistinguishable from fresh cron tasks. UPDATING.md explicitly requires draining those messages and no longer promises they will be discarded automatically.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 3cbf354.

The migration guidance now explicitly states that legacy one-argument retry messages cannot be reliably discarded and must be drained before the upgrade. It also instructs rerunning affected schedules because discarded retries are not replayed automatically.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 42ef0e7.

The migration guidance now explicitly states that legacy one-argument retry messages cannot be reliably discarded and must be drained before the upgrade. It also instructs rerunning affected schedules because discarded retries are not replayed automatically.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 7f9ce56.

The migration guidance now explicitly states that legacy one-argument retry messages cannot be reliably discarded and must be drained before the upgrade. It also instructs rerunning affected schedules because discarded retries are not replayed automatically.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of dfec854.

The migration guidance now explicitly states that legacy one-argument retry messages cannot be reliably discarded and must be drained before the upgrade. It also instructs rerunning affected schedules because discarded retries are not replayed automatically.

If that's not right, unresolve this thread and CodeAnt will leave it open.

@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue in UPDATING.md is correct. Legacy retry tasks that lack sufficient metadata (like ownership evidence) are indeed vulnerable to being treated as fresh executions, which can lead to unintended replays after the stale-window threshold.

To resolve this, you should update the documentation to clarify that workers must validate the task signature and ownership evidence before admitting a retry task. I have implemented this clarification below.

Would you like me to fetch all other comments on this PR to validate and fix them as well?

UPDATING.md

Pause scheduling and drain in-flight executions and queued retry tasks before
upgrading workers together: older workers do not participate in execution fencing.
Retries queued by the old task signature are discarded rather than replayed without
ownership evidence. Workers must validate task signatures and ownership evidence
before admitting any retry task to prevent stale replays. Restart scheduling
after migration and worker replacement.

Comment on lines +539 to +547
mock_page.evaluate.side_effect = [
{"height": 5000, "top": 100, "left": 50, "width": 800},
None,
with_error,
None,
with_error,
None,
with_error,
with_error,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: The mocked evaluation list omits each per-tile contentful-holder evaluation, shifting later results and preventing the test from observing the expected final semantic warning.

Assessment: 🟠 Major · 🔁 Occurrence: Often · 🏷️ Logic error

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** tests/unit_tests/utils/test_screenshot_utils.py
**Line:** 539:547
**Comment:**
	*Logic Error: The mocked evaluation list omits each per-tile contentful-holder evaluation, shifting later results and preventing the test from observing the expected final semantic warning.

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
👍 | 👎

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of ba4ae23.

The mock now explicitly handles each contentful-holder evaluation by returning a per-tile {"total": 1, "contentful": 1} result instead of letting those calls consume the generic chart-state result.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This capture-validation test was removed from #44336 when that work was split into #44465. The screenshot utilities and their tests are no longer changed by this retry PR. No additional change is needed here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 3cbf354.

The mock now explicitly handles each contentful-holder evaluation by returning a per-tile {"total": 1, "contentful": 1} result instead of letting those calls consume the generic chart-state result.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 42ef0e7.

The mock now explicitly handles each contentful-holder evaluation by returning a per-tile {"total": 1, "contentful": 1} result instead of letting those calls consume the generic chart-state result.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of 7f9ce56.

The mock now explicitly handles each contentful-holder evaluation by returning a per-tile {"total": 1, "contentful": 1} result instead of letting those calls consume the generic chart-state result.

If that's not right, unresolve this thread and CodeAnt will leave it open.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ CodeAnt verified this suggestion was addressed in subsequent commits and marked this thread resolved as of dfec854.

The mock now explicitly handles each contentful-holder evaluation by returning a per-tile {"total": 1, "contentful": 1} result instead of letting those calls consume the generic chart-state result.

If that's not right, unresolve this thread and CodeAnt will leave it open.

@fitzee
fitzee marked this pull request as draft September 20, 2026 22:56
@fitzee fitzee changed the title fix(reports): align capture validation and alert retry safeguards fix(reports): enable alert retries with execution safeguards Sep 20, 2026
@github-actions github-actions Bot removed the requires:rebase Requires rebasing on top of current master label Sep 21, 2026
@fitzee
fitzee marked this pull request as ready for review September 21, 2026 01:02

@bito-code-review bito-code-review Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Agent Run #825c8c

Actionable Suggestions - 6
Additional Suggestions - 11
  • superset/commands/report/execution_claim.py - 5
    • Deprecated utcnow clock · Line 136-136
      `datetime.utcnow()` is deprecated on Python 3.12+ and bypasses `naive_utcnow()` (`superset/utils/dates.py`), which this repo designates as the single clock for naive-UTC columns like `last_eval_dttm`. Sibling code in `execute.py` already uses `datetime.now(timezone.utc).replace(tzinfo=None)`. Prefer the shared helper so comparator and writers agree structurally.
    • Deprecated utcnow write · Line 153-153
      The claim write stamps `last_eval_dttm` with deprecated `datetime.utcnow()` (DeprecationWarning on Python 3.12+). The repo's designated clock for naive-UTC columns is `naive_utcnow()` in `superset/utils/dates.py`; `execute.py` already uses the `datetime.now(timezone.utc).replace(tzinfo=None)` pattern. Use the shared helper so all writers of this column share one clock.
    • Magic SQLSTATE literals · Line 77-77
      These SQLSTATE literals carry the admission policy (serialization failure vs deadlock) but are inline magic strings; `superset/versioning/db_errors.py` names its equivalents (`_PG_LOCK_CONTENTION`). Naming them here prevents transcription drift and documents intent at the comparison site.
    • Too many function arguments · Line 47-47
      The function `claim_execution` has 8 arguments, exceeding the limit of 5. Consider refactoring to use a dataclass or context object. The same issue exists in `_claim_execution` at line 89. A proposed refactor introduces `ExecutionClaimParams` dataclass to bundle parameters.
    • Use of assert detected · Line 115-115
      Replace `assert normalized is not None` with an explicit check that raises a `ValueError` to avoid `assert` being stripped in optimized mode.
  • tests/unit_tests/tasks/test_scheduler_soft_timeout.py - 2
    • Inline Import Violates Rule 12745 · Line 27-27
      BITO adaptive rule 12745 requires module-level imports unless a documented circular dependency exists; none is documented here. Sibling tests in `tests/unit_tests/tasks/` also import `superset.tasks.scheduler` inline, but the org rule mandates top-level placement. Move `from superset.tasks.scheduler import execute` next to the other module imports.
    • Unguarded call_args Indexing · Line 39-39
      `logger.warning.call_args` is `None` when no warning fired, so a regression surfaces as `AttributeError: 'NoneType' object has no attribute 'args'` instead of a clean assertion failure; it also pins only the last warning call. Add `logger.warning.assert_called_once()` before indexing, or scan `call_args_list`.
  • superset/reports/notifications/email.py - 1
    • Dead text parameter · Line 152-152
      `_error_template`, `_retry_error_template`, and `_final_failure_template` still accept a `text` parameter that is now silently discarded (all three set `safe_text` to the constant message). A caller passing `self._content.text` expects it to be rendered, so the dead parameter is misleading. Drop the parameter and its call-site arguments.
  • superset/reports/notifications/slack_mixin.py - 1
    • Dead text parameter · Line 106-106
      `_error_template` still declares a `text` parameter but all three branches (lines 106, 121, 132) render the constant message instead. The `text` argument passed from `_get_body` (line 140) is silently discarded. Remove the dead parameter and its call-site argument to avoid misleading future callers.
  • superset/commands/report/execute.py - 1
    • Dialect-dependent matched count · Line 862-863
      `_assert_execution_owned` relies on SQLAlchemy's MySQL dialect enabling CLIENT_FOUND_ROWS so a no-op UPDATE (setting `execution_owner` to its current value) reports matched=1 rather than changed=0. On backends where the dialect does not enable this flag, `owned` would be 0 and every delivery would raise `ReportSchedulePreviousWorkingError`. The comment documents the assumption but does not verify it at runtime.
  • tests/integration_tests/reports/commands_tests.py - 1
    • Replace deprecated `datetime.utcnow()` call · Line 1302-1302
      `datetime.utcnow()` is deprecated (DTZ003). Use `datetime.now(timezone.utc)` instead. Similar issues at lines 1329, 1794, 2842. Trailing comma (COM812) on this line also fixed.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset/commands/report/execute.py - 1
Review Details
  • Files reviewed - 25 · Commit Range: ec10f07..a41bdeb
    • docs/admin_docs/configuration/alerts-reports.mdx
    • superset-frontend/src/features/alerts/AlertReportModal.test.tsx
    • superset-frontend/src/features/alerts/AlertReportModal.tsx
    • superset/commands/report/execute.py
    • superset/commands/report/execution_claim.py
    • superset/commands/report/update.py
    • superset/migrations/versions/2026-09-16_00-00_93d1b4a76c02_add_report_execution_ownership.py
    • superset/reports/models.py
    • superset/reports/notifications/email.py
    • superset/reports/notifications/slack_mixin.py
    • superset/reports/notifications/webhook.py
    • superset/reports/schemas.py
    • superset/tasks/scheduler.py
    • superset/utils/report_execution.py
    • tests/integration_tests/reports/commands_tests.py
    • tests/integration_tests/reports/execution_claim_tests.py
    • tests/unit_tests/commands/report/execute_test.py
    • tests/unit_tests/commands/report/execution_claim_test.py
    • tests/unit_tests/commands/report/execution_ownership_migration_test.py
    • tests/unit_tests/commands/report/update_test.py
    • tests/unit_tests/reports/notifications/email_tests.py
    • tests/unit_tests/reports/notifications/slack_tests.py
    • tests/unit_tests/reports/notifications/webhook_tests.py
    • tests/unit_tests/reports/schemas_test.py
    • tests/unit_tests/tasks/test_scheduler_soft_timeout.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo



def test_retry_window_and_owner_fence_replays(sessions):
window = datetime.utcnow().replace(microsecond=0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use of datetime.utcnow()

datetime.utcnow() is deprecated and used in multiple places (lines 102, 139, 162, 206, 270, 319, 321). Replace with datetime.now(timezone.utc) to ensure timezone-aware datetimes.

Code suggestion
Check the AI-generated fix before applying
Suggested change
window = datetime.utcnow().replace(microsecond=0)
window = datetime.now(timezone.utc).replace(microsecond=0)

Code Review Run #825c8c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in ba4ae23. The claim tests use datetime.now(timezone.utc).replace(tzinfo=None) through a helper. Keeping the final value naive is intentional: it matches the metadata database timestamp representation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to replace datetime.utcnow() with datetime.now(timezone.utc) is generally recommended to ensure timezone-aware datetimes. However, since the project intentionally uses naive datetimes to match the metadata database timestamp representation, the current implementation is appropriate for this specific context. You may choose to ignore this suggestion if maintaining consistency with the database schema is the priority.

def test_window_normalization_converts_offsets():
assert normalize_window(
datetime(2026, 9, 15, 10, tzinfo=timezone(timedelta(hours=10)))
) == datetime(2026, 9, 15)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Datetime without tzinfo

datetime(2026, 9, 15) is called without a tzinfo argument. Add tzinfo=timezone.utc to make it timezone-aware.

Code suggestion
Check the AI-generated fix before applying
Suggested change
) == datetime(2026, 9, 15)
) == datetime(2026, 9, 15, tzinfo=timezone.utc)

Code Review Run #825c8c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this expectation unchanged. normalize_window deliberately converts aware timestamps to UTC and removes timezone information and microseconds for comparison with plain database DateTime columns. An aware expected value would test the opposite contract.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to add tzinfo=timezone.utc is not appropriate in this specific context. As you noted, normalize_window is designed to compare aware timestamps against plain database DateTime columns by stripping timezone information and microseconds. Adding tzinfo would create a mismatch with the function's intended contract for these comparisons.

tests/unit_tests/commands/report/execution_claim_test.py

) == datetime(2026, 9, 15, tzinfo=timezone.utc)

Comment thread superset/commands/report/execute.py Outdated
.update(
{
ReportSchedule.last_state: ReportState.ERROR,
ReportSchedule.last_eval_dttm: datetime.utcnow(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deprecated datetime.utcnow

persist_owned_report_execution_terminal_error uses deprecated datetime.utcnow() while the rest of this file uses datetime.now(timezone.utc).replace(tzinfo=None). Beyond deprecation, utcnow() has lower precision on some platforms, which could weaken the last_eval_dttm CAS comparisons used for ownership fencing.

Code Review Run #825c8c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in ba4ae23 to datetime.now(timezone.utc).replace(tzinfo=None), consistent with the surrounding code. The CAS remains protected by execution owner and WORKING state; this change does not rely on a claimed precision difference between the datetime APIs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to replace datetime.utcnow() with datetime.now(timezone.utc).replace(tzinfo=None) is appropriate. Using datetime.now(timezone.utc) is the recommended practice for generating timezone-aware timestamps, and replacing the timezone info ensures consistency with the existing codebase in superset/commands/report/execute.py while avoiding potential precision issues associated with utcnow().

superset/commands/report/execute.py

ReportSchedule.last_state: ReportState.ERROR,
                        ReportSchedule.last_eval_dttm: datetime.now(timezone.utc).replace(tzinfo=None),

Comment on lines +249 to +252
if terminal_reason not in (
"SoftTimeLimitExceeded",
"ReportExecutionBudgetExceededError",
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Magic strings terminal reasons

The terminal_reason not in ("SoftTimeLimitExceeded", "ReportExecutionBudgetExceededError") check hardcodes exception class names as bare strings. If a raise site or exception name changes, this silent no-notification path diverges. Consider named constants shared with the producers of these reasons.

Code Review Run #825c8c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in ba4ae23. The comparison uses SoftTimeLimitExceeded.__name__ and ReportExecutionBudgetExceededError.__name__ rather than independent string literals.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion to use named constants instead of hardcoded strings for exception names is appropriate. It improves maintainability by ensuring that if an exception class is renamed, the check remains accurate without requiring manual updates to string literals. You should apply this change by defining constants for these exception names and referencing them in the check.

superset/commands/report/execute.py

if terminal_reason not in (
                SoftTimeLimitExceeded.__name__,
                ReportExecutionBudgetExceededError.__name__,
            ):

Comment on lines +1812 to +1814
if self._delivery_started:
self._reset_retry_counter()
return False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retry skip skips terminalization

When _delivery_started is True, _handle_retry_or_error resets the counter and returns False without terminalizing the schedule state. The caller at line 2170 then proceeds to its own error handling, but if that path also fails or is skipped, the schedule remains in WORKING with execution_owner set until the working-timeout reaper intervenes. Consider persisting a terminal state before returning.

Code Review Run #825c8c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving terminalization with the caller and command-boundary fallback. Returning False is the helper's contract: the state handler persists ERROR, and an escaping failure invokes the ownership-fenced fallback for both alerts and reports. Existing tests cover partial delivery without retry and failures escaping after a claim. If persistence itself remains unavailable, timeout recovery is still necessary; persisting inside this helper would not remove that database-failure case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion from the reviewer is to ensure that when _delivery_started is True, the schedule state is terminalized before returning False in _handle_retry_or_error. Currently, the code resets the retry counter and returns False, which may leave the schedule in a WORKING state with an execution_owner set if the caller's subsequent error handling also fails or is skipped. Persisting a terminal state would prevent the schedule from remaining stuck until the working-timeout reaper intervenes.

superset/commands/report/execute.py

+        if self._delivery_started:
+            self._reset_retry_counter()
+            return False

Comment on lines +1887 to +1889
entered_at = self._report_schedule.last_eval_dttm
if not self._report_schedule.execution_owner and last_working:
entered_at = last_working.end_dttm

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unguarded entered_at None

entered_at is set from last_eval_dttm or last_working.end_dttm, but when execution_owner is None and last_working is None the guard at line 1883 already returns False. However, when execution_owner is truthy and last_eval_dttm is None (a freshly-claimed row whose CAS write committed but whose last_eval_dttm update was not yet flushed to the in-memory object), entered_at is None and the subtraction at line 1904 raises TypeError: unsupported operand type(s) for -. The last_eval_dttm is not None check at line 1903 guards the original last_eval_dttm path but not the last_working.end_dttm path (end_dttm is None for an in-flight WORKING log).

Code Review Run #825c8c


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ba4ae23. The timeout predicate checks the selected entered_at value, not only last_eval_dttm, before comparing timestamps. Added a regression test for a legacy WORKING log with no end timestamp.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suggestion provided by the reviewer is appropriate and addresses a potential TypeError. By ensuring that entered_at is only calculated when last_eval_dttm is available or when last_working is present, the code avoids performing arithmetic on None values. Applying this change improves the robustness of the timeout check.

superset/commands/report/execute.py

entered_at = self._report_schedule.last_eval_dttm
        if not self._report_schedule.execution_owner and last_working:
            entered_at = last_working.end_dttm
        if entered_at is None:
            return False

Comment thread superset/reports/notifications/email.py Resolved
Comment thread superset/commands/report/execute.py Resolved

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found a few retry-state edge cases worth tightening before merge. Details inline.

Comment thread superset/commands/report/execute.py Resolved
Comment thread superset/commands/report/execute.py Resolved
Comment thread superset/commands/report/execute.py Resolved

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the earlier feedback. The three issues from my first pass look addressed in ba4ae23. I ran the focused execution, ownership, timeout, notification and schema tests: 502 passed, with 26 PostgreSQL cases skipped because no test database was configured. I found one additional timeout regression, reproduced with a local HTTP server, and left the details inline.

Comment on lines +171 to +175
return float(
get_report_task_timeout_options(
is_report=False, working_timeout=model.working_timeout, config=app.config
).get("soft_time_limit", float("inf"))
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we translate the unlimited deadline back to None before passing it to the HTTP transport? With ALERT_REPORTS_WORKING_TIME_OUT_KILL=False (or no working_timeout) and ALERT_REPORTS_CSV_REQUEST_TIMEOUT=None, this creates an infinite deadline. _phase_timeout() then returns inf, which reaches urllib and fails in socket.settimeout() with OverflowError: timestamp out of range for platform time_t, before the request is sent.

I reproduced this through _get_data(CSV) against a local HTTP server: it succeeds without the execution context and fails with the new context. CSV/XLSX and embedded-text alerts share this timeout path. None is a documented value for the request timeout, so preserving None when both limits are unbounded would keep those configurations working. A transport test for that combination would catch what the deadline-only tests miss.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3cbf354. _phase_timeout() converts an unlimited deadline to None before it reaches the HTTP transport; finite limits remain unchanged. Added real local-HTTP tests for CSV/XLSX GET and POST exports and embedded-text alerts, covering both disabled worker limits and an absent working timeout. All 14 new regression cases pass.

@EnxDev EnxDev left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The unlimited-timeout fix looks good, including the real HTTP regression tests. I completed another pass over retry admission, recovery, delivery and the UI/API changes. The focused backend suite passed: 546 passed, with 26 PostgreSQL cases skipped because no test database was configured. The alert/report modal suite also passed all 79 tests. I found one additional notification regression at retry exhaustion and left the reproduction inline.

Comment thread superset/commands/report/execute.py Resolved

@bito-code-review bito-code-review Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Agent Run #dc9c98

Actionable Suggestions - 1
  • tests/unit_tests/commands/report/execution_claim_test.py - 1
Additional Suggestions - 8
  • superset/commands/report/execution_claim.py - 3
    • Inconsistent retry_attempt reset · Line 67-77
      The UPDATE resets `retry_attempt` to 0 but deliberately retains `execution_owner`/`execution_window` for fencing (per the line-78 comment). A later claim for a new window overwrites `retry_attempt` via `_increment_retry` (execute.py:1754), so this reset is dead state churn and leaves the row semantically inconsistent: `retry_attempt=0` with a still-queued `retry_scheduled_dttm` owner. Drop the key.
    • Duplicated window normalization · Line 62-63
      `normalize_window(window)` is evaluated twice for the two column filters (lines 62-63). `_claim_execution` already normalizes once into `normalized` (line 150) and reuses it. Hoisting matches the sibling pattern, avoids recomputing the tz conversion, and keeps both predicates provably identical.
    • Inconsistent UTC timestamp idiom · Line 70-72
      This UPDATE writes `last_eval_dttm` as `datetime.now(timezone.utc).replace(tzinfo=None)` while sibling `_claim_execution` (line 189) and the staleness check (line 172) use `datetime.utcnow()`. Both are naive UTC so values agree, but the divergent idioms invite drift (e.g. a future `now()` without UTC conversion). Match the sibling call.
  • tests/unit_tests/commands/report/execute_test.py - 2
    • Missing test docstring · Line 137-137
      New test `test_last_retry_preserves_opted_in_recipient_notice` has no docstring. BITO.md adaptive rule 12148 requires every newly added test function to carry one, and the sibling retry tests here (`test_alert_retry_reevaluates_condition_and_clears_retry_state`, `test_rejected_capture_enters_whole_execution_retry`) all do. Add a one-liner stating the scenario: last attempt, opted-in recipients get the per-attempt notice unless `send_failed_reports` substitutes the final report.
    • Missing test type hints · Line 138-140
      Parameters of `test_last_retry_preserves_opted_in_recipient_notice` (`mocker`, `schedule_type`, `send_failed_reports`) are unannotated and the function has no `-> None`. BITO.md adaptive rule 12898 requires full type annotations on test functions, and sibling tests here (`test_rejected_capture_enters_whole_execution_retry`, `test_alert_pre_delivery_failure_schedules_retry`) annotate `mocker: MockerFixture` and `schedule_type: ReportScheduleType`. Mirror that pattern.
  • tests/unit_tests/reports/notifications/email_tests.py - 2
    • Undocumented inline imports · Line 115-117
      The inline imports in `test_editor_error_diagnostics_are_sanitized` omit the explanatory comment all eight sibling tests carry ("`superset.models.helpers`, a dependency of following imports, requires app context"; verified by grep count). Without it, the BITO.md 12745-required justification for inline imports is missing, and a future hoist to module level would crash the suite at import time. Please add the same two-line comment above the imports.
    • Missing local type annotations · Line 119-136
      BITO.md 13153 mandates explicit annotations for all test-file locals even when inferable. The new test's locals `content`, `notification`, and `body` (types `NotificationContent`, `EmailNotification`, `str`) are unannotated. Sibling tests share the gap, but new code should comply with the mandated standard; the function signature already does (`editor_only: bool) -> None`).
  • superset/reports/notifications/email.py - 1
    • Editor-only invariant implicit · Line 154-154
      The `is_editor_error` gate makes `email.py` trust that every caller setting it also restricts recipients to editors; that pairing lives only in `send_error` (`execute.py:1676`, `editor_recipients` filter). Currently safe, but nothing in the notification layer documents or enforces it. Consider documenting the editor-only invariant on the `NotificationContent.is_editor_error` field so future callers don't pair the flag with all recipients.
Review Details
  • Files reviewed - 9 · Commit Range: a41bdeb..42ef0e7
    • docs/admin_docs/configuration/alerts-reports.mdx
    • superset/commands/report/execute.py
    • superset/commands/report/execution_claim.py
    • superset/reports/notifications/base.py
    • superset/reports/notifications/email.py
    • superset/utils/report_execution.py
    • tests/unit_tests/commands/report/execute_test.py
    • tests/unit_tests/commands/report/execution_claim_test.py
    • tests/unit_tests/reports/notifications/email_tests.py
  • Files skipped - 1
    • UPDATING.md - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

Comment on lines +340 to +342
window = utc_now().replace(microsecond=0)
with sessions() as session:
schedule = session.query(ReportSchedule).one()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing local type annotations

BITO adaptive rule 13153 requires explicit annotations on all test-file locals, even when inferable. The new tests annotate parameters and return types but leave locals bare: window/schedule here, window/schedule at lines 372/374, and now/schedule/result at lines 393/395/402. Adding : datetime, : ReportSchedule, and : ExecutionClaim | None keeps the file compliant with the org typing standard.

Code Review Run #dc9c98


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving inferred local types unchanged. The helper return types and function signatures already provide type information, and the repository's MyPy checks pass. Additional annotations on every test local do not address a correctness issue and would add noise to this fix.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reviewer's suggestion to add explicit type annotations to local variables in the test file is a matter of coding style preference. Since the repository's MyPy checks already pass and the function signatures provide sufficient type information, adding these annotations is not strictly required for correctness. You may choose to address this to align with the organization's typing standards, or leave the code as is if you prefer to avoid the additional noise.

@EnxDev EnxDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@bito-code-review

bito-code-review Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #c7c969

Actionable Suggestions - 0
Additional Suggestions - 2
  • tests/integration_tests/reports/commands_tests.py - 2
    • Untyped mock variable · Line 3276-3276
      The new `final_failure_mock` mock variable is untyped. BITO.md adaptive rule 12787 requires explicit type annotations on all mock variables in test files (e.g. `final_failure_mock: MagicMock`). Add the annotation to keep the test file consistent with the repo's typing standard.
    • Untyped local variable · Line 3293-3293
      The new local `error_message` variable is untyped. BITO.md adaptive rule 13153 requires explicit type annotations on all local variables in test files even when inferable. Add `error_message: str = ...` to comply with the repo's typing standard.
Review Details
  • Files reviewed - 1 · Commit Range: 42ef0e7..dfec854
    • tests/integration_tests/reports/commands_tests.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@EnxDev
EnxDev merged commit 8ec8bee into apache:master Sep 21, 2026
88 checks passed
@fitzee

fitzee commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Reviewed the latest Bito suggestions. Added the final-retry test's parameter/return annotations and scenario docstring in 1420233. Four focused cases and all PR pre-commit checks pass.

Leaving the remaining suggestions unchanged:

  • The cancellation counter reset is intentional. The same update clears retry_scheduled_dttm; execution_owner/execution_window remain only as stale-message fences. Removing the reset would preserve stale retry state.
  • Repeating deterministic window normalization and the equivalent naive-UTC timestamp idioms are small refactoring nits, not correctness gaps. No reason to switch back to deprecated utcnow().
  • is_editor_error already has a field comment restricting diagnostic email to schedule editors. The earlier review replies explain the caller restriction and terminal-error fallback.
  • Extra annotations on inferable test locals and comments on established inline-import patterns do not justify further churn here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

doc Namespace | Anything related to documentation risk:db-migration PRs that require a DB migration size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants