Repository navigation
fix(reports): validate final capture artifacts before delivery - #44465
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #44465 +/- ##
==========================================
+ Coverage 80.73% 80.75% +0.01%
==========================================
Files 2944 2944
Lines 176476 176609 +133
Branches 40932 40958 +26
==========================================
+ Hits 142485 142619 +134
+ Misses 31313 31306 -7
- Partials 2678 2684 +6
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
| context_suffix, | ||
| exc_info=True, | ||
| ) | ||
| raise ScreenshotBlankCaptureError( |
There was a problem hiding this comment.
for_delivery=False doesn't bypass this, so the CSV/XLSX/TEXT query-context bootstrap still passes the execution context and a flaky content-state evaluate now fails the tabular report (previously has_rendered_content=False and it continued). That seems to contradict "retaining the existing browser readiness/capture contract" for bootstrap captures.
There was a problem hiding this comment.
Fixed in 857769f. Bootstrap-only captures no longer receive the delivery-validation context, preserving the existing CSV/XLSX/TEXT query-context bootstrap behavior.
| except Exception as ex: | ||
| context.reject_capture("invalid_image") | ||
| raise ScreenshotBlankCaptureError("Unable to validate screenshot bytes") from ex | ||
| if blankness.is_blank: |
There was a problem hiding this comment.
Both capture paths accept a blank image when no holder has rendered content (is_blank = has_rendered_content and ...), but this gate then rejects the same bytes with no retry. Is failing an empty/error-only chart or dashboard on the first attempt intended?
There was a problem hiding this comment.
Fixed in 857769f. A blank capture is approved as a screenshot when browser state positively establishes that no holder rendered content, so empty/error-only results pass the final gate without weakening validation of other blank captures.
| try: | ||
| with Image.open(io.BytesIO(screenshot)) as image: | ||
| image.verify() | ||
| blankness = get_screenshot_blankness_metrics(screenshot) |
There was a problem hiding this comment.
Could we make pixel-decoding failures propagate here? Image.verify() checks the PNG structure and CRCs, but it does not decode the IDAT stream. get_screenshot_blankness_metrics() then catches a decoding OSError and returns is_blank=False, so these bytes are approved below. I reproduced this with a PNG whose IDAT payload was corrupted and whose CRC was recomputed: verify() passed, convert("RGB").load() raised OSError: broken data stream, and validate_report_screenshot() still called approve_artifact(). For this final delivery gate, a decode failure should reject the artifact as invalid_image, for example by letting the helper surface decode errors to this caller.
There was a problem hiding this comment.
Fixed in 857769f. Final screenshot validation now propagates decoding failures from the blankness helper and rejects the artifact as invalid_image. A regression test covers a PNG whose IDAT payload is corrupted with a recomputed CRC.
EnxDev
left a comment
There was a problem hiding this comment.
I rechecked the latest commit: the strict decode check and the artifact-type separation address my two earlier comments, and their regression tests pass. I found three remaining cases below while following captures through to final validation. I ran 148 selected helper tests successfully in an isolated harness, plus focused reproductions with mocked browser state; live Superset capture testing is still outstanding.
EnxDev
left a comment
There was a problem hiding this comment.
The three fixes from the previous pass check out: tiled acceptance survives final validation, bootstrap captures retain their deadline, and off-screen errors appear in the final diagnostics. The 154 selected helper tests pass in the isolated harness, and the follow-up reproductions for those cases pass too. I found one remaining byte-validation gap in the standard capture approval path below.
| ) | ||
| if not is_blank: | ||
| if blankness.is_blank: | ||
| report_execution_context.approve_artifact( |
There was a problem hiding this comment.
Could this call validate_report_screenshot(image, report_execution_context, content_validated=True) before recording approval, as the tiled path does? A terminal empty/error capture reaches this branch without running Image.verify(), and the cached hash then makes every later validator return early.
I reproduced this by flipping one byte of the IDAT checksum in an otherwise valid blank PNG. The pixel metrics still classify it as blank, but Image.verify() raises SyntaxError: broken PNG file (bad header checksum in b'IDAT'). The shared validator and tiled path reject those bytes; _get_validated_screenshot() followed by final validation accepts them. Using the shared validator here would preserve the empty/error exception while still checking the file's integrity.
There was a problem hiding this comment.
Fixed in 43cde6c. Standard empty/error-state captures use the shared validator before recording approval, preserving the content-state exception without bypassing file-integrity checks. Regression tests corrupt an IDAT checksum for both chart and dashboard captures and verify rejection, no approval, and rejection again at the final gate.
There was a problem hiding this comment.
Code Review Agent Run #b4ab75
Actionable Suggestions - 5
-
docs/admin_docs/configuration/alerts-reports.mdx - 2
- Ambiguous terminal wording · Line 490-493
- Triplicated disclaimer text · Line 495-501
-
tests/unit_tests/utils/test_report_execution.py - 2
- Missing test docstrings · Line 49-88
- Missing local type annotation · Line 189-189
-
tests/unit_tests/utils/test_screenshot_utils.py - 1
- Missing test docstring · Line 99-99
Additional Suggestions - 6
-
docs/admin_docs/configuration/alerts-reports.mdx - 1
-
Contradictory logo claims · Line 495-497This reads as contradicting lines 486-487 ('A small label or logo does not override a blank classification'): here a 'large enough title or logo' exceeds the thresholds. Both can be true on a size continuum, but the criterion (content amount vs threshold) is never stated, so operators cannot predict which applies to their dashboard. Please clarify the distinguishing factor. It looks like the underlying threshold logic in `screenshot_utils.py` supports a continuum, but the doc text alone is ambiguous.
-
-
superset/utils/webdriver.py - 2
-
Obscure nested blank check · Line 375-375Inside `if not is_blank:`, the added `if blankness.is_blank:` is reachable only when `has_rendered_content` is False (given `is_blank = has_rendered_content and blankness.is_blank`), i.e. blank pixels over no rendered chart content. The bare re-test reads like an independent check; a comment naming that state would prevent future misreading. Behavior is correct as written.
-
Duplicated semantic_success ternary · Line 768-770The ternary `diagnostics.semantic_success if element_name == "standalone" else None` is repeated verbatim at lines 518-522, 689-691, and 768-770 of `_wait_for_charts_ready`. Extracting a small helper keeps the standalone-only gating rule in one place as `ChartHolderDiagnostics` semantics evolve, and prevents one site from drifting when the policy changes.
-
-
superset/utils/screenshot_utils.py - 2
-
Magic number threshold · Line 255-255The `16` channel-spread tolerance for the neutral-grey blank check is a bare literal, while the sibling luminance threshold is a named constant (`SCREENSHOT_BLANK_MIN_NEUTRAL_MEAN_LUMINANCE`). Extract it to a module constant so the two thresholds stay consistent and tunable together.
-
Misleading diagnostics log · Line 1599-1605When `observed_holder_states` is non-empty, final diagnostics are built only from recorded rendered/empty/error states (`_record_visible_holder_states` state_priority). Holders that stayed virtualized are dropped, so `report_readiness_ready` always logs `virtualized_holders=0`, `unready_holders=0` and undercounts `mounted_holders`, misrepresenting the capture.
-
-
tests/unit_tests/utils/test_screenshot_utils.py - 1
-
Missing test annotations/docstrings · Line 192-295The eight new test methods in `TestScreenshotBlankDetection` omit `-> None` return annotations and docstrings. BITO.md adaptive rules 7819/12148 require explicit return type hints and docstrings on all new test functions. Note the repo mypy config relaxes `disallow_untyped_defs` for `tests.*` and 85 of 93 existing test defs are untyped, so this is an org-standard consistency gap rather than a CI failure.
-
Review Details
-
Files reviewed - 11 · Commit Range:
cd66f67..43cde6c- docs/admin_docs/configuration/alerts-reports.mdx
- superset/commands/report/execute.py
- superset/utils/report_execution.py
- superset/utils/screenshot_utils.py
- superset/utils/webdriver.py
- tests/integration_tests/reports/commands/execute_dashboard_report_tests.py
- tests/integration_tests/reports/commands_tests.py
- tests/unit_tests/commands/report/execute_test.py
- tests/unit_tests/utils/test_report_execution.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
| Chart error and empty states are terminal for readiness, but a rendered error is | ||
| not successful chart data. Logs distinguish `rendered_holders`, `empty_holders`, | ||
| `error_holders` and `semantic_success`; `report_semantic_status` warns when a | ||
| completed capture includes terminal chart errors. |
There was a problem hiding this comment.
'Chart error and empty states are terminal for readiness' is ambiguous: 'terminal' suggests capture fails, but lines 498-499 say recognized terminal chart errors are 'capture-ready and may be delivered with a warning'. Code agrees errors only warn (report_semantic_status at screenshot_utils.py:1642-1659). Please reword to say the readiness wait stops without retry, not that delivery is blocked.
Code Review Run #b4ab75
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
There was a problem hiding this comment.
Fixed in f4ef4cc. The docs explicitly say recognized empty/error states satisfy the readiness wait and do not themselves trigger capture retries or block delivery. Error-state delivery is distinguished from successful chart data.
There was a problem hiding this comment.
The suggestion provided by the reviewer is appropriate. It correctly identifies that the term 'terminal' in the documentation could be misinterpreted as a complete capture failure, whereas the code indicates that terminal chart errors are still considered capture-ready and are handled with a warning. Updating the wording to clarify that the readiness wait stops without retry, rather than blocking delivery, improves the accuracy of the documentation.
| This is not a guarantee that every delivered image contains useful data. A large | ||
| enough title or logo can still exceed the detector's content thresholds while the | ||
| rest of the page is incomplete; removing the sparse-content override does not | ||
| solve that general limitation. Recognized terminal chart errors are capture-ready | ||
| and may be delivered with a warning, provided the | ||
| image passes visual validation. Operators requiring all charts to contain data | ||
| must not treat this policy as that guarantee. The strict invariant is that an |
There was a problem hiding this comment.
The same 'not a guarantee' caveat is stated three times in the added text: lines 484-485 ('Detection is a heuristic, not a guarantee...'), 495-496 ('This is not a guarantee that every delivered image contains useful data'), and 500-501 ('Operators requiring all charts to contain data must not treat this policy as that guarantee'). Consolidate into one statement to keep the troubleshooting section scannable.
Code Review Run #b4ab75
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
There was a problem hiding this comment.
Fixed in f4ef4cc. Consolidated the heuristic limitation into one paragraph, preserving the fail-closed invariant and explaining that a sufficiently large title/logo can exceed the content threshold without a special exemption.
There was a problem hiding this comment.
The suggestion to consolidate the disclaimer text is appropriate. The updated text in the provided diff successfully merges the three separate caveats into a single, cohesive paragraph, which improves the readability and scannability of the troubleshooting section.
docs/admin_docs/configuration/alerts-reports.mdx
+Final screenshot bytes are validated independently of the capture implementation.
+PDF delivery requires evidence that the exact PDF was assembled from validated
+images during this execution. Capture rejection remains sticky for the execution;
+substituting another attachment cannot clear it. Detection is a heuristic, not a
+guarantee that every chart contains correct data. Uniform fills are rejected
+regardless of colour or theme. A small label or logo does not override a blank
+classification. Extremely sparse legitimate output can therefore be rejected;
+a solid-fill KPI without visible structure has no pixel-only exemption.
| def test_chart_holder_diagnostics_separate_terminal_errors_from_success() -> None: | ||
| diagnostics = ChartHolderDiagnostics.from_holder_states( | ||
| [ | ||
| {"chartId": "1", "state": "rendered"}, | ||
| {"chartId": "2", "state": "rendered"}, | ||
| {"chartId": "3", "state": "empty"}, | ||
| {"chartId": "4", "state": "error"}, | ||
| {"chartId": "5", "state": "virtualized"}, | ||
| ] | ||
| ) | ||
|
|
||
| assert diagnostics.mounted_holders == 5 | ||
| assert diagnostics.ready_holders == 5 | ||
| assert diagnostics.rendered_holders == 2 | ||
| assert diagnostics.empty_holders == 1 | ||
| assert diagnostics.error_holders == 1 | ||
| assert diagnostics.virtualized_holders == 1 | ||
| assert diagnostics.unready_holders == 0 | ||
| assert diagnostics.semantic_success is False | ||
|
|
||
|
|
||
| def test_chart_holder_diagnostics_count_unready_holders() -> None: | ||
| diagnostics = ChartHolderDiagnostics.from_holder_states( | ||
| [ | ||
| {"chartId": "1", "state": "rendered"}, | ||
| {"chartId": "2", "state": "waiting_on_database"}, | ||
| {"chartId": "3", "state": "nothing_mounted"}, | ||
| ] | ||
| ) | ||
|
|
||
| assert diagnostics.ready_holders == 1 | ||
| assert diagnostics.unready_holders == 2 | ||
| assert diagnostics.semantic_success is False | ||
|
|
||
|
|
||
| def test_chart_holder_diagnostics_do_not_treat_zero_holders_as_success() -> None: | ||
| diagnostics = ChartHolderDiagnostics.from_holder_states([]) | ||
|
|
||
| assert diagnostics.mounted_holders == 0 | ||
| assert diagnostics.semantic_success is False |
There was a problem hiding this comment.
These three new tests have no docstrings. Repo rule [12148] requires every newly added test function to include a docstring documenting purpose, scenario, and expected outcome; sibling tests in this file (e.g. test_working_timeout_caps_report_budget) already follow it. ([BITO.md adaptive rule 12148])
Code Review Run #b4ab75
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
There was a problem hiding this comment.
Fixed in f4ef4cc. Added short scenario/outcome docstrings to the three holder-diagnostics tests.
There was a problem hiding this comment.
The user has addressed the reviewer's suggestion by adding docstrings to the three new test functions in tests/unit_tests/utils/test_report_execution.py. This change aligns the code with the repository's documentation requirements.
| report_schedule_id=7, | ||
| deadline=ReportExecutionDeadline(total_seconds=900), | ||
| ) | ||
| artifact = b"same exact bytes" |
There was a problem hiding this comment.
Local artifact lacks an explicit type annotation. Repo rule [13153] requires explicit annotations for all local variables in test files, even when inferable; the surrounding test code is otherwise fully typed. ([BITO.md adaptive rule 13153])
Code Review Run #b4ab75
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
There was a problem hiding this comment.
Leaving this unchanged. The bytes literal has an unambiguous inferred type and passes the repository's MyPy checks. An explicit local annotation would not improve correctness or readability here; keeping this PR focused rather than applying a blanket test-local annotation rewrite.
There was a problem hiding this comment.
The decision to omit the explicit type annotation is reasonable. Since the bytes literal has an unambiguous inferred type and the code passes existing repository checks, adding an explicit annotation would not provide additional clarity or correctness in this specific test context.
| page.wait_for_function.assert_not_called() | ||
|
|
||
|
|
||
| def test_holder_diagnostics_include_offscreen_errors_for_full_capture() -> None: |
There was a problem hiding this comment.
New test function lacks a docstring, which BITO.md adaptive rule 12148 requires for every newly added test function; sibling helpers in this file (e.g. _report_context, line 431) include one. Add a brief docstring stating the scenario: full-capture diagnostics must report virtualized for off-screen holders and error for alert holders.
Code Review Run #b4ab75
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
There was a problem hiding this comment.
Fixed in f4ef4cc. Added a docstring describing the actual distinction: viewport scans mark off-screen holders virtualized; full-dashboard scans expose their error state. Full-capture diagnostics should not mark that off-screen error as virtualized.
There was a problem hiding this comment.
The suggestion to add a docstring to the new test function is appropriate. It improves code maintainability by documenting the specific diagnostic scenario being tested, as required by the project's documentation standards.
tests/unit_tests/utils/test_screenshot_utils.py
def test_holder_diagnostics_include_offscreen_errors_for_full_capture() -> None:
"""Verifies that full-capture diagnostics report off-screen errors correctly."""
|
Reviewed the latest Bito suggestions. Clarified readiness versus delivery, consolidated the heuristic caveat, explained the logo threshold distinction, and added the requested diagnostics-test docstrings in f4ef4cc. All 141 selected tests and PR pre-commit checks pass. The tiled logging observation is a real scope limitation, not a new delivery check: final counts aggregate terminal states observed across captured viewports, rather than every holder ever present in the DOM. Documented that limitation and the need to compare per-tile diagnostics with expected holder counts. No claim that never-visible holders were captured. Leaving the small semantic-success helper extraction, threshold constant extraction, inferable local annotations, and broad test-style cleanup out of this fix. The nested blank check intentionally distinguishes blank pixels with no rendered chart content; the shared validator still checks those bytes before approval. No runtime behaviour changed in this cleanup. |
|
Bito Automatic Review Skipped – PR Already Merged |
babel-extract runs check_pot_drift.py, added in #44467 to fail a PR that adds or renames a translatable string without regenerating messages.pot. It is not currently in .asf.yaml's required contexts, so it can be red (or, on a PR whose branch predates the script's own existence, error outright) without blocking merge. That gap let #44465 land 18 minutes after #44467 regenerated the template, reintroducing drift immediately: #44465's branch was cut before #44467 merged, so check_pot_drift.py did not exist on it yet, and nothing required babel-extract to be green (or even present) on the up-to-date branch before allowing the merge. #44509 cleaned up the resulting drift. babel-extract is also the only translation-drift check gated on both Python and frontend changes (unit-tests-required, which independently covers check_pot_drift.py via check_pot_drift_test.py, only runs when a PR touches Python), so it is the one that has to be required for a frontend-only string addition to be caught at all. This does not by itself close the race that let #44465 through -- that needs required_status_checks.strict: true, a separate, repo-wide decision left for a follow-up PR stacked on this one. This PR only makes the existing check_pot_drift.py gate binding on the PR's own branch. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
TL;DR
Validate the actual screenshot bytes used in scheduled PDF/PNG delivery, and require the delivered PDF to match the bytes assembled from validated images. This is the capture-only split from #44336, based directly on master; it does not depend on that PR or add retry fields or migrations.
SUMMARY
Master already includes capture readiness, perceptual blank detection, capture-time stability checks and sticky capture rejection (#43784, #44034, #44114, #44191). This adds final-image validation, exact-PDF provenance and fail-closed handling when standard capture cannot establish content state. It also adds chart-holder diagnostics.
The classifier retains master's uniform-fill rejection across colours and themes and adds neutral light-grey coverage. There is no sparse-label override: a small title, logo or error label cannot automatically exempt an otherwise blank image. Extremely sparse legitimate output, including a solid-fill KPI without visible structure, can be rejected. A sufficiently large title or logo can still exceed the content thresholds while the rest of the page is incomplete. This is not a guarantee that every rendering defect is detected.
Visible query-error panels remain capture-ready and may be delivered with diagnostic warnings if the image passes visual validation. This is a capture safeguard, not a requirement that every chart query succeeds.
Discarded screenshots used to bootstrap query context for CSV/XLSX/TEXT skip the additional final-image validation, while retaining the existing browser readiness/capture contract. Identical image bytes are pixel-validated once per execution; later assembly and per-recipient gates check SHA-256 identity and sticky rejection. Changed bytes require validation again.
PDF provenance validates its source images and exact assembled bytes; it does not rasterize and visually inspect the finished PDF. The diff includes realistic image fixtures and diagnostics tests alongside the delivery-boundary checks. Whole-execution retries and ownership fencing remain in #44336.
BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
No UI change. Previously, successful capture provenance alone could allow corrupt or unvalidated final bytes through. These additional checks reject those artifacts before delivery. The classifier fixtures cover white/light-grey placeholders, sparse labels and solid-colour output; live browser canaries remain necessary.
TESTING INSTRUCTIONS
ADDITIONAL INFORMATION
Risk: false rejection can suppress delivery; false negatives remain possible. There is no feature flag to deliver a rejected capture. The classifier also affects tiled-thumbnail retry decisions. Reverting this PR restores master's existing capture safeguards, not an unchecked capture path. No schema rollback is needed. CI and live scheduled-report canaries must pass before rollout. Reviewers should explicitly assess the sparse-output trade-off and the policy allowing visible query-error panels.