You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by rb...@apache.org on 2026/09/10 18:21:56 UTC
(superset) branch master updated: fix(reports): recheck readiness at capture time (#44114)
This is an automated email from the ASF dual-hosted git repository.
rebenitez1802 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 12e747437d1 fix(reports): recheck readiness at capture time (#44114)
12e747437d1 is described below
commit 12e747437d1159098174aef805b9f702406d91a3
Author: Mafi <ma...@gmail.com>
AuthorDate: Fri Sep 11 04:21:48 2026 +1000
fix(reports): recheck readiness at capture time (#44114)
Co-authored-by: Rafael Benitez <re...@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <no...@anthropic.com>
---
UPDATING.md | 6 +
docs/admin_docs/configuration/alerts-reports.mdx | 9 ++
superset/utils/screenshot_utils.py | 99 ++++++++++++++++
superset/utils/webdriver.py | 41 +++++++
tests/unit_tests/utils/test_screenshot_utils.py | 145 +++++++++++++++++++++--
tests/unit_tests/utils/webdriver_test.py | 125 +++++++++++++++++--
6 files changed, 410 insertions(+), 15 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index 07c6bb0b600..a4c4eb75f2c 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,12 @@ assists people when migrating to a new version.
## Next
+### Report capture readiness is rechecked immediately before screenshots
+
+Scheduled report and alert captures require chart readiness to remain stable
+immediately before Chromium captures the image. A capture that re-enters a loading
+state during that window fails instead of delivering a screenshot with spinners.
+
### Resample "Fill the entire time range"
Charts with Resample can enable **Fill the entire time range** so gap-filling
diff --git a/docs/admin_docs/configuration/alerts-reports.mdx b/docs/admin_docs/configuration/alerts-reports.mdx
index be847061a05..c6c8b4c9c0f 100644
--- a/docs/admin_docs/configuration/alerts-reports.mdx
+++ b/docs/admin_docs/configuration/alerts-reports.mdx
@@ -486,6 +486,15 @@ applies to alerts that attach reports. Check worker logs for
`ScreenshotBlankCaptureError` and `report_capture_validation` when investigating
these failures.
+Immediately before each scheduled report screenshot, chart readiness must remain
+stable for 500 milliseconds, unless less than one stability window of the
+execution budget is left, in which case the check is skipped and logged with
+`skipped=True`. This final check runs after scrolling, content
+expansion, and animation waits so a chart that returns to a loading state is not
+captured during the stability window. Successful checks emit
+`report_capture_readiness_stable`; a timeout emits
+`report_capture_readiness_changed` and stops capture and delivery.
+
### Confirm feature flag is enabled and you have sufficient permissions
If you don't see "Alerts & Reports" under the _Manage_ section of the Settings dropdown in the Superset UI, you need to enable the `ALERT_REPORTS` feature flag (see above). Enable another feature flag and check to see that it took effect, to verify that your config file is getting loaded.
diff --git a/superset/utils/screenshot_utils.py b/superset/utils/screenshot_utils.py
index b48814b2403..8f98528d3b9 100644
--- a/superset/utils/screenshot_utils.py
+++ b/superset/utils/screenshot_utils.py
@@ -55,6 +55,7 @@ SCREENSHOT_BLANK_MAX_ENTROPY = 1.5
SCREENSHOT_BLANK_MIN_EDGE_DIFFERENCE = 8
SCREENSHOT_BLANK_MIN_STRUCTURAL_EDGE_RATIO = 0.02
SCREENSHOT_BLANK_SAMPLE_SIZES = (256, 1024)
+REPORT_CAPTURE_READINESS_STABILITY_MS = 500
# Runtime task-budget policy shared with the approach introduced in #42118.
# Celery exposes the effective per-task hard/soft limits only on the running
@@ -487,6 +488,35 @@ REPORT_ALL_CHART_HOLDERS_READY_JS = (
f"() => {{ {UNREADY_ALL_CHART_HOLDERS_JS_BODY} "
"return holders.length > 0 && unready.length === 0; }"
)
+
+
+def _stable_readiness_js(readiness_predicate: str) -> str:
+ """Require a readiness predicate to remain true for a capture dwell."""
+
+ return f"""
+ args => {{
+ const ready = ({readiness_predicate})();
+ const now = performance.now();
+ const previous = window.__supersetCaptureReadiness;
+ if (!ready) {{
+ window.__supersetCaptureReadiness = {{token: args.token, since: null}};
+ return false;
+ }}
+ if (!previous || previous.token !== args.token || previous.since === null) {{
+ window.__supersetCaptureReadiness = {{token: args.token, since: now}};
+ return false;
+ }}
+ return now - previous.since >= args.stabilityMs;
+ }}
+ """
+
+
+STABLE_REPORT_CHART_HOLDERS_READY_JS = _stable_readiness_js(
+ REPORT_CHART_HOLDERS_READY_JS
+)
+STABLE_REPORT_ALL_CHART_HOLDERS_READY_JS = _stable_readiness_js(
+ REPORT_ALL_CHART_HOLDERS_READY_JS
+)
CHART_HOLDERS_MOUNTED_JS = (
f"() => document.querySelectorAll('{CHART_HOLDER_SELECTOR}').length > 0"
)
@@ -516,6 +546,38 @@ CHART_CONTAINER_READY_JS = f"""
);
}}
"""
+STABLE_CHART_CONTAINER_READY_JS = _stable_readiness_js(CHART_CONTAINER_READY_JS)
+
+
+def wait_for_stable_readiness(
+ page: Page,
+ readiness_predicate: str,
+ timeout_seconds: float,
+) -> bool:
+ """Wait for capture readiness when the available budget can satisfy the dwell.
+
+ Returns ``False`` when less than one stability window plus a polling-interval
+ margin remains. The caller may proceed because the preceding readiness gate has
+ already completed; starting an impossible dwell would only convert a usable
+ capture budget into a timeout.
+ """
+
+ # The first poll only records the dwell start, so success needs the full
+ # stability window plus at least one polling interval on top of it.
+ minimum_timeout_seconds = (REPORT_CAPTURE_READINESS_STABILITY_MS + 250) / 1000
+ if timeout_seconds <= minimum_timeout_seconds:
+ return False
+
+ page.wait_for_function(
+ readiness_predicate,
+ arg={
+ "token": str(time.monotonic_ns()),
+ "stabilityMs": REPORT_CAPTURE_READINESS_STABILITY_MS,
+ },
+ timeout=timeout_seconds * 1000,
+ )
+ return True
+
# Diagnostic companion to CHART_CONTAINER_READY_JS: reports why a chart
# capture is (or is not) ready. Chart pages have no dashboard grid holders,
@@ -1152,6 +1214,43 @@ def take_tiled_screenshot( # noqa: C901
# Take screenshot with clipping to capture only this tile's content
tile_screenshot: bytes | None = None
for capture_attempt in range(1, TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS + 1):
+ if report_execution_context:
+ stable_wait = _timeout_seconds(
+ "capture_readiness_stability",
+ reserve_seconds=(
+ report_execution_context.readiness_reserve_seconds
+ ),
+ )
+ try:
+ waited_for_stability = wait_for_stable_readiness(
+ page,
+ STABLE_REPORT_CHART_HOLDERS_READY_JS,
+ stable_wait,
+ )
+ logger.info(
+ "report_capture_readiness_stable tile=%s/%s "
+ "attempt=%s/%s stability_ms=%s skipped=%s%s",
+ i + 1,
+ num_tiles,
+ capture_attempt,
+ TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS,
+ REPORT_CAPTURE_READINESS_STABILITY_MS,
+ not waited_for_stability,
+ context_suffix,
+ )
+ except PlaywrightTimeout:
+ logger.warning(
+ "report_capture_readiness_changed tile=%s/%s "
+ "attempt=%s/%s%s; aborting before capture or delivery",
+ i + 1,
+ num_tiles,
+ capture_attempt,
+ TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS,
+ context_suffix,
+ exc_info=True,
+ )
+ readiness_timeout = True
+ raise
capture_timeout = (
_timeout_seconds(
"screenshot_capture",
diff --git a/superset/utils/webdriver.py b/superset/utils/webdriver.py
index 9a5f32e75a8..85ade1b2b58 100644
--- a/superset/utils/webdriver.py
+++ b/superset/utils/webdriver.py
@@ -42,12 +42,16 @@ from superset.utils.screenshot_utils import (
FORCE_ALL_CHART_HOLDERS_IN_VIEW_JS,
get_screenshot_blankness_metrics,
REPORT_ALL_CHART_HOLDERS_READY_JS,
+ REPORT_CAPTURE_READINESS_STABILITY_MS,
REPORT_HAS_RENDERED_CHART_HOLDERS_JS,
resolve_screenshot_task_budget_seconds,
ScreenshotBlankCaptureError,
ScreenshotTaskBudgetExceededError,
+ STABLE_CHART_CONTAINER_READY_JS,
+ STABLE_REPORT_ALL_CHART_HOLDERS_READY_JS,
take_tiled_screenshot,
TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS,
+ wait_for_stable_readiness,
)
WindowSize = tuple[int, int]
@@ -262,6 +266,43 @@ class WebDriverPlaywright(WebDriverProxy):
context_suffix = f" [{log_context}]" if log_context else ""
for attempt in range(1, TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS + 1):
+ if report_execution_context:
+ stable_timeout = report_execution_context.deadline.timeout_seconds(
+ "capture_readiness_stability",
+ reserve_seconds=(
+ report_execution_context.readiness_reserve_seconds
+ ),
+ )
+ stable_predicate = (
+ STABLE_CHART_CONTAINER_READY_JS
+ if element_name == "chart-container"
+ else STABLE_REPORT_ALL_CHART_HOLDERS_READY_JS
+ )
+ try:
+ waited_for_stability = wait_for_stable_readiness(
+ page,
+ stable_predicate,
+ stable_timeout,
+ )
+ logger.info(
+ "report_capture_readiness_stable capture=standard "
+ "attempt=%s/%s stability_ms=%s skipped=%s%s",
+ attempt,
+ TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS,
+ REPORT_CAPTURE_READINESS_STABILITY_MS,
+ not waited_for_stability,
+ context_suffix,
+ )
+ except PlaywrightTimeout:
+ logger.warning(
+ "report_capture_readiness_changed capture=standard "
+ "attempt=%s/%s%s; aborting before capture or delivery",
+ attempt,
+ TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS,
+ context_suffix,
+ exc_info=True,
+ )
+ raise
capture_timeout = (
report_execution_context.deadline.timeout_seconds(
"screenshot_capture",
diff --git a/tests/unit_tests/utils/test_screenshot_utils.py b/tests/unit_tests/utils/test_screenshot_utils.py
index 34beab9ac58..943ee8441e7 100644
--- a/tests/unit_tests/utils/test_screenshot_utils.py
+++ b/tests/unit_tests/utils/test_screenshot_utils.py
@@ -16,21 +16,26 @@
# under the License.
import io
+import shutil
+import subprocess
from unittest.mock import MagicMock, patch
from uuid import UUID
import pytest
from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
+from superset.utils import json
from superset.utils.report_execution import (
ReportExecutionContext,
ReportExecutionDeadline,
)
from superset.utils.screenshot_utils import (
+ _stable_readiness_js,
combine_screenshot_tiles,
CONTENTFUL_CHART_HOLDERS_IN_CLIP_JS,
get_screenshot_blankness_metrics,
is_screenshot_nearly_uniform,
+ REPORT_CAPTURE_READINESS_STABILITY_MS,
resolve_screenshot_task_budget_seconds,
SCREENSHOT_TASK_BUDGET_MAX_MARGIN_SECONDS,
ScreenshotBlankCaptureError,
@@ -40,6 +45,7 @@ from superset.utils.screenshot_utils import (
take_tiled_screenshot,
TILED_SCREENSHOT_TOTAL_WAIT_BUDGET_SECONDS,
TiledScreenshotBudgetExceededError,
+ wait_for_stable_readiness,
)
@@ -60,6 +66,83 @@ def _two_tone_blank(width: int = 100, height: int = 100) -> bytes:
return output.getvalue()
+def test_stable_readiness_skips_impossible_dwell() -> None:
+ page = MagicMock()
+
+ waited = wait_for_stable_readiness(
+ page,
+ "() => true",
+ REPORT_CAPTURE_READINESS_STABILITY_MS / 1000,
+ )
+
+ assert waited is False
+ page.wait_for_function.assert_not_called()
+
+
+def test_stable_readiness_skips_when_budget_below_polling_margin() -> None:
+ page = MagicMock()
+
+ # Above the raw 500 ms window but below window + polling margin: the dwell
+ # cannot complete before the timeout, so it must skip rather than abort.
+ waited = wait_for_stable_readiness(page, "() => true", 0.6)
+
+ assert waited is False
+ page.wait_for_function.assert_not_called()
+
+
+def test_stable_readiness_javascript_resets_dwell_state() -> None:
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required to execute the readiness predicate")
+ assert node is not None
+
+ expression = _stable_readiness_js("() => globalThis.ready")
+ script = r"""
+const input = JSON.parse(require("fs").readFileSync(0, "utf8"));
+global.window = global;
+let now = 0;
+global.performance = {now: () => now};
+global.ready = false;
+const predicate = eval("(" + input.expression + ")");
+const results = [];
+const poll = (token, time, ready) => {
+ now = time;
+ global.ready = ready;
+ results.push(predicate({token, stabilityMs: 500}));
+};
+poll("first", 0, false);
+poll("first", 100, true);
+poll("first", 599, true);
+poll("first", 600, true);
+poll("first", 700, false);
+poll("first", 800, true);
+poll("first", 1300, true);
+poll("second", 1400, true);
+poll("second", 1900, true);
+process.stdout.write(JSON.stringify(results));
+"""
+
+ completed = subprocess.run( # noqa: S603
+ [node, "-e", script],
+ input=json.dumps({"expression": expression}),
+ capture_output=True,
+ check=True,
+ text=True,
+ )
+
+ assert json.loads(completed.stdout) == [
+ False,
+ False,
+ False,
+ True,
+ False,
+ False,
+ True,
+ False,
+ True,
+ ]
+
+
class TestScreenshotBlankDetection:
def test_uniform_png_is_blank(self):
is_blank, dominant_ratio = is_screenshot_nearly_uniform(_png(100, 100, "white"))
@@ -743,7 +826,7 @@ class TestTakeTiledScreenshot:
self._create_chart_like_tile(),
]
- def wait_for_function(script, **_kwargs):
+ def wait_for_function(script, *_args, **_kwargs):
if "__supersetRepaintComplete" in script:
raise PlaywrightTimeout("no repaint")
return None
@@ -836,9 +919,21 @@ class TestTakeTiledScreenshot:
element_info = {"height": 1000, "top": 0, "left": 0, "width": 800}
wait_calls = 0
- def wait_for_function(*args, **kwargs):
+ def wait_for_function(
+ expression,
+ *,
+ arg=None,
+ timeout=None,
+ polling=None,
+ ):
nonlocal wait_calls
- events.append("mount" if wait_calls == 0 else "ready")
+ if wait_calls == 0:
+ events.append("mount")
+ elif "__supersetCaptureReadiness" in expression:
+ assert arg["stabilityMs"] == REPORT_CAPTURE_READINESS_STABILITY_MS
+ events.append("stable_ready")
+ else:
+ events.append("ready")
wait_calls += 1
def evaluate(script, _arg=None):
@@ -870,7 +965,13 @@ class TestTakeTiledScreenshot:
)
assert result == b"combined"
- assert events == ["mount", "dimensions", "ready", "capture"]
+ assert events == [
+ "mount",
+ "dimensions",
+ "ready",
+ "stable_ready",
+ "capture",
+ ]
def test_zero_holders_timeout_before_dimensions_or_capture(self, mock_page):
"""An empty DOM cannot vacuously pass the tiled readiness gate."""
@@ -1098,8 +1199,19 @@ class TestTakeTiledScreenshot:
report_execution_context=_report_context(),
)
- # One initial holder-mount gate, then one readiness poll per tile.
- assert mock_page.wait_for_function.call_count == 4
+ # One initial holder-mount gate, then readiness and stable-readiness
+ # polls per tile.
+ stable_calls = [
+ call
+ for call in mock_page.wait_for_function.call_args_list
+ if call.args and "__supersetCaptureReadiness" in call.args[0]
+ ]
+ assert len(stable_calls) == 3
+ for stable_call in stable_calls:
+ assert (
+ stable_call.kwargs["arg"]["stabilityMs"]
+ == REPORT_CAPTURE_READINESS_STABILITY_MS
+ )
# Each call uses viewport-scoped JS and the load_wait timeout
mount_call, *tile_calls = mock_page.wait_for_function.call_args_list
@@ -1110,7 +1222,7 @@ class TestTakeTiledScreenshot:
assert "getBoundingClientRect" in js
assert "window.innerHeight" in js
assert "dashboard-component-chart-holder" in js
- assert call[1]["timeout"] == 30 * 1000
+ assert call.kwargs["timeout"] == 30 * 1000
def test_per_tile_readiness_timeout_raises_and_skips_capture(self, mock_page):
"""A per-tile readiness timeout raises and does not capture that tile.
@@ -1170,6 +1282,25 @@ class TestTakeTiledScreenshot:
# slow query can be told apart from the virtualization race.
assert warning_args[14] == [{"chartId": "42", "state": "waiting_on_database"}]
+ def test_readiness_change_aborts_before_tile_capture(self, mock_page):
+ from superset.utils.screenshot_utils import PlaywrightTimeout
+
+ mock_page.wait_for_function.side_effect = [
+ None,
+ None,
+ PlaywrightTimeout("spinner returned"),
+ ]
+
+ with pytest.raises(PlaywrightTimeout, match="spinner returned"):
+ take_tiled_screenshot(
+ mock_page,
+ "dashboard",
+ tile_height=2000,
+ report_execution_context=_report_context(),
+ )
+
+ mock_page.screenshot.assert_not_called()
+
def test_timeout_warning_includes_log_context(self, mock_page):
"""The log context (e.g. report execution id) is threaded through for
correlation with the run that triggered this screenshot."""
diff --git a/tests/unit_tests/utils/webdriver_test.py b/tests/unit_tests/utils/webdriver_test.py
index e031f847d58..ac9641b9861 100644
--- a/tests/unit_tests/utils/webdriver_test.py
+++ b/tests/unit_tests/utils/webdriver_test.py
@@ -28,7 +28,10 @@ from superset.utils.report_execution import (
ReportExecutionContext,
ReportExecutionDeadline,
)
-from superset.utils.screenshot_utils import ScreenshotBlankCaptureError
+from superset.utils.screenshot_utils import (
+ REPORT_CAPTURE_READINESS_STABILITY_MS,
+ ScreenshotBlankCaptureError,
+)
from superset.utils.webdriver import (
check_playwright_availability,
PLAYWRIGHT_AVAILABLE,
@@ -127,10 +130,35 @@ class TestStandardScreenshotValidation:
assert result == output.getvalue()
assert page.screenshot.call_count == 2
page.bring_to_front.assert_called_once_with()
- page.wait_for_function.assert_called_once_with(
- "() => window.__supersetRepaintComplete === true",
- timeout=5000,
+ assert any(
+ call.args == ("() => window.__supersetRepaintComplete === true",)
+ and call.kwargs == {"timeout": 5000}
+ for call in page.wait_for_function.call_args_list
)
+ stable_calls = [
+ call
+ for call in page.wait_for_function.call_args_list
+ if "__supersetCaptureReadiness" in call.args[0]
+ ]
+ assert len(stable_calls) == 2
+
+ def test_readiness_change_aborts_before_standard_capture(self):
+ from superset.utils.webdriver import PlaywrightTimeout
+
+ page = MagicMock()
+ element = MagicMock()
+ page.wait_for_function.side_effect = PlaywrightTimeout("spinner returned")
+
+ with pytest.raises(PlaywrightTimeout, match="spinner returned"):
+ WebDriverPlaywright._get_validated_screenshot(
+ page,
+ element,
+ "standalone",
+ "execution_id=test",
+ _report_context(),
+ )
+
+ page.screenshot.assert_not_called()
def test_repeated_blank_capture_fails_closed(self):
page = MagicMock()
@@ -180,7 +208,13 @@ class TestStandardScreenshotValidation:
valid.save(output, format="PNG")
page.screenshot.side_effect = [_png("white"), output.getvalue()]
page.evaluate.return_value = True
- page.wait_for_function.side_effect = PlaywrightTimeout("stalled repaint")
+
+ def wait_for_function(script, *_args, **_kwargs):
+ if "__supersetRepaintComplete" in script:
+ raise PlaywrightTimeout("stalled repaint")
+ return None
+
+ page.wait_for_function.side_effect = wait_for_function
result = WebDriverPlaywright._get_validated_screenshot(
page,
@@ -191,9 +225,10 @@ class TestStandardScreenshotValidation:
)
assert result == output.getvalue()
- page.wait_for_function.assert_called_once_with(
- "() => window.__supersetRepaintComplete === true",
- timeout=5000,
+ assert any(
+ call.args == ("() => window.__supersetRepaintComplete === true",)
+ and call.kwargs == {"timeout": 5000}
+ for call in page.wait_for_function.call_args_list
)
def test_repaint_preserves_celery_soft_timeout(self):
@@ -1494,6 +1529,80 @@ class TestWebDriverPlaywrightChartReadiness:
assert page.wait_for_function.call_args.kwargs["timeout"] == 590_000
+ def test_capture_readiness_wires_stable_predicate_and_timeout(self):
+ page = MagicMock()
+ element = MagicMock()
+ page.screenshot.return_value = _png("white")
+ page.evaluate.return_value = False
+
+ def signature_checked_wait(
+ expression,
+ *,
+ arg=None,
+ timeout=None,
+ polling=None,
+ ):
+ assert "__supersetCaptureReadiness" in expression
+ assert arg["stabilityMs"] == REPORT_CAPTURE_READINESS_STABILITY_MS
+
+ page.wait_for_function.side_effect = signature_checked_wait
+
+ result = WebDriverPlaywright._get_validated_screenshot(
+ page,
+ element,
+ "standalone",
+ "execution_id=test",
+ report_execution_context=_report_context(),
+ )
+
+ assert result == _png("white")
+ readiness_call = page.wait_for_function.call_args
+ assert "__supersetCaptureReadiness" in readiness_call.args[0]
+ assert (
+ readiness_call.kwargs["arg"]["stabilityMs"]
+ == REPORT_CAPTURE_READINESS_STABILITY_MS
+ )
+ assert readiness_call.kwargs["timeout"] == 690_000
+
+ def test_chart_capture_uses_chart_container_stable_predicate(self):
+ page = MagicMock()
+ element = MagicMock()
+ element.screenshot.return_value = _png("white")
+ page.evaluate.return_value = False
+
+ WebDriverPlaywright._get_validated_screenshot(
+ page,
+ element,
+ "chart-container",
+ "execution_id=test",
+ report_execution_context=_report_context(chart_id=7),
+ )
+
+ predicate = page.wait_for_function.call_args.args[0]
+ assert "document.querySelector('.chart-container')" in predicate
+
+ def test_capture_skips_stability_dwell_when_budget_is_too_short(self):
+ page = MagicMock()
+ element = MagicMock()
+ page.screenshot.return_value = _png("white")
+ page.evaluate.return_value = False
+ context = _report_context()
+ context = replace(
+ context,
+ deadline=replace(context.deadline, _clock=lambda: 689.6),
+ )
+
+ result = WebDriverPlaywright._get_validated_screenshot(
+ page,
+ element,
+ "standalone",
+ "execution_id=test",
+ report_execution_context=context,
+ )
+
+ assert result == _png("white")
+ page.wait_for_function.assert_not_called()
+
def test_report_readiness_budget_exhaustion_skips_poll_and_capture(self):
from uuid import UUID