Skip to content

fix(reports): detect perceptually blank screenshots - #44034

Merged
rebenitez1802 merged 8 commits into
apache:masterfrom
fitzee:fitzee/detect-perceptually-blank-reports
Sep 9, 2026
Merged

rebenitez1802 merged 8 commits into
apache:masterfrom
fitzee:fitzee/detect-perceptually-blank-reports

Conversation

@fitzee

@fitzee fitzee commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Hardens scheduled report screenshot validation after a real blank PDF bypassed the existing exact-color heuristic. The incident artifact contained multiple near-white backgrounds, so no single RGB value reached the old 99.5% threshold even though the page contained no meaningful content.

This change:

  • evaluates blankness at 256px and 1024px sampling scales using luminance variance, grayscale entropy, mean luminance, and exact-color dominance;
  • checks DOM terminal state before rejecting output, allowing legitimate empty/error reports while validating rendered chart content;
  • retries perceptually blank standard and tiled captures;
  • bounds repaint waits against the report deadline and preserves budget/Celery timeout exceptions;
  • validates the final combined tiled image only when contentful chart tiles were captured;
  • fails scheduled reports after repeated blank captures rather than delivering the final rejected image;
  • emits validation metrics at INFO; and
  • preserves lenient non-report thumbnail behavior.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable; backend screenshot validation and logging only.

TESTING INSTRUCTIONS

pytest -q tests/unit_tests/utils/test_screenshot_utils.py tests/unit_tests/utils/webdriver_test.py::TestStandardScreenshotValidation

Coverage includes:

  • pure-white, multi-tone RGB 245, and neighboring RGB 239 blank captures;
  • readable empty-state text and DOM-terminal empty/error exemptions;
  • sparse content and tall-dashboard fixtures;
  • multi-scale classifier behavior;
  • standard and tiled retry recovery and fail-closed exhaustion;
  • real-PNG combined-image rejection and empty-state acceptance;
  • bounded repaint timeout and Celery soft-time-limit propagation; and
  • command-level prevention of PDF generation and delivery after capture rejection.

Local focused result: 82 passed. Ruff 0.9.7 formatting/check and mypy passed. The real incident PDF raster is classified blank with dominant ratio 0.76750, near-white ratio 1.0, mean luminance 253.61, standard deviation 2.53, and entropy 0.803.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #d71270

Actionable Suggestions - 0
Additional Suggestions - 3
  • superset/utils/webdriver.py - 1
    • Dashboard blank false-positive · Line 255-257
      For dashboards, `content_expected` is just `bool(expected_chart_count)` (set to `len(dashboard.slices)` in `execute.py`), so any dashboard with ≥1 slice gets blankness validation on the full-page `standalone` screenshot. The tiled path (`screenshot_utils.py:1046`) additionally requires `contentful_chart_holders > 0` before flagging blank. A sparse dashboard with a few small charts on a large white canvas can exceed the near-white threshold, trigger 3 re-captures, then raise `ScreenshotBlankCaptureError` and fail the report. Consider gating on contentful chart holders here too.
  • superset/utils/screenshot_utils.py - 2
    • Combined blank check over-rejects · Line 1210-1227
      The combined blank check raises `ScreenshotBlankCaptureError` whenever the combined image is blank, but it is not gated on contentful charts. This contradicts the per-tile logic (lines 1046-1048) and `test_uniform_tile_without_visible_charts_is_allowed`, which deliberately allow blank tiles when `contentful_chart_holders == 0`. A dashboard whose charts are all virtualized/empty would now fail the report where it previously succeeded. Gate the raise on observed contentful charts.
    • Misleading function name · Line 201-205
      `is_screenshot_nearly_uniform` now returns `metrics.is_blank`, which is `exact_uniform OR perceptually_blank`. A two-tone near-white image with `dominant_ratio` 0.85 now returns True (see `test_two_tone_near_white_png_is_blank`), so the name no longer matches the behavior. Consider renaming it to something like `is_screenshot_blank` to avoid misleading callers — and update all callers (including the unit tests in test_screenshot_utils.py) consistently.
Review Details
  • Files reviewed - 4 · Commit Range: 2798700..2798700
    • superset/utils/screenshot_utils.py
    • superset/utils/webdriver.py
    • tests/unit_tests/utils/test_screenshot_utils.py
    • tests/unit_tests/utils/webdriver_test.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

@netlify

netlify Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit db94b2e
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa0a6413940580008caa2bd
😎 Deploy Preview https://deploy-preview-44034--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 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.19626% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.90%. Comparing base (c510946) to head (0c283b8).
⚠️ Report is 17 commits behind head on master.

Files with missing lines Patch % Lines
superset/utils/webdriver.py 91.17% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #44034      +/-   ##
==========================================
+ Coverage   79.88%   79.90%   +0.02%     
==========================================
  Files        2915     2916       +1     
  Lines      170737   170845     +108     
  Branches    39566    39578      +12     
==========================================
+ Hits       136391   136519     +128     
+ Misses      31829    31811      -18     
+ Partials     2517     2515       -2     
Flag Coverage Δ
hive 37.61% <29.90%> (-0.02%) ⬇️
mysql 57.36% <29.90%> (-0.03%) ⬇️
postgres 57.39% <29.90%> (-0.03%) ⬇️
presto 39.53% <29.90%> (-0.02%) ⬇️
python 84.35% <97.19%> (+0.05%) ⬆️
sqlite 57.08% <29.90%> (-0.03%) ⬇️
unit 75.50% <97.19%> (+0.16%) ⬆️

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 github-actions Bot added the doc Namespace | Anything related to documentation label Sep 9, 2026
…ptually-blank-reports

# Conflicts:
#	superset/utils/webdriver.py
@pull-request-size pull-request-size Bot added size/XL and removed size/L labels Sep 9, 2026
@pull-request-size pull-request-size Bot added size/L and removed size/XL labels Sep 9, 2026
Comment thread superset/utils/screenshot_utils.py Outdated
Comment on lines +186 to +190
perceptually_blank = (
near_white_ratio >= SCREENSHOT_BLANK_NEAR_WHITE_PIXEL_RATIO
and luminance_stddev <= SCREENSHOT_BLANK_MAX_LUMINANCE_STDDEV
and entropy <= SCREENSHOT_BLANK_MAX_ENTROPY
)

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 perceptual rule classifies any image with fewer than 0.5% dark pixels as blank when its remaining pixels are near-white, rejecting legitimate sparse charts or thin text. [incorrect condition logic]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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

**Path:** superset/utils/screenshot_utils.py
**Line:** 186:190
**Comment:**
	*Incorrect Condition Logic: The perceptual rule classifies any image with fewer than 0.5% dark pixels as blank when its remaining pixels are near-white, rejecting legitimate sparse charts or thin text.

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 Author

Choose a reason for hiding this comment

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

Addressed in 6a9011b. Blankness is no longer decided by near-white coverage alone: the revised detector requires low luminance variance and low entropy at both 256px and 1024px sampling scales, plus either high mean luminance or exact uniformity. Capture rejection is also DOM-state-aware, so terminal empty/error states are accepted. Added realistic readable empty-state, sparse-content, tall-report, and RGB 239 background regression cases.

Comment on lines +324 to +333
page.bring_to_front()
page.evaluate(
"""() => {
window.scrollBy(0, 1);
window.scrollBy(0, -1);
return new Promise(resolve => requestAnimationFrame(
() => requestAnimationFrame(resolve)
));
}"""
)

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: page.evaluate() waits for two animation frames without a timeout, so a wedged page can block standard screenshot retries beyond the report deadline. [api mismatch]

Assessment: 🟠 Major · 🔁 Occurrence: Sometimes

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

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

**Path:** superset/utils/webdriver.py
**Line:** 324:333
**Comment:**
	*Api Mismatch: `page.evaluate()` waits for two animation frames without a timeout, so a wedged page can block standard screenshot retries beyond the report deadline.

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 Author

Choose a reason for hiding this comment

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

Addressed in 6a9011b. The standard repaint no longer returns a Promise from page.evaluate(). It schedules a completion flag and waits with page.wait_for_function() using a five-second timeout capped by the remaining report deadline and post-capture reserve. Playwright repaint failures are logged, while report-budget and Celery soft-time-limit exceptions propagate. Added bounded-timeout and SoftTimeLimitExceeded regression tests.

@pull-request-size pull-request-size Bot added size/XL and removed size/L labels Sep 9, 2026
@bito-code-review

Copy link
Copy Markdown
Contributor

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

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

@rebenitez1802 rebenitez1802 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.

Approve — thorough, well-tested fix that closes the reported multi-tone blank-PDF incident. I verified the incident raster (stddev 2.53 / entropy 0.803 / mean 253.61) now classifies blank via the new path, CI is green, and the security model is untouched. I ran a multi-lens review (correctness / control-flow / false-positive / tests / perf) with adversarial verification of each finding — nothing blocking.

Three non-blocking medium items left inline for you to decide on; they all revolve around the fail-closed path's false-positive surface (legit sparse/light reports) and its test coverage. There are also a few low nits I intentionally kept out of the PR (repaint except type differs between the two paths; standard path fails-open on a content-probe error while the tiled path fails-closed; dark-theme blanks aren't detected; getcolors(maxcolors=pixel_count) drops the old fast-bail; the retry/repaint loop is duplicated across the two paths; dataclasses.replace for the frozen-dataclass rebuild) — happy to drop those in a follow-up comment if useful. Your call on all of it.

luminance_stddev <= SCREENSHOT_BLANK_MAX_LUMINANCE_STDDEV
and entropy <= SCREENSHOT_BLANK_MAX_ENTROPY
)
perceptually_blank = low_information and (

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.

🟡 Medium (non-blocking — your call): this fail-closed rejection can deterministically fail a narrow class of legitimate light/sparse reports, with no operator opt-out. perceptually_blank = (stddev≤8 and entropy≤1.5) and (mean≥250 or dominant≥0.995) — common charts survive (line/scatter with axes, Big Number, bordered tables, all verified), but genuinely sparse low-chrome near-white content (a sparse scatter with minimal axes, a borderless text table, a very-light pastel area chart) reads blank at both sample scales → 3 retries over identical pixels → ScreenshotBlankCaptureError → ReportScheduleScreenshotFailedError on every run, and there's no config flag to turn perceptual rejection off. Worth considering a config/feature flag as a safety valve, and/or gating on a resolution-independent ink fraction rather than the DPI-sensitive global stddev/entropy. Not blocking the approval.

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.

Addressed the false-positive surface in 0c283b8 without adding a global opt-out. The classifier now measures structural edge density at both sampling scales, so light/thin chart and table marks prevent a blank classification even when global luminance variance and entropy remain low. The actual incident raster remains classified blank (stddev=2.525, entropy=0.801, structural_edge_ratio=0.00000). I’m intentionally not adding a bypass flag because disabling validation would restore silent blank delivery; the more targeted classifier correction preserves fail-closed behavior.

log_context=log_context,
)

if report_execution_context and contentful_tiles_captured:

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.

🟡 Medium (non-blocking): the combined-image check gates only on contentful_tiles_captured, not on what fraction of the page is actually content. A tall / sparse-ink dashboard (a few real charts among empty / spacer / markdown tiles, or many low-chrome charts) can wash out at the 1024px downsample so the combined image scores blank and raises here — even though every tile individually passed its per-tile check. This is new behavior (base master just returned the combined image). Consider basing the combined decision on aggregate non-near-white ink (or on the per-tile results already computed), or making the combined check advisory/log-only once tiles have individually passed. Your call.

@fitzee fitzee Sep 9, 2026 •

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 0c283b8. Once contentful tiles have individually passed capture validation, the combined-image classification is now advisory/log-only (report_capture_blank_combined_retained) rather than a second rejection gate. This avoids a 1024px composite downsample overriding stronger per-tile evidence on tall or sparse dashboards.


assert is_blank is False

def test_tall_sparse_report_with_content_is_not_blank(self):

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.

🟡 Medium (non-blocking): this "sparse" test passes only because its strokes are thick and black — swap them to thin/light and it flips to is_blank=True. Together with _create_chart_like_tile (a dense ~60%-colored block), the suite has no fixture asserting that a realistic light thin-stroke line/scatter or a sparse table at report resolution is not blank — so the false-positive class flagged on screenshot_utils.py line 190 would ship green. Worth adding light thin-stroke line/scatter + sparse-table fixtures at ~3000×1200 (and pixel_density=2) that assert is_blank is False, and using them to calibrate the thresholds. Your call.

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.

Addressed in 0c283b8. Added 3000x1200 fixtures for a light, thin-stroke line/scatter-style chart and a sparse light table. Both exercise the new structural-edge signal and assert non-blank classification. The actual customer blank raster was also rechecked and still classifies blank.

@fitzee

fitzee commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

@rebenitez1802 Thanks — I went through the remaining low nits as well.

Implemented in 0c283b88d8:

  • aligned tiled repaint handling with the standard path by catching Playwright errors while explicitly preserving Celery SoftTimeLimitExceeded propagation;
  • switched the frozen execution-context test rebuild to dataclasses.replace;
  • made combined-image blankness advisory after individually validated contentful tiles;
  • added structural-edge calibration and high-resolution light/thin chart and sparse-table coverage.

Intentionally left unchanged:

  • standard content-probe failure remains fail-open because rejecting when DOM state itself cannot be read would create an unbounded false-positive class; the probe failure is logged;
  • multi-tone dark-theme blank detection is outside this incident’s evidence. Exactly uniform dark captures are already caught by the dominant-color rule; broader dark heuristics should be calibrated against a real failure raster;
  • getcolors(maxcolors=pixel_count) operates only on bounded 256/1024 samples and is needed for the diagnostic dominant ratio, so the old 256-color fast-bail is not applicable;
  • the standard/tiled retry loops stay separate because tiled capture has clip positioning, per-tile holder state, thumbnail retention, and combination semantics that the standard path does not share;
  • is_screenshot_nearly_uniform remains as a compatibility wrapper; production decisions use get_screenshot_blankness_metrics, whose name reflects the broader behavior.

Validation: 129 affected utility tests pass; Ruff and mypy pass. The actual incident raster remains classified blank with structural_edge_ratio=0.00000.

@rebenitez1802 rebenitez1802 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 🎉 Re-reviewed 0c283b88. The structural-edge signal resolves the sparse/light false-positive cleanly (realistic charts with any chrome now read non-blank, while the incident raster and hard/smooth near-white blanks stay caught), the combined-image check is now advisory, and the exception/SoftTimeLimitExceeded handling and dataclasses.replace cleanups look good. I also went through your deferrals — all reasonable; agreed that keeping getcolors at full enumeration is correct (a 256-colour fast-bail would actually miss high-dominant near-white blanks), and that a dark-theme heuristic should wait for a real failure raster.

Non-blocking nit for whenever: the new except SoftTimeLimitExceeded: raise guards the outer handler, but the two inner except Exception blocks around the page.evaluate calls (screenshot_utils.py ~1125 and ~1333) can still swallow a soft-timeout that fires during those windows — a one-line except SoftTimeLimitExceeded: raise before each would fully close the propagation guarantee. Not a blocker. Nice work.

@rebenitez1802
rebenitez1802 merged commit 97329bb into apache:master Sep 9, 2026
75 checks passed
@bito-code-review

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped – PR Already Merged

Bito scheduled an automatic review for this pull request, but the review was skipped because this PR was merged before the review could be run.
No action is needed if you didn't intend to review it. To get a review, you can type /review in a comment and save it

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 size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants