Skip to content

fix(reports): recheck readiness at capture time - #44114

Merged
rebenitez1802 merged 9 commits into
apache:masterfrom
fitzee:fix/report-capture-readiness-race
Sep 10, 2026
Merged

rebenitez1802 merged 9 commits into
apache:masterfrom
fitzee:fix/report-capture-readiness-race

Conversation

@fitzee

@fitzee fitzee commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Scheduled report screenshots can capture loading indicators even after the initial readiness check succeeds. Dashboard expansion, scrolling, repaint work, or a late chart rerender can move a chart back into its loading state between that check and the actual screenshot.

This change narrows that capture-time race by requiring the existing readiness predicate to remain continuously true for 500 ms immediately before every scheduled screenshot attempt:

  • standard chart and dashboard captures
  • every tiled-dashboard capture
  • blank-capture retries

The check reuses the existing loading, rendered-content, terminal empty/error state, ECharts, and AG Grid signals. It is report-only and bounded by the existing execution deadline and readiness reserve. If readiness changes and does not stabilize within the remaining budget, capture and delivery stop instead of sending a spinner-filled report.

Readiness and screenshot capture are separate browser operations, so a page can still change after the final sampled readiness frame. This mitigation substantially reduces that window but does not claim atomicity.

The new lifecycle logs are:

  • report_capture_readiness_stable
  • report_capture_readiness_changed

The shared backend CI setup also pins uv 0.12.12. Without an explicit
version, astral-sh/setup-uv fetched Astral's online version manifest on every
cache miss to resolve latest; a transient timeout in that lookup failed this
PR before its experimental Playwright tests could start.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Before: a report could pass readiness, re-enter a chart loading state during capture preparation, and deliver a PDF containing loading indicators.

After: readiness must remain stable at the screenshot boundary. A page that returns to loading is allowed to settle within the bounded wait; otherwise the report fails before capture or delivery.

TESTING INSTRUCTIONS

Run:

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

Result: 132 passed.

The tests cover:

  • stable readiness before standard and tiled captures
  • keyword-only Playwright argument binding on both capture routes
  • revalidation on blank-capture retries
  • aborting before screenshot when readiness changes
  • report deadline propagation and bounded waits
  • non-report screenshot behavior remaining unchanged

The changed-file pre-commit checks also validate the shared action YAML and
GitHub Actions configuration.

Also run the changed-file hooks:

git add docs/admin_docs/configuration/alerts-reports.mdx \
  superset/utils/screenshot_utils.py \
  superset/utils/webdriver.py \
  tests/unit_tests/utils/test_screenshot_utils.py \
  tests/unit_tests/utils/webdriver_test.py
pre-commit run

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 9, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #11d981

Actionable Suggestions - 0
Additional Suggestions - 1
  • tests/unit_tests/utils/test_screenshot_utils.py - 1
    • Hardcoded stability constant · Line 1119-1119
      The assertion hardcodes the stability window literal `500`, duplicating the production constant `REPORT_CAPTURE_READINESS_STABILITY_MS` (defined as 500 at screenshot_utils.py:58). If that constant changes, this test silently diverges from production behavior. Import and reference the constant so the assertion stays in sync.
Review Details
  • Files reviewed - 5 · Commit Range: 30f7afb..30f7afb
    • docs/admin_docs/configuration/alerts-reports.mdx
    • 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

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Sep 9, 2026
@netlify

netlify Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 5c6d83c
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa2d23fba4ef80008d571ff
😎 Deploy Preview https://deploy-preview-44114--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

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.15%. Comparing base (e5c2a3e) to head (5c6d83c).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #44114   +/-   ##
=======================================
  Coverage   80.14%   80.15%           
=======================================
  Files        2924     2924           
  Lines      172370   172405   +35     
  Branches    40018    40021    +3     
=======================================
+ Hits       138147   138183   +36     
  Misses      31637    31637           
+ Partials     2586     2585    -1     
Flag Coverage Δ
hive 37.34% <23.33%> (-0.01%) ⬇️
mysql 56.89% <23.33%> (-0.01%) ⬇️
postgres 56.92% <23.33%> (-0.01%) ⬇️
presto 39.23% <23.33%> (-0.01%) ⬇️
python 84.52% <100.00%> (+<0.01%) ⬆️
sqlite 56.62% <23.33%> (-0.01%) ⬇️
unit 75.85% <100.00%> (+0.04%) ⬆️

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.

