Skip to content

preserve dismissed summary sidebar across column pagination - #17595

Merged
kevinushey merged 4 commits into
mainfrom
bugfix/17564-data-viewer-summary-pagination
May 12, 2026
Merged

kevinushey merged 4 commits into
mainfrom
bugfix/17564-data-viewer-summary-pagination

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17564.

Summary

  • The data viewer's per-object UI state (sidebar visibility, pinned columns, sort, filters, manual widths) was being silently wiped from localStorage on every column-frame pagination. The user-visible symptom is the one reported: dismissing the Summary sidebar and then paginating brings the sidebar back.
  • Root cause: the "is this the same underlying frame?" fingerprint was built from the visible column slice (DataViewer.js columnFingerprint), so the fingerprint inevitably mismatched whenever the client paged through columns -- applySavedState then called clearSavedState() and dropped everything.
  • Fix: compute the fingerprint server-side from the full set of column names (in .rs.describeCols / .rs.describeColSlice) and surface it on the rownames metadata as cols_fingerprint. The client reads it instead of joining visible names, so it stays stable across pagination and only changes on a legitimate object reassignment.
  • Defense in depth: in initGrid, the data_viewer_show_summary URL default no longer overwrites sidebarVisible when saved state already has a sidebar choice.
  • Bumped STATE_VERSION to 2 so any saved state from the previous schema is cleanly discarded on first read.

Test plan

  • df <- data.frame(matrix(1:1000000, nrow = 100000, ncol = 500)), View(df), dismiss the Summary sidebar, then click the right-paginate arrow. Sidebar stays dismissed.
  • Verify the same with data_viewer_show_summary user pref set to off.
  • Pin a column, sort, set a filter; reload the viewer (close + reopen via View(df)). State persists.
  • df <- mtcars; View(df); df <- iris; View(df). The iris view comes up fresh (no stale pins/filters from mtcars).
  • ./rstudio-tests --scope r -- new regression test in test-dataviewer.R verifying fingerprint stability across slices.

The data viewer's saved-state fingerprint joined the names of the
visible column slice, so paginating to a different offset always
mismatched and wiped the per-object state -- re-showing a dismissed
summary sidebar (and silently clearing pinned columns, sort, filters,
and manual widths from localStorage as a side effect).

Compute the fingerprint from the full frame's column names on the
server and surface it on the rownames metadata, so it stays stable
across paginations. Also stop clobbering sidebarVisible with the URL
default on re-bootstraps when saved state already has a choice.

Addresses #17564.
@kevinushey kevinushey added this to the Golden Wattle milestone May 11, 2026
@posit-snyk-bot

posit-snyk-bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

Address review findings on b7e704d:

- The bootstrap path skipped sidebarVisible = loc.showSummary whenever
  saved state had a sidebarVisible boolean, but applySavedState drops
  the entire state on fingerprint mismatch without applying its sidebar
  choice -- leaving sidebarVisible at its module default for users who
  prefer it hidden. Only skip the URL default when saved state will
  actually be restored (sidebarVisible boolean AND fingerprint matches).

- The fingerprint joined column names with "-", so reassignments like
  c("a-b", "c") vs c("a", "b-c") produced identical fingerprints and
  silently passed the reassignment-detection check. Length-prefix the
  names and join with the ASCII Unit Separator. Cover with a test.
@kevinushey
kevinushey requested a review from gtritchie May 11, 2026 16:56
@gtritchie

Copy link
Copy Markdown
Member

Review Summary

Reviewed via /pr-review-toolkit:review-pr (code-reviewer, silent-failure-hunter, pr-test-analyzer, comment-analyzer). The fix direction is sound — moving the fingerprint server-side eliminates the slice/full-frame mismatch. A few collision concerns in the fingerprint encoding are worth addressing before merge.

Critical

1. Separator collision in fingerprint — SessionDataViewer.R:151,459
paste(names(x), collapse = "-") produces identical fingerprints for distinct frames when a column name contains -. Verified: c("a-b","c") and c("a","b-c") both yield "a-b-c". Column names containing - are legal in R (e.g. check.names = FALSE or backtick quoting), so saved pin/sort/filter state can be silently applied across mismatched frames — the corruption the fingerprint was added to prevent. Consider length-prefixing, hashing (rlang::hash / digest::digest), or using a delimiter that cannot appear in an R name.

2. Empty / NULL names(x) collide — SessionDataViewer.R:151,459
When names(x) is NULL or zero-length, the fingerprint is \"\". applySavedState in DataViewer.js:3453-3457 only clears state when state.columns !== columnFingerprint(), so two unrelated frames in this state are considered the same. Emit NA_character_ -> JSON null for empty cases and treat null/\"\" on the client as always-mismatch.

