Skip to content

fix slow data viewer when the summary panel is shown - #17812

Merged
kevinushey merged 11 commits into
mainfrom
bugfix/dataviewer-summary-perf
Jun 2, 2026
Merged

kevinushey merged 11 commits into
mainfrom
bugfix/dataviewer-summary-perf

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17806.

Problem

The "fast" data viewer becomes slow to open, scroll, and search when the summary panel is shown. The slowdown is not tied to any particular dataset and is reported on Windows/Electron. A community report and a user in the issue both found that turning off "Show summary pane by default" restores responsiveness.

Root cause

The R backend work is cheap (column histograms + NA counts are ~tens of ms; search transforms are cached). The cost is in the frontend:

  • The summary sidebar builds one SVG <rect> per histogram bin for every numeric column -- hundreds to thousands of vector nodes across a wide frame.
  • Neither the grid viewport, the sidebar, nor the sparklines were isolated onto their own paint layers (no contain/will-change). So the constant DOM churn from virtual scrolling (spacer-height changes, row add/remove) invalidated the root layer and forced all of those SVG sparklines to repaint every scroll frame.
  • The full sidebar (including sparklines) was built even when the panel was hidden -- it was only collapsed to width: 0. That is why toggling the preference off avoids the cost.

Changes (all in src/cpp/session/resources/grid/)

  1. Containment -- add contain: layout paint to #gridViewport and #sidebarContent, making each a paint/layout boundary so grid scrolling no longer repaints the sidebar. (Filter popups attach to document.body, so the paint clip does not affect them.)
  2. Canvas sparklines -- render each column's histogram to a single <canvas> raster instead of per-bin SVG <rect> nodes. Bar color is read from --grid-focus-border so theming still applies; the hover tooltip is preserved (bin derived from cursor position). The only cosmetic change is the loss of the per-bar hover highlight.
  3. Lazy build -- defer drawing the sparkline canvases until the summary panel is actually visible (renderPendingSparklines), so a hidden panel never pays the rendering cost.

Testing / caveat

The data viewer resources are static (no GWT compile). node --check passes; no e2e tests assert on sidebar/sparkline internals. The perf win itself could not be confirmed locally -- the slowness does not reproduce on macOS and is likely a Windows/Electron compositing characteristic. Suggested confirmation on the repro: open with DevTools Paint flashing enabled and scroll with the summary panel open -- the sidebar should no longer flash on every frame.

The summary sidebar built one SVG <rect> per histogram bin for every
numeric column (hundreds of vector nodes across a wide frame) and never
isolated the grid/sidebar onto their own paint layers. Scrolling the grid
invalidated the root layer and forced all of those SVG sparklines to
repaint each frame, producing multi-second stalls -- which is why turning
the summary panel off restored responsiveness (#17806).

- Add `contain: layout paint` to #gridViewport and #sidebarContent so the
  virtual-scroll DOM churn stays local and no longer repaints the sidebar.
- Render each column's histogram to a single <canvas> instead of per-bin
  SVG <rect> nodes; the hover tooltip is preserved.
- Defer sparkline drawing until the summary panel is actually visible, so
  a hidden panel never pays the rendering cost.

Addresses #17806.
@kevinushey kevinushey added this to the Blue Plumbago milestone Jun 1, 2026
kevinushey and others added 9 commits June 1, 2026 16:14
The canvas sparkline lost the SVG version's per-bar :hover highlight.
Redraw the canvas on hover with the hovered bar at full opacity, tracking
the hovered bin so it only repaints when the cursor crosses into a
different bar, and clear it on mouse-leave.
Moving these changes to a fresh branch via a file copy reverted three
blocks that #17804 (#17800 fix) had landed on main, since the copied file
predated that PR. Restore them:

- showScrollbars() in onResize and window.onActivate
- the multi-cell native-selection guard in onGridKeyDown's copy path

Also address review feedback on the canvas sparkline:

- return null when getContext("2d") yields no context, instead of a
  wrapper around an un-drawable canvas that still shows a hover tooltip
- drop the empty .sidebar-sparkline placeholder when no sparkline is
  produced, so it doesn't reserve vertical space
Render only the columns intersecting the horizontal viewport (plus the always-rendered pinned columns), mirroring the existing row virtualization, with left/right spacer cells preserving the table's total width and scrollbar. Wide frames materialized ~200 columns x ~100 rows of cells in a single DOM write, and the compositor commit for that many cells stalled the main thread for several seconds. Purely client-side; the column-paging data contract is unchanged.

Also restore a column's per-column filter display when its header is recreated as it scrolls back into the window, trim the row overscan, and add an e2e test covering the filter round-trip.

Addresses #17806.
PW_DEBUG opens Chromium DevTools on the dev desktop build and parks each test (via readline in the RStudio Console) so a human can arm the Performance profiler before the test drives its scenario. No-op without PW_DEBUG.

Adds a rstudio-console-waiting-for-input class on the console input (set when R requests interactive input, e.g. readline/menu/scan) so the pause can tell 'waiting for the user' apart from 'idle' -- the console clears its busy state on any prompt.

developer-only tooling; no user-facing behavior change.
Enable the MiddleClickAutoscroll Blink feature, which Chrome and Firefox ship enabled by default but Electron does not -- so middle-click in scrollable areas (e.g. the data viewer) did nothing in RStudio Desktop.
activeHeaderUIs (the filter/column-type re-injection registry used as the column window slides) was module state that survived resetGridState, so it could re-inject header controls into a reset/refreshed grid even when the frontend considered them off. Clear it on teardown, and record header-UI visibility in postInitActions unconditionally so column-pagination persistence flows through that replay channel (the source of truth across bootstraps) rather than relying on the leaked registry.

Addresses #17806 (roborev review).
The open-and-type relied on page.keyboard after the 'All' click's implicit focus, and the text filter auto-dismisses (reverts to 'All') if its input blurs while empty -- so a focus hiccup between opening and typing silently dropped the keystroke or closed the editor. Type through the input locator and retry the open-and-type as a unit until the value sticks; gate on the input value before the downstream filtered-row assertion. Stable across --repeat-each=5.
columnOffsets() rebuilt an O(columns) prefix sum on every call, including
once per rendered row in appendWindowedCells. Cache the result and invalidate
it alongside the pinned-offsets cache (same columnOrder + measuredWidths
dependencies), turning a full rebuild's offset work from O(rows x columns) into
O(columns) per render pass.
@gtritchie

Copy link
Copy Markdown
Member

Review Summary

Four specialized review passes (code quality, error handling, test coverage, comments). The core engineering is strong -- column virtualization is correctly implemented with consistent coordinate spaces, sound cache invalidation, and edge-case handling that holds up under tracing. The findings cluster around description accuracy and test coverage of the new code, not correctness bugs.


Critical Issues (1)

1. PR description materially understates scope.
The body says "Changes (all in src/cpp/session/resources/grid/)" and lists three CSS/JS changes. The diff actually contains far more, undisclosed:

  • Client-side column virtualization (~400 lines) -- the headline behavioral change, mentioned only in NEWS.
  • BUFFER_ROWS reduced 200->25 (a behavioral tuning change).
  • A Playwright debug harness (e2e/rstudio/utils/debug.ts, fixture hooks).
  • Production GWT code: setWaitingForInput added to Shell.java / ShellWidget.java / ShellDisplay.java.
  • A new desktop env flag RSTUDIO_OPEN_DEVTOOLS.
  • Enabling MiddleClickAutoscroll Blink feature in main.ts -- an unrelated user-facing feature.

The "Testing / caveat" also claims "data viewer resources are static (no GWT compile)" -- false, since the PR modifies GWT Java.


Important Issues (4)

2. getColumnWindow last-column fallback conflates two cases -- DataViewer.js:491-493. The start === -1 branch fires on benign transient overscroll and on clientWidth === 0 (background/hidden tab) or degenerate widths. In the latter, it silently renders the last column regardless of scroll position. The comment only mentions "transient layout," misleading a future debugger. Distinguish the unmeasurable-viewport case (return existing window / first unpinned) from overscroll, and broaden the comment.

3. Spacer-width / total-table-width invariant is untested -- this is the mechanism the whole fix rests on. No test asserts viewport.scrollWidth stays equal to the sum of column widths as the window slides. A miscomputed spacer would silently corrupt horizontal navigation while the one new test still passes.

4. pendingSparklines_ not reset in resetGridState -- DataViewer.js resetGridState resets colWinStart/End and activeHeaderUIs but not pendingSparklines_ (only reset in initSidebar). Latent rather than currently reachable (bootstrap runs initSidebar first), but it breaks the symmetry the resetGridState comment claims. Reset it there or document why initSidebar is sole owner.

5. createSparkline null-path masks a real canvas-context failure -- DataViewer.js:~2336, renderPendingSparklines:~3158. Returns null both for legitimately-empty histograms (all-equal values) and for getContext("2d") failing (context loss / exhausted memory). Both are treated identically (remove container), so a genuine failure blanks every sparkline with no diagnostic. A dev-only console.warn on context loss would make it observable.


Suggestions (5)

  • Cell-click & keyboard-nav across the window boundary are untested (data-col-pos mapping in onGridCellClick; ensureActiveCellVisible/ensureActiveHeaderVisible materializing off-window columns). Highest-value tests to add after the scrollWidth invariant.
  • pagination-sorting frame reduction (1M->10k cells) preserves column count (good) but drops the only large-frame render-cost guard -- the exact scenario this PR optimizes. Consider a lightweight "wide frame opens within timeout" smoke test as replacement.
  • Sort indicators & pinned columns on recreated headers untested for the scroll-out-and-back path the new filter test covers -- add the sort/pin analogues.
  • Lazy sparkline render (canvas appears on first panel open; placeholder removed on empty) is cheap to assert (.sidebar-sparkline canvas count 0->>0) and currently relies entirely on manual verification.
  • Redundant sync + async re-window in ensureActive*Visible/scrollToColumn is correct (async pass is a no-op) but add a one-line comment so a future reader doesn't "optimize" away the synchronous call.

Recommended Action

  1. Rewrite the PR description to describe what's actually in the diff; fix the "static resources / no GWT compile" claim (Clone fail-Permission denied (publickey) #1).
  2. Fix the getColumnWindow fallback + comment (Autocompletion of delimiters #2) and the createSparkline context-loss diagnostic (Implemented Hunspell suggest feature #5); reset pendingSparklines_ in resetGridState (PAM Session Prototype #4).
  3. Add the scrollWidth invariant test (Allow for homebrew's version of libboost #3), then cell-click/keyboard-nav coverage.
  4. Reconcile the "loss of per-bar hover highlight" claim -- the code actually preserves it via drawBars(highlightBin).

@gtritchie gtritchie left a comment

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.

LGTM, Claude is very upset about the PR description and some nits on comments and unreachable edge cases.

@kevinushey

Copy link
Copy Markdown
Collaborator Author

E2E test failures appear to be flakes, and passed locally. Filed #17819 for follow-up.

@kevinushey kevinushey closed this Jun 2, 2026
@kevinushey kevinushey reopened this Jun 2, 2026
@kevinushey
kevinushey merged commit b17d41c into main Jun 2, 2026
0 of 2 checks passed
@kevinushey
kevinushey deleted the bugfix/dataviewer-summary-perf branch June 2, 2026 17:18
kevinushey added a commit that referenced this pull request Jun 3, 2026
getActiveCellTd located the cell by the rsGridCell_<row>_<col> id, but
buildRow assigns that id only to the cell that is already active. So when
setActiveCell updated activeRow/activeCol and looked up the newly targeted
cell to mark it, the lookup returned null and .activeCell was never applied;
the highlight only reappeared once a later render pass (e.g. a scroll)
rebuilt the row and re-derived the class from activeRow/activeCol. Headers
were unaffected because getActiveHeaderTh resolves by column index.

Look the cell up by data-col-pos, which buildRow sets on every rendered
cell, so the highlight lands immediately. Regression from #17812.
kevinushey added a commit that referenced this pull request Jun 4, 2026
* keep data viewer pinned columns pinned across column pagination

Pinned columns, the sort column, and per-column filters are now tracked by
absolute column index in the full frame rather than by their position within
the currently fetched window, and the column request asks for any pinned
columns alongside the visible window so an off-window pinned column keeps its
data. Previously a pinned column was tracked by window position, so paging to
a different set of columns left the pin on whatever column now occupied that
slot.

The server-side column request is now an explicit ordered list of absolute
column indices (pinned first, then the window), which also removes the
column-offset realignment of sort and filter indices on the backend.

Addresses #17835.

* preserve an open data viewer filter editor across header rebuilds

The post-load column auto-size rebuilds the header row, which would tear down
an open per-column filter editor (a popup, or the inline text-filter input)
while the user was still typing into it. Defer that rebuild while a header
editor is open and flush it once the editor closes, so keystrokes typed into a
filter immediately after opening a wide frame are not lost.

* speed up the data viewer filter e2e test and document trace profiling

The per-column filter test opened its retry loop with inputValue() on the
text-filter input before the editor existed, blocking ~10s on the action
timeout each load. Probe with count() (instant) and wait for the initial row
batch before opening the filter; the test body drops from ~12s to ~2s.

Also document how to profile a slow Playwright test (force a trace, then pair
the before/after events in test.trace by callId) in the e2e README and the
run-playwright-tests skill.

* extend data viewer summary hover highlight over the stats widget

The global td background rule painted an opaque --grid-bg over the
sidebar stats table, so the .sidebar-col hover highlight stopped at the
expanded summary widget. Keep the stats cells transparent so the parent
background shows through.

* align the data viewer reset view menu item with the summary toggle

The plain Reset View MenuItem rendered its label flush left while the
CheckableMenuItem reserves a 25px icon column, leaving Reset View looking
offset. Render its label through formatMenuLabel so it carries the same
icon column. Add a single-arg AppCommand.formatMenuLabel(String) overload
for this label-only case.

* apply data viewer active-cell highlight on click and keyboard nav

getActiveCellTd located the cell by the rsGridCell_<row>_<col> id, but
buildRow assigns that id only to the cell that is already active. So when
setActiveCell updated activeRow/activeCol and looked up the newly targeted
cell to mark it, the lookup returned null and .activeCell was never applied;
the highlight only reappeared once a later render pass (e.g. a scroll)
rebuilt the row and re-derived the class from activeRow/activeCol. Headers
were unaffected because getActiveHeaderTh resolves by column index.

Look the cell up by data-col-pos, which buildRow sets on every rendered
cell, so the highlight lands immediately. Regression from #17812.

* test: cover data viewer active-cell highlight on click and keyboard nav

Guards the regression fixed in the previous commit: clicking or arrow-keying
a cell must apply .activeCell to the live cell immediately, not only after a
later scroll re-renders the row. Asserts on the class rather than the painted
outline so it does not depend on focus/compositing state.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants