This is an automated email from the ASF dual-hosted git repository. sadpandajoe pushed a commit to branch fix-report-dashboard-screenshot-whitespace in repository https://gitbox.apache.org/repos/asf/superset.git
commit 1ad08529d0a07f60cb90006a51289598fd08df2e Author: Joe Li <[email protected]> AuthorDate: Mon Nov 16 00:48:54 2026 +0000 fix(reports): end report dashboard screenshots at the rendered content Add an opt-in trim_to_content option on BaseScreenshot and DashboardScreenshot, forwarded through driver() to the Playwright webdriver and enabled by the report command for dashboards whose schedule does not pin a height. After the capture, the page nominates the colour of the page background behind the dashboard (the opaque background of the innermost box that covers the whole page, so the two-tone app shell is handled), and the image must confirm that colour exactly on every removed row. Only a trailing run of rows that are uniformly that colour is removed, keeping as many background rows below the content as lead the image. Anything else is left untouched: content painted to the bottom edge, gradient, image or translucent backgrounds, unreadable pages and images that are not 8-bit truecolour PNGs or fail the PNG integrity check. The blank-capture verdict is taken on the untrimmed capture, and the trimmed bytes are re-validated with the content verdict carried over only when the same report context already approved the original bytes. Thumbnails, chart captures, captures with a pinned height and captures that do not opt in are unchanged. --- superset/commands/report/execute.py | 2 + superset/utils/screenshot_utils.py | 179 ++++++++++++ superset/utils/screenshots.py | 8 + superset/utils/webdriver.py | 15 + tests/unit_tests/utils/test_screenshot_trim.py | 389 +++++++++++++++++++++++++ 5 files changed, 593 insertions(+) diff --git a/superset/commands/report/execute.py b/superset/commands/report/execute.py index c367bb7d44d..87574ee4c7c 100644 --- a/superset/commands/report/execute.py +++ b/superset/commands/report/execute.py @@ -1137,6 +1137,8 @@ class BaseReportState: self._report_schedule.dashboard.digest, window_size=window_size, thumb_size=app.config["WEBDRIVER_WINDOW"]["dashboard"], + # A schedule that pins a height gets exactly that height. + trim_to_content=not self._report_schedule.custom_height, ) for url in urls ] diff --git a/superset/utils/screenshot_utils.py b/superset/utils/screenshot_utils.py index 96fe1f32ee2..7e24d7c1e8a 100644 --- a/superset/utils/screenshot_utils.py +++ b/superset/utils/screenshot_utils.py @@ -819,6 +819,47 @@ async (maxWaitMs) => {{ """ +# Nominates the colour of the page behind the dashboard, for trimming a capture. +# It is the opaque background of the innermost box, among the first +# ``.dashboard-grid`` and its ancestors, whose border box covers the whole page +# (``html`` always counts; ``body`` counts whenever ``html`` paints nothing, per +# CSS canvas propagation). The body colour alone is not enough: the app shell +# paints ``body`` one colour and covers it with layout boxes of another. The +# result is only a nomination; the image must confirm it row by row. +PAGE_BACKGROUND_COLOR_JS = r""" +() => { + const grid = document.querySelector('.dashboard-grid'); + if (!grid) { return null; } + const root = document.documentElement; + const pageWidth = root.scrollWidth; + const pageHeight = root.scrollHeight; + const coversPage = (el) => { + const rect = el.getBoundingClientRect(); + return rect.left + window.scrollX <= 0.5 && rect.top + window.scrollY <= 0.5 + && rect.right + window.scrollX >= pageWidth - 0.5 + && rect.bottom + window.scrollY >= pageHeight - 0.5; + }; + const rootStyle = getComputedStyle(root); + const rootPaints = rootStyle.backgroundImage !== 'none' + || !/^rgba\(\d+, \d+, \d+, 0\)$/.test(rootStyle.backgroundColor); + for (let el = grid; el; el = el.parentElement) { + const isCanvas = el === root || (el === document.body && !rootPaints); + if (!isCanvas && !coversPage(el)) { continue; } + const style = getComputedStyle(el); + if (style.backgroundImage !== 'none') { return null; } + const match = /^rgba?\((\d+), (\d+), (\d+)(?:, ([0-9.]+))?\)$/ + .exec(style.backgroundColor); + if (!match) { return null; } + const alpha = match[4] === undefined ? 1 : Number(match[4]); + if (alpha === 0) { continue; } + if (alpha !== 1) { return null; } + return [Number(match[1]), Number(match[2]), Number(match[3])]; + } + return null; +} +""" + + def combine_screenshot_tiles( screenshot_tiles: list[bytes], *, @@ -874,6 +915,144 @@ def combine_screenshot_tiles( raise +def read_page_background_color( + page: "Page", log_context: str | None = None +) -> tuple[int, int, int] | None: + """Read the colour of the page behind the dashboard, or None if unknown. + + Anything other than three integers in 0..255 is treated as unknown, so a + page that cannot be read only costs the trim. + """ + try: + color = page.evaluate(PAGE_BACKGROUND_COLOR_JS) + except (SoftTimeLimitExceeded, ReportExecutionBudgetExceededError): + raise + except Exception: # noqa: BLE001 # an unreadable page only costs the trim + logger.warning( + "Unable to read the page background colour%s", + f" [{log_context}]" if log_context else "", + exc_info=True, + ) + return None + if ( + isinstance(color, list) + and len(color) == 3 + and all( + isinstance(channel, int) + and not isinstance(channel, bool) + and 0 <= channel <= 255 + for channel in color + ) + ): + return color[0], color[1], color[2] + return None + + +def trim_trailing_background_rows( + screenshot: bytes, + background: tuple[int, int, int], + log_context: str | None = None, +) -> bytes: + """Remove the blank band below the content of a PNG capture. + + A row is blank only if every pixel is exactly ``background``. As many + background rows as lead the image (the top margin) are kept below the last + row that differs, so the frame stays symmetric. Every failure, and every + capture with nothing to remove, returns the original bytes object: trimming + only ever errs toward leaving blank space. + """ + try: + with Image.open(io.BytesIO(screenshot)) as probe: + # The integrity check delivery validation applies. Decoding alone + # tolerates a bad checksum or a missing IEND, so re-encoding without + # it would turn bytes validation rejects into bytes it accepts. + probe.verify() + with Image.open(io.BytesIO(screenshot)) as image: + # 8-bit truecolour only: what Chromium emits and the tile combiner + # writes. Pillow reports a 16-bit capture as plain RGB and narrows + # it, so the raw sample format is checked rather than the mode. + raw_modes: list[object] = [tile.args for tile in image.tile] + if ( + raw_modes not in (["RGB"], ["RGBA"]) + or getattr(image, "n_frames", 1) != 1 + or "transparency" in image.info + ): + return screenshot + width, height = image.size + background_row = ( + bytes(background) + (b"\xff" if image.mode == "RGBA" else b"") + ) * width + + def is_background(row: int) -> bool: + return image.crop((0, row, width, row + 1)).tobytes() == background_row + + top_margin = 0 + while top_margin < height and is_background(top_margin): + top_margin += 1 + if top_margin == height: + return screenshot # nothing but background: validation judges it + content_bottom = height + while is_background(content_bottom - 1): + content_bottom -= 1 + kept_height = content_bottom + top_margin + if kept_height >= height: + return screenshot + output = io.BytesIO() + image.crop((0, 0, width, kept_height)).save(output, format="PNG") + logger.info( + "report_capture_trimmed height_px=%s->%s%s", + height, + kept_height, + f" [{log_context}]" if log_context else "", + ) + return output.getvalue() + except (SoftTimeLimitExceeded, ReportExecutionBudgetExceededError): + raise + except Exception: # noqa: BLE001 # an image that cannot be read is left as it is + logger.warning( + "Unable to trim the screenshot to its content%s", + f" [{log_context}]" if log_context else "", + exc_info=True, + ) + return screenshot + + +def trim_report_screenshot_to_content( + page: "Page", + screenshot: bytes, + report_execution_context: ReportExecutionContext | None = None, + log_context: str | None = None, +) -> bytes: + """End a finished report capture at its content instead of the capture window. + + A full-page capture is never shorter than the capture window, so a dashboard + that ends above the window bottom comes with a band of empty page background. + The page nominates the background colour and the image confirms it on every + removed row; when either is unavailable the capture is returned untouched. + """ + context = report_execution_context + delivery_context = ( + context if context is not None and context.validate_for_delivery else None + ) + if delivery_context is not None: + # The blank-capture verdict belongs to the capture as taken: one that + # fails here is never trimmed into one that passes. Returns at once for + # bytes this context already approved (the tiled combined image). + validate_report_screenshot(screenshot, delivery_context) + background = read_page_background_color(page, log_context) + if background is None: + return screenshot + trimmed = trim_trailing_background_rows(screenshot, background, log_context) + if trimmed is screenshot: + return screenshot + if delivery_context is not None: + # Approval is keyed to exact bytes. The original was approved just + # above, so the rows that remain carry its content verdict; the new + # bytes still have to pass the decode checks. + validate_report_screenshot(trimmed, delivery_context, content_validated=True) + return trimmed + + def take_tiled_screenshot( # noqa: C901 page: "Page", element_name: str, diff --git a/superset/utils/screenshots.py b/superset/utils/screenshots.py index 4010df285a6..4c25f2fd34d 100644 --- a/superset/utils/screenshots.py +++ b/superset/utils/screenshots.py @@ -432,11 +432,16 @@ class BaseScreenshot: url: str, digest: str | None, require_complete_capture: bool = False, + trim_to_content: bool = False, ) -> None: self.digest = digest self.url = url self.screenshot = None self.require_complete_capture = require_complete_capture + # Thumbnails are resized against the window aspect ratio, which pads a + # shorter image with black, and are cached under a key that embeds the + # window size, so only reports opt in to ending at the content. + self.trim_to_content = trim_to_content def driver( self, @@ -448,6 +453,7 @@ class BaseScreenshot: "", window_size, require_complete_capture=self.require_complete_capture, + trim_to_content=self.trim_to_content, ) def get_screenshot( @@ -868,6 +874,7 @@ class DashboardScreenshot(BaseScreenshot): window_size: WindowSize | None = None, thumb_size: WindowSize | None = None, require_complete_capture: bool = False, + trim_to_content: bool = False, ) -> None: # per the element above, dashboard screenshots # should always capture in standalone @@ -879,6 +886,7 @@ class DashboardScreenshot(BaseScreenshot): url, digest, require_complete_capture=require_complete_capture, + trim_to_content=trim_to_content, ) self.window_size = window_size or DEFAULT_DASHBOARD_WINDOW_SIZE self.thumb_size = thumb_size or DEFAULT_DASHBOARD_THUMBNAIL_SIZE diff --git a/superset/utils/webdriver.py b/superset/utils/webdriver.py index a5b6b247b03..5d78b5b35e1 100644 --- a/superset/utils/webdriver.py +++ b/superset/utils/webdriver.py @@ -59,6 +59,7 @@ from superset.utils.screenshot_utils import ( STABLE_REPORT_ALL_CHART_HOLDERS_READY_JS, take_tiled_screenshot, TILED_SCREENSHOT_MAX_CAPTURE_ATTEMPTS, + trim_report_screenshot_to_content, validate_report_screenshot, wait_for_stable_readiness, ) @@ -206,11 +207,13 @@ class WebDriverPlaywright(WebDriverProxy): window: WindowSize | None = None, *, require_complete_capture: bool = False, + trim_to_content: bool = False, browser_manager: _PlaywrightBrowserManager | None = None, ) -> None: super().__init__(driver_type, window) self._browser_manager = browser_manager or _browser_manager self._require_complete_capture = require_complete_capture + self._trim_to_content = trim_to_content @staticmethod def auth(user: User, context: BrowserContext) -> BrowserContext: @@ -1421,6 +1424,18 @@ class WebDriverPlaywright(WebDriverProxy): context_suffix, ) + # A full-page capture is never shorter than the capture window, + # so a dashboard that ends above the window bottom comes with a + # band of empty page background. Runs after the capture and its + # validation, for the tiled and both standard branches alike. + if self._trim_to_content and img: + img = trim_report_screenshot_to_content( + page, + img, + report_execution_context=report_execution_context, + log_context=log_context, + ) + except PlaywrightTimeout: raise except PlaywrightError: diff --git a/tests/unit_tests/utils/test_screenshot_trim.py b/tests/unit_tests/utils/test_screenshot_trim.py new file mode 100644 index 00000000000..055389322d9 --- /dev/null +++ b/tests/unit_tests/utils/test_screenshot_trim.py @@ -0,0 +1,389 @@ +# 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. + +"""Trimming a report capture to its content: pixel formats, corruption, approval.""" + +import dataclasses +import io +import logging +import struct +import zlib +from typing import Any +from unittest.mock import MagicMock, patch +from uuid import UUID + +import pytest +from celery.exceptions import SoftTimeLimitExceeded +from PIL import Image +from playwright.sync_api import Error as PlaywrightError + +from superset.utils import screenshot_utils +from superset.utils.report_execution import ( + ReportArtifactKind, + ReportExecutionContext, + ReportExecutionDeadline, +) +from superset.utils.screenshot_utils import ( + get_screenshot_blankness_metrics, + read_page_background_color, + ScreenshotBlankCaptureError, + trim_report_screenshot_to_content, + trim_trailing_background_rows, + validate_report_screenshot, +) + +GREY = (245, 245, 245) +WHITE = (255, 255, 255) +BLUE = (0, 102, 204) +RED = (255, 0, 0) + +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" + + +def _scene( + mode: str = "RGB", + width: int = 40, + height: int = 120, + top: int = 4, + content: int = 30, +) -> Image.Image: + """A grey page with a blue block, ``top`` rows below the top edge.""" + alpha = (255,) if mode == "RGBA" else () + image = Image.new(mode, (width, height), GREY + alpha) + image.paste( + Image.new(mode, (width - 8, content), BLUE + alpha), + (4, top), + ) + return image + + +def _png(image: Image.Image) -> bytes: + output = io.BytesIO() + image.save(output, format="PNG") + return output.getvalue() + + +def _chunk(kind: bytes, data: bytes) -> bytes: + return ( + struct.pack(">I", len(data)) + + kind + + data + + struct.pack(">I", zlib.crc32(kind + data)) + ) + + +def _hand_built_png( + width: int, + height: int, + rows: list[bytes], + *, + bit_depth: int = 8, + color_type: int = 2, + extra_chunk: tuple[bytes, bytes] | None = None, +) -> bytes: + """A PNG of a kind Pillow cannot write, one filter-less row per entry.""" + header = struct.pack(">IIBBBBB", width, height, bit_depth, color_type, 0, 0, 0) + pixels = b"".join(b"\x00" + row for row in rows) + return ( + PNG_SIGNATURE + + _chunk(b"IHDR", header) + + (_chunk(*extra_chunk) if extra_chunk else b"") + + _chunk(b"IDAT", zlib.compress(pixels)) + + _chunk(b"IEND", b"") + ) + + +def _sixteen_bit_rgb() -> bytes: + """Every sample narrows to grey, but row 5 differs and row 30 differs only in + the low byte of each sample.""" + rows = [b"\xf5\x00" * 3 * 20 for _ in range(40)] + rows[5] = b"\x00\x66" * 3 * 20 + rows[30] = b"\xf5\x01" * 3 * 20 + return _hand_built_png(20, 40, rows, bit_depth=16) + + +def _eight_bit_rgb_with_transparency() -> bytes: + rows = [bytes(GREY) * 20 for _ in range(40)] + rows[5] = bytes(BLUE) * 20 + return _hand_built_png( + 20, 40, rows, extra_chunk=(b"tRNS", struct.pack(">HHH", 1, 2, 3)) + ) + + +def _animated() -> bytes: + output = io.BytesIO() + _scene().save(output, "PNG", save_all=True, append_images=[_scene(top=8)]) + return output.getvalue() + + +def _flipped_idat_checksum(png: bytes) -> bytes: + start = png.index(b"IDAT") + length = struct.unpack(">I", png[start - 4 : start])[0] + crc_at = start + 4 + length + corrupted = bytearray(png) + corrupted[crc_at] ^= 0xFF + return bytes(corrupted) + + +def _without_iend(png: bytes) -> bytes: + return png[: png.rindex(b"IEND") - 4] + + +def _context() -> ReportExecutionContext: + return ReportExecutionContext( + execution_id=UUID("084e7ee6-5557-4ecd-9632-b7f39c9ec524"), + report_schedule_id=11, + dashboard_id=805, + expected_chart_count=1, + deadline=ReportExecutionDeadline( + total_seconds=240, + started_at=0, + _clock=lambda: 0, + ), + capture_reserve_seconds=60, + delivery_reserve_seconds=120, + cleanup_reserve_seconds=30, + ) + + +def _page(color: Any = (245, 245, 245)) -> MagicMock: + page = MagicMock() + page.evaluate.return_value = None if color is None else list(color) + return page + + +def _sparse_capture() -> bytes: + """Mostly empty and tall: approved by regions, blank by the whole-image metrics.""" + image = Image.new("RGB", (800, 8000), GREY) + for row in range(0, 5001, 1000): + for column in range(0, 800, 8): + image.putpixel((column, row), BLUE) + return _png(image) + + [email protected]("mode", ["RGB", "RGBA"]) +def test_trim_removes_only_the_excess_background_rows(mode: str) -> None: + scene = _scene(mode) + result = trim_trailing_background_rows(_png(scene), GREY) + + with Image.open(io.BytesIO(result)) as trimmed: + assert trimmed.size == (40, 38) + assert trimmed.mode == mode + assert trimmed.tobytes() == scene.crop((0, 0, 40, 38)).tobytes() + + +def _bottom_rows_red() -> Image.Image: + image = _scene() + image.paste(Image.new("RGB", (40, 20), RED), (0, 100)) + return image + + +def _rgba_with_translucent_corner() -> Image.Image: + image = _scene("RGBA") + image.putpixel((39, 119), GREY + (254,)) + return image + + [email protected]( + ("image", "background"), + [ + pytest.param(_scene(height=34), GREY, id="content_reaches_the_bottom"), + pytest.param(_scene(height=38), GREY, id="margin_already_symmetric"), + pytest.param(Image.new("RGB", (40, 120), GREY), GREY, id="all_background"), + pytest.param(_bottom_rows_red(), GREY, id="uniform_but_not_the_background"), + pytest.param(_scene(), WHITE, id="other_background_colour"), + pytest.param(_rgba_with_translucent_corner(), GREY, id="alpha_254"), + ], +) +def test_trim_returns_the_same_object_when_nothing_is_removed( + caplog: pytest.LogCaptureFixture, + image: Image.Image, + background: tuple[int, int, int], +) -> None: + source = _png(image) + name = screenshot_utils.logger.name + with caplog.at_level(logging.DEBUG, logger=name): + result = trim_trailing_background_rows(source, background) + + assert result is source + assert [record for record in caplog.records if record.name == name] == [] + + [email protected]( + "source", + [ + pytest.param(_png(_scene().convert("P")), id="palette"), + pytest.param(_png(Image.new("I;16", (40, 120))), id="sixteen_bit_grey"), + pytest.param(_png(Image.new("1", (40, 120))), id="bilevel"), + pytest.param(_sixteen_bit_rgb(), id="sixteen_bit_rgb"), + pytest.param(_eight_bit_rgb_with_transparency(), id="transparency_chunk"), + pytest.param(_animated(), id="animated"), + ], +) +def test_trim_leaves_unsupported_pixel_formats_untouched(source: bytes) -> None: + assert trim_trailing_background_rows(source, GREY) is source + + [email protected]( + "source", + [ + pytest.param(_flipped_idat_checksum(_png(_scene())), id="bad_checksum"), + pytest.param(_without_iend(_png(_scene())), id="missing_iend"), + pytest.param(b"not a png", id="not_an_image"), + ], +) +def test_trim_leaves_corrupt_bytes_untouched(source: bytes) -> None: + assert trim_trailing_background_rows(source, GREY) is source + + +def test_trim_survives_a_decompression_bomb( + monkeypatch: pytest.MonkeyPatch, +) -> None: + source = _png(_scene()) + monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100) + + assert trim_trailing_background_rows(source, GREY) is source + + [email protected]("source_of_deadline", ["image_decode", "page_read"]) +def test_report_deadlines_pass_through(source_of_deadline: str) -> None: + source = _png(_scene()) + page = _page() + if source_of_deadline == "page_read": + page.evaluate.side_effect = SoftTimeLimitExceeded() + with pytest.raises(SoftTimeLimitExceeded): + trim_report_screenshot_to_content(page, source) + return + + with patch.object( + screenshot_utils.Image, "open", side_effect=SoftTimeLimitExceeded() + ): + with pytest.raises(SoftTimeLimitExceeded): + trim_trailing_background_rows(source, GREY) + + +def test_page_background_read_returns_the_colour() -> None: + assert read_page_background_color(_page([245, 245, 245])) == (245, 245, 245) + + +def test_page_background_read_rejects_anything_else() -> None: + for unusable in ( + None, + "rgb(1, 2, 3)", + [1, 2], + [1, 2, 3.0], + [True, 0, 0], + [1, 2, 256], + ): + assert read_page_background_color(_page(unusable)) is None + + for error in (RuntimeError("boom"), PlaywrightError("closed")): + page = MagicMock() + page.evaluate.side_effect = error + assert read_page_background_color(page) is None + + +def test_trimmed_capture_stays_approved_for_delivery() -> None: + source = _sparse_capture() + context = _context() + validate_report_screenshot(source, context, content_validated=True) + + result = trim_report_screenshot_to_content( + _page(), source, report_execution_context=context + ) + + with Image.open(io.BytesIO(result)) as trimmed: + assert trimmed.size == (800, 5001) + assert context.artifact_was_validated(result, ReportArtifactKind.SCREENSHOT) + validate_report_screenshot(result, context) + assert context.capture_rejection_reasons == () + + +def test_unapproved_capture_earns_no_exemption() -> None: + context = _context() + page = _page() + + with pytest.raises(ScreenshotBlankCaptureError): + trim_report_screenshot_to_content( + page, _sparse_capture(), report_execution_context=context + ) + + assert "blank_final_image" in context.capture_rejection_reasons + page.evaluate.assert_not_called() + + +def test_capture_rejected_untrimmed_stays_rejected() -> None: + image = Image.new("RGB", (1600, 2000), GREY) + image.paste(Image.new("RGB", (1568, 400), (227, 227, 227)), (16, 16)) + source = _png(image) + assert get_screenshot_blankness_metrics(source).is_blank + assert not get_screenshot_blankness_metrics( + trim_trailing_background_rows(source, GREY) + ).is_blank + + with pytest.raises(ScreenshotBlankCaptureError): + trim_report_screenshot_to_content( + _page(), source, report_execution_context=_context() + ) + + +def test_blank_capture_is_not_rescued() -> None: + source = _png(Image.new("RGB", (800, 2000), GREY)) + + with pytest.raises(ScreenshotBlankCaptureError): + trim_report_screenshot_to_content( + _page(), source, report_execution_context=_context() + ) + + +def test_corrupt_capture_is_rejected_not_trimmed() -> None: + source = _flipped_idat_checksum(_png(_scene())) + context = _context() + + with pytest.raises(ScreenshotBlankCaptureError): + trim_report_screenshot_to_content( + _page(), source, report_execution_context=context + ) + assert "invalid_image" in context.capture_rejection_reasons + + assert trim_report_screenshot_to_content(_page(), source) is source + + +def test_capture_without_a_delivery_context_is_trimmed_unvalidated() -> None: + context = _context() + for report_context in ( + None, + dataclasses.replace(context, validate_for_delivery=False), + ): + result = trim_report_screenshot_to_content( + _page(), + _png(_scene()), + report_execution_context=report_context, + ) + + with Image.open(io.BytesIO(result)) as trimmed: + assert trimmed.size == (40, 38) + if report_context is not None: + assert not report_context.artifact_was_validated( + result, ReportArtifactKind.SCREENSHOT + ) + + +def test_no_page_background_leaves_the_capture_alone() -> None: + source = _png(_scene()) + + assert trim_report_screenshot_to_content(_page(None), source) is source