3. columnFingerprint() fail-open on missing field — DataViewer.js:3380-3384
Returns \"\" when cols[0].cols_fingerprint is missing. Combined with #2, any response omitting the new field collides with every other such response. Return a per-load random sentinel (or null) so missing data always triggers clearSavedState() rather than silently passing the equality check.

Important

4. No regression test for the user-visible bug
The new R test verifies fingerprint stability across slices, but nothing exercises pagination + sidebar/pin persistence end-to-end. A BRAT test (in test-automation-data-viewer.R) viewing a >100-column frame, dismissing sidebar, paginating, then asserting state persists would prevent regression. Worth a separate BRAT test that pre-seeds a v1 localStorage payload and asserts it's discarded.

5. Tighten mismatch guard — DataViewer.js:3453
Current: typeof state.columns === \"string\" && state.columns !== columnFingerprint(). If state.columns === undefined, the mismatch check is skipped and positional indices are applied blind. Change to typeof state.columns !== \"string\" || state.columns !== columnFingerprint().

6. describeCols default-branch is a footgun — SessionDataViewer.R:144-151
The comment says callers that subset x must pass colsFingerprint themselves, but nothing enforces it. A future caller that subsets and forgets reintroduces the original bug silently. Either assert when maxCols > 0, or reframe the comment in terms of consequence ("otherwise saved per-object UI state is invalidated on every column-frame change").

Minor

  • Silent discard paths — loadSavedState's version-mismatch, corrupt-JSON, and applySavedState mismatch branches log nothing. The STATE_VERSION bump will wipe every existing user's state on first load with no breadcrumb; a one-time console.info would help support correlate "my pins disappeared after upgrade."
  • Comment in .rs.describeColSlice:455 singles out "dismissed summary sidebar" — invites rot if the feature is renamed; generalize to "pins, widths, sort, filters, sidebar visibility."
  • columnFingerprint comment frames the trigger as reassignment, but anything mutating names(x) (names(df) <- ..., df$new <- ...) also flips it. Slight under-statement.
  • Anchor [[1]] indexing in test-dataviewer.R:106+ — add expect_equal(slice_a[[1]]$col_type, \"rownames\") so a refactor that shifts the rownames slot doesn't make tests silently pass with NULL == NULL.
  • Add collision tests for hyphenated names and empty-names cases (Clone fail-Permission denied (publickey) #1, Autocompletion of delimiters #2) to lock in whatever fix is chosen.

Strengths

  • Diagnosis and fix direction are correct.
  • STATE_VERSION bump cleanly drops v1 payloads via the version check at DataViewer.js:3424.
  • loadSavedState() ordering in initGrid is safe: stateKey() reads only URL params, applySavedState guards on !cols, single read preserved.
  • New R unit test asserts the right invariants: stable across slices, distinct across frames, parity between describeCols/describeColSlice.

The collision concerns in #1-#3 are the only real blockers — the rest is polish.

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

See review feedback

Replace the unbounded length-prefix + Unit Separator fingerprint with a
SHA-256 hash of the column names. Empty/NULL names now produce
NA_character_ so the client can treat "no anchor" as always-mismatch,
and the client-side fallback for a missing fingerprint is now a
per-load random sentinel (fail-closed) instead of an empty string that
silently passes the equality check. applySavedState also fails closed
when state.columns is non-string.

The hash is computed via a new .rs.digest helper that calls into a small
rs_sha256 routine exposed from SessionRUtil.cpp (wrapping
core::system::crypto::sha256Hex), so we don't take a dependency on the
digest package.

Also fix rstudio-tests arg parsing: the prior case "$1" only matched
the first argument, so --scope r --filter foo silently ignored the
filter. Wrap in a loop so the options compose in either order.
- rstudio-tests --filter now validates a value is present before
  shifting, mirroring --scope; with the new while-loop, an unguarded
  --filter could shift past the args and spin forever.
- .rs.digest no longer hand-frames character vectors with a Unit
  Separator delimiter -- name-internal \\x1F could still collide. All
  non-raw inputs go through serialize(), which encodes element
  boundaries unambiguously.
- .rs.dataViewer.colsFingerprint now returns NA_character_ when the
  digest helper itself fails, instead of building a valid-looking
  "N:NA" string that any other digest-failed frame with the same
  column count would also produce.
@kevinushey
kevinushey merged commit 893b36b into main May 12, 2026
8 checks passed
@kevinushey
kevinushey deleted the bugfix/17564-data-viewer-summary-pagination branch May 12, 2026 01:59
kevinushey added a commit that referenced this pull request May 28, 2026
…digest (#17789)

* fix import dataset preview by removing embedding dependency from .rs.digest

The async data-preview subprocess (R_PROCESS_VANILLA, launched from
SessionData.cpp) sources only Tools.R + a handful of session modules
and has no RStudio embedding registered. The SHA-256-backed
.rs.digest added in #17595 lived in SessionRUtil.R (not sourced in
the subprocess) and called into rs_sha256 via the embedding (not
available there either), so the column-names fingerprint failed with
"could not find function '.rs.digest'" on any Import Dataset preview.

The fingerprint just needs a stable identity token for collision
detection, not a cryptographic hash, so replace .rs.digest with a
vectorized Adler-32 in pure base R living in Tools.R. Closed-form
rewrite (a = 1 + sum(b); b = n + (n+1)*sum(b) - sum(k*b[k])) avoids
an R-level loop, and promoting to double sidesteps R's 32-bit integer
overflow.

Verified against the canonical Adler-32 of "abc" (0x024d0127) and
against a loop-based reference. 50k random column names hash in 4ms.

Drops the rs_sha256 C++ helper and its Crypto.hpp include.

Addresses #17777.

* test(e2e): import dataset csv preview renders

Regression coverage for #17777: opens Import Dataset > From Text
(readr), types the path to a small CSV, clicks Update, and asserts
the preview iframe populates with the file's column headers. Without
the .rs.digest fix the preview subprocess errored out before
returning column data and the iframe never populated.

Verified to fail when the fix is reverted (preview iframe stays
empty within the 20s timeout).

* clean up

* harden .rs.digest against int overflow for large inputs

The vectorized double-precision implementation lost integer precision
beyond ~8 MB of input (s2's worst-case 255*n*(n+1)/2 crosses 2^53), so
inputs above that ceiling would silently drift from canonical Adler-32
-- with platform-dependent results once R's long-double sum accumulator
enters the picture. Switch to chunked int32 arithmetic: process 1024
bytes at a time, with per-chunk weights k, k-1, ..., 1 fed straight
into b. All intermediate sums stay well under 2^31, so the result is
exact and identical across platforms regardless of input size.

Adds a cross-check against the byte-at-a-time recursive Adler-32 spec
at multi-chunk and chunk-boundary lengths.

* remove dead INTEGER_OR_NULL dlopen in SessionEnvironment

INTEGER_OR_NULL was added in #13544 for compact row-name detection in
ALTREP frames, then orphaned by #13938 when that detection was rewritten
to walk ALTREP class metadata via TAG/ATTRIB. The declaration and the
Library rLibrary(kLibraryName); loadSymbol(...) block have had no
callers since.

The dlopen itself was also broken on macOS: libR.dylib's install name
is the framework-versioned path (.../Versions/4.5-arm64/Resources/lib/
libR.dylib), so a bare-name dlopen never matches the already-loaded
image even though DYLD_INSERT_LIBRARIES had preloaded it. The correct
cross-platform pattern for symbol lookup in already-loaded R lives in
RRuntime.cpp (dlopen(nullptr) / GetModuleHandle(kRLibraryName)), but
there's no need to port this site -- it's dead.

Also drops the now-unused kLibraryName define and LibraryLoader.hpp
include.

* fail rstudio-tests fast when r-scope is run without a TTY on macOS

Without a controlling TTY, rsession's startup takes a different code
path and reliably SEGFAULTs during teardown -- even when the tests
themselves pass -- producing a confusing "RETCODE=139" failure with
no actionable signal in the output. Anything spawning rstudio-tests
from a non-interactive harness on macOS (CI without PTY allocation,
shell tools that pipe stdio, etc.) hits this.

Detect the case before doing R-scope setup and bail with a clear
suggestion to wrap with `script -q /dev/null`. Linux is unaffected
and the check stays out of the way there.

* downgrade rstudio-tests TTY check to a warning, skip in jenkins

The previous commit's hard error was too aggressive: Jenkins shell
steps don't allocate a PTY by default, so r-scope CI runs on macOS
would have started failing on RETCODE=1 from this script even though
the underlying r-scope tests pass fine there today.

Soften to a warning so the remediation is still visible to local
users hitting the spurious teardown SEGFAULT, and skip the warning
entirely when JENKINS_URL is set so CI logs stay quiet.

* more tweaks for pane layout tests

* auto-wrap rstudio-tests under script on macOS when stdin lacks a TTY

rsession SEGFAULTs during teardown of the r-scope tests on macOS when
stdin isn't a TTY -- the bodies pass but the process exits 139, which
reads as a real failure. Previously surfaced as a warning + Jenkins
skip. Replace with a top-of-file guard that re-execs under `script -q
/dev/null`, gated by RSTUDIO_TESTS_UNDER_SCRIPT to prevent infinite
recursion. Drops the warning text and the Jenkins-specific carve-out;
both become unnecessary once the wrap is automatic.

* address review feedback on .rs.digest changes

- Drop the now-unreachable is.na(key) guard from .rs.logMessageImpl --
  .rs.digest is total over character input after the SHA-256 -> Adler-32
  rewrite, same cleanup colsFingerprint already had.
- Polish the Adler-32 comment block in Tools.R: name 65521 as the
  largest prime below 2^16, use unambiguous sum_{i=1..k} (k+1-i)*chunk[i]
  notation, and ground the k <= 3854 bound in the actual hot expression
  b + k*a + weighted (chunk size 1024 stays well under that).
- Pin a serialize()-routed digest reference value so a future R
  serialization-format change is caught loudly rather than silently
  invalidating saved data-viewer state.
- Bracket the chunk-size boundary (n=1023 / 1024 / 1025) so an off-by-one
  in either the end-of-chunk math or the loop condition is caught --
  multi-chunk tests like n=2048 slip past several of those.
- Use fileInput.fill() in the import_dataset Playwright test instead of
  pressSequentially, so we don't race the 250ms checkForTextBoxChange
  poll on slow CI workers.

* harden playwright tests against shared-state and locator-scope flakes

Replace closeAllBuffersWithoutSaving / closeAllSourceDocs cleanups with
resetSourcePane so every test starts from a single Untitled tab. The old
"close everything" path drained the source pane through the zero-tab HIDE
animation (#17738), in which gap rstudio would auto-spawn a fresh Untitled1
that subsequent tab-scoped locators then collided with.

Scope tab-toolbar locators (publishBtn, formatOptions, knitOptions, saveBtn,
visualMdToggle) to the visible tabpanel; every open editor tab renders its
own copy of these buttons and a plain page-wide locator strict-matches
multiple elements now that single-Untitled is the steady state. The xpath
wrappers are a workaround for the missing active-tab marker -- follow-up
DOM-side simplification tracked in #17793.

Air formatting reformatCode helper now drives selectAll + reformatCode
through the window.rstudio bridge instead of Cmd+A + Cmd+Shift+A keystrokes.
The keyboard path was losing focus between the two presses on slow CI and
the reformat never fired, surfacing as a 10s opaque content-change timeout.
Add a built-in-formatter smoke probe in beforeAll so a broken reformat
machinery fails fast instead of cascading into per-test timeouts.

Capture ensurePackages failures in rmarkdown.test.ts and rmarkdown_chunks.test.ts
and skip each test with a clear reason instead of letting missing rmarkdown
cascade into multiple opaque knit/spellcheck/notebook timeouts. Bump the
install timeout to 180s since the transitive install (knitr, markdown, ...)
regularly outlasts the previous 60s default on CI.

* stabilize .rs.digest() across R versions

serialize() embeds the writer's R version in bytes 7-10 of its header,
so the digest of c("a", "b") drifted whenever rsession ran on a
different R version than the one the canonical test was pinned against
(R 4.5.3 -> 44fa02c4, R 4.1.2 -> 442e02bf). That same drift would
silently invalidate every data-viewer colsFingerprint persisted on
disk after an R upgrade.

Pin serialize(version = 2L) and zero out the writer-version field
before hashing. v2 chosen over v3 because v3 additionally embeds
R_NativeEncodingForSerialize() in the header, which varies per
platform; v2's only version-dependent field is bytes 7-10. v2 has
been the stable archival format since R 1.4.0.

Re-pin the canonical reference value and add a test that verifies
the writer-version patching is actually happening (compares against
manually-patched bytes; also asserts unpatched bytes hash differently).
gtritchie pushed a commit that referenced this pull request Jun 2, 2026
The async data-preview subprocess (R_PROCESS_VANILLA, launched from
SessionData.cpp) sources only Tools.R plus a handful of session modules
and has no RStudio embedding registered. The SHA-256-backed .rs.digest
added in #17595 lived in SessionRUtil.R (not sourced in the subprocess)
and called into rs_sha256 via the embedding (not available there
either), so the column-names fingerprint failed with "could not find
function '.rs.digest'" on any Import Dataset preview.

The fingerprint just needs a stable identity token for collision
detection, not a cryptographic hash, so move .rs.digest to Tools.R and
implement it as a vectorized Adler-32 in pure base R. The chunked int32
closed form keeps all intermediate sums within R's signed 32-bit range,
and pinning serialize(version = 2L) with the writer-version field zeroed
keeps the hash stable across R upgrades.

Drops the now-unused rs_sha256 C++ helper and its Crypto.hpp include.

Addresses #17777.
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.

3 participants