@fitzee
fitzee marked this pull request as draft September 9, 2026 21:56
@github-actions github-actions Bot added the github_actions Pull requests that update GitHub Actions code label Sep 9, 2026
@fitzee
fitzee marked this pull request as ready for review September 10, 2026 00:09
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
# Avoid a network-dependent lookup of the latest uv version during setup.
version: "0.12.12"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Pinning this version still leaves the same manifest request on every tool-cache miss: setup-uv resolves the artifact through getArtifact() → findManifestVersion() → the remote uv.ndjson, so a timeout to that endpoint still fails backend setup before tests. Should this use an install path or local manifest that actually removes that lookup?

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.

Agreed. A version pin still goes through setup-uv artifact resolution on a cache miss, so it does not remove the failing network lookup. I removed this unrelated setup-uv change from the PR in 1d5e341.

const now = performance.now();
const previous = window.__supersetCaptureReadiness;
if (!ready) {{
window.__supersetCaptureReadiness = {{token: args.token, since: null}};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The new tests stub wait_for_function, so none executes this reset/dwell state machine; replacing the comparison with return true or removing this reset still leaves them green and reopens the exact ready → loading race. Could we add a browser/JS-level regression that drives ready → loading → ready and asserts a fresh 500 ms dwell before capture?

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.

Added executable coverage in 1d5e341. The test evaluates the generated JavaScript through Node and verifies initial false, success only after 500 ms, ready-to-loading-to-ready dwell reset, and token reset. It skips explicitly when Node is unavailable rather than adding a Chromium dependency to the Python unit suite.

@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #4a3553

Actionable Suggestions - 0
Additional Suggestions - 1
  • tests/unit_tests/utils/test_screenshot_utils.py - 1
    • Magic number duplicates constant · Line 850-850
      The literal `500` duplicates the source constant `REPORT_CAPTURE_READINESS_STABILITY_MS` (=500) defined in `superset/utils/screenshot_utils.py` and passed as `stabilityMs` at the production call site. If the threshold changes, this assertion silently diverges. Import `REPORT_CAPTURE_READINESS_STABILITY_MS` from `superset.utils.screenshot_utils` and reference it in the assertion at line 850 (and line 1126) instead of the hardcoded literal.
Review Details
  • Files reviewed - 5 · Commit Range: 30f7afb..63b2f44
    • docs/admin_docs/configuration/alerts-reports.mdx
    • 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 - 1
    • .github/actions/setup-backend/action.yml - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

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

  • /review - Manually triggers an incremental AI Review.

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

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

  • /resume - Resumes automatic reviews.

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

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

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

Documentation & Help

AI Code Review powered by Bito Logo

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

Request changes: the capture-time readiness dwell is a sound idea and cleanly integrated, but a reserve mismatch makes the 500ms dwell deterministically unsatisfiable in a narrow near-deadline window — aborting reports that would otherwise deliver. Worth fixing before merge, plus a few test-coverage and DRY nits.

🟡 Medium — Dwell is unsatisfiable when <500ms of readiness budget remains, aborting a deliverable report
The stable gate bounds its wait_for_function timeout with deadline.timeout_seconds("capture_readiness_stability", reserve_seconds=readiness_reserve_seconds) (webdriver.py:269-273, and via _timeout_seconds at screenshot_utils.py:1187-1191), but readiness_reserve_seconds = capture + delivery + cleanup (report_execution.py:225-229) is strictly larger than the post_capture_reserve_seconds = delivery + cleanup the actual capture uses (231-235, webdriver.py:310-312). available_seconds has no lower floor — it returns any value > 0 (report_execution.py:152-159) — and the dwell needs performance.now() - since >= 500ms with the first poll always resetting since. So when remaining - readiness_reserve lands in (0, 0.5s), wait_for_function gets a sub-500ms timeout the dwell can never complete → PlaywrightTimeout → report_capture_readiness_changed → re-raise, aborting a report whose actual capture still had capture_reserve (~60s default) of budget and would have succeeded before this change. Narrow window and it fails loudly (no bad screenshot shipped), but it's a deterministic regression. Fix: when the computed stability budget is below REPORT_CAPTURE_READINESS_STABILITY_MS / 1000, skip the dwell and proceed to capture — the pre-existing readiness gate already confirmed the page ready — rather than abort. (Charging it against post_capture_reserve_seconds narrows but doesn't eliminate the window.)

🟢 Low — Per-tile / per-attempt dwell inflates deadline pressure on large tiled dashboards
The gate sits inside the per-tile for capture_attempt loop (screenshot_utils.py:1185-1224) and uses a fresh token = str(time.monotonic_ns()) each call, so every tile re-accrues a full 500ms dwell with no carryover — ~500ms × N tiles of pure added wall-clock (a 40-tile dashboard adds ≥20s), all charged to the shared deadline, which accelerates hitting the unsatisfiable window above. Consider establishing the dwell once per capture, or making it adaptive to remaining budget.

🟢 Low — The dwell JS (_stable_readiness_js) has zero executable coverage
The whole mechanism — token reset, since === null reset, !ready oscillation reset, now - since >= stabilityMs — lives in the browser JS string (screenshot_utils.py:493), but every test mocks page.wait_for_function on the Python side and only asserts the predicate contains __supersetCaptureReadiness and stabilityMs == 500. Changing >= to > or returning true on the first truthy poll would leave the suite green. Fix: add a JS/headless test that exercises first-poll-false, pass-after-500ms, ready→unready→ready reset, and token reset.

🟢 Low — chart-container stable-gate branch is untested
webdriver.py:275-279 selects STABLE_CHART_CONTAINER_READY_JS for element_name == "chart-container", else STABLE_REPORT_ALL_CHART_HOLDERS_READY_JS, but every new standard-path test uses element_name="standalone", and the assertions can't distinguish the two predicates (both contain the same marker). Inverting the branch would go uncaught, yet it matters — REPORT_ALL_CHART_HOLDERS_READY_JS requires holders.length > 0, which is vacuously false on a chart-only page. Fix: add a chart-container case asserting the predicate contains document.querySelector('.chart-container').

🟢 Low — test_capture_readiness_requires_a_stable_dwell doesn't test a dwell
webdriver_test.py:1529: the mocked signature_checked_wait returns success unconditionally and only asserts predicate/stabilityMs/timeout wiring — no dwell is exercised (the name overpromises). It's meaningful wiring coverage; just rename it to match what it checks (or drive a fake clock through the real JS).

🟢 Low — Brittle call_count == 7 / call_args_list[2::2] slicing
test_screenshot_utils.py:1121-1126 couples to exact call ordering/count rather than predicate identity. Fix: filter stable calls by JS content (as webdriver_test.py:135-139 already does) and assert one stable call per tile instead of an absolute count.

🟢 Low — Near-duplicated ~35-line stable-gate in two modules
The gate block is near-verbatim in _get_validated_screenshot (webdriver.py:268-306) and take_tiled_screenshot (screenshot_utils.py:1186-1224); they already diverge (the tiled copy sets readiness_timeout = True before raising, the standard copy doesn't). Consider a shared _wait_for_stable_readiness(page, predicate, timeout_seconds, log_fields) helper.

🟢 Low — Operator-visible delivery change lacks an UPDATING.md note
Reports whose charts briefly re-enter loading during the 500ms window now abort where they previously delivered. The alerts-reports.mdx paragraph is accurate, but UPDATING.md's ## Next section already documents analogous report-capture behavior ("charts that never mount are no longer captured blank"); a one-line entry there would surface this to upgraders.

@github-actions github-actions Bot removed the github_actions Pull requests that update GitHub Actions code label Sep 10, 2026
@fitzee
fitzee force-pushed the fix/report-capture-readiness-race branch from d7ab0e7 to 1d5e341 Compare September 10, 2026 10:39
@fitzee

fitzee commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the latest review in 1d5e341711:

  • Fixed the near-deadline regression: if the available timeout is no longer sufficient to complete the 500 ms dwell, capture proceeds using the already-satisfied readiness gate instead of starting a deterministically impossible wait.
  • Centralized the standard and tiled stable-readiness wait in one helper.
  • Added executable Node coverage for initial state, the 500 ms boundary, ready → loading → ready reset, and token reset.
  • Added chart-container predicate-selection coverage.
  • Renamed the wiring test so it no longer claims to execute the dwell.
  • Replaced brittle call-count/slicing assertions with predicate-based filtering.
  • Replaced hardcoded 500 assertions with REPORT_CAPTURE_READINESS_STABILITY_MS.
  • Added the UPDATING.md note.
  • Removed the unrelated setup-uv pin because it still performs remote manifest resolution on cache misses.

I retained the per-tile/per-attempt dwell intentionally: scrolling changes which virtualized holders are active, and a blank retry follows a compositor repaint, so readiness from a previous tile or attempt is not transferable. The new insufficient-budget path prevents that safety check from consuming a capture that could still complete.

Validation: repository-pinned Ruff formatting and lint pass. The JavaScript state-machine test executes directly when Node is available. The full local pytest invocation was blocked by the available shell image carrying an incompatible dependency set for this OSS head (flask-caching constructor mismatch), so CI remains the authoritative full-suite run.

@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: all blocking concerns from the previous rounds are resolved. Verified locally against d7d4c4dca4 — pytest tests/unit_tests/utils/webdriver_test.py tests/unit_tests/utils/test_screenshot_utils.py → 136 passed, ruff check + format clean.

Resolved since my CHANGES_REQUESTED review:

  • The v1 Medium (near-deadline unsatisfiable 500ms dwell) is closed by the wait_for_stable_readiness skip guard.
  • The v2 blocker (FrozenInstanceError in test_capture_skips_stability_dwell_when_budget_is_too_short) is fixed by rebuilding the frozen deadline with dataclasses.replace; the test now actually drives the skip branch.
  • Real Node-executed coverage for the dwell state machine, a chart-container predicate test, the test rename, predicate-based (non-brittle) assertions, the shared helper, the UPDATING.md note, and the reverted uv pin are all in.

One optional, non-blocking follow-up (fine to defer): wait_for_stable_readiness skips only when timeout_seconds <= REPORT_CAPTURE_READINESS_STABILITY_MS/1000 (exactly 0.5s), but a genuinely-ready page needs >500ms + one poll interval (default raf, ~16ms) to satisfy the dwell — so for timeout_seconds ∈ (0.5s, ~0.516s] the wait can still time out and abort a ready capture. It's a ~one-frame residual band and fails loudly, so not a blocker; consider adding a small margin to the skip floor if you touch this again.

Thanks for the thorough iteration on the tests.

rebenitez1802 and others added 2 commits September 10, 2026 14:37
Resolve UPDATING.md conflict by keeping both "## Next" entries (report
capture readiness recheck + Resample fill-the-time-range).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
shutil.which returns str | None; assert after the skip guard so the
subprocess.run invocation in the readiness JS test type-checks.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@aminghadersohi
aminghadersohi self-requested a review September 10, 2026 14:32

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

Ran sadpandajoe's mutation: with node present the new test catches return true, reset removal, token-drop and dwell length, and CI does ship node (junit: passed) — that thread is closed on the merits. unit-tests-required is red from the 30-min job cap during codecov upload, not a test failure.

Comment thread superset/utils/screenshot_utils.py Outdated
Comment on lines +564 to +565
minimum_timeout_seconds = REPORT_CAPTURE_READINESS_STABILITY_MS / 1000
if timeout_seconds <= minimum_timeout_seconds:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The first poll only records since, so success needs >500 ms — an always-ready page first returns true at 512 ms under rAF polling. A budget in (500, 512] ms times out and raises report_capture_readiness_changed, failing the report while capture reserve is still intact.

Suggested change
minimum_timeout_seconds = REPORT_CAPTURE_READINESS_STABILITY_MS / 1000
if timeout_seconds <= minimum_timeout_seconds:
# 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:

Comment on lines +489 to +490
Immediately before each scheduled report screenshot, chart readiness must remain
stable for 500 milliseconds. This final check runs after scrolling, content

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.

wait_for_stable_readiness skips the dwell entirely when less than one stability window of budget remains (logged skipped=True), so this is not unconditional — and budget-starved reports are exactly the ones the race affects.

Suggested change
Immediately before each scheduled report screenshot, chart readiness must remain
stable for 500 milliseconds. This final check runs after scrolling, content
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

The dwell's first poll only records the start, so a ready page needs the
full 500 ms window plus one polling interval to satisfy. A remaining budget
in (500 ms, ~512 ms] started a wait that could never complete and aborted an
otherwise deliverable report with capture reserve still intact. Skip the
dwell below window + 250 ms instead. Clarify the docs that the check is
skipped (logged skipped=True) when budget is short, and add a regression
test for the margin.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@aminghadersohi aminghadersohi 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

@rebenitez1802
rebenitez1802 merged commit 12e7474 into apache:master Sep 10, 2026
81 of 87 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/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants