Skip to content

fix import dataset preview by removing embedding dependency from .rs.digest - #17789

Merged
kevinushey merged 12 commits into
mainfrom
bugfix/17777-import-dataset-digest
May 28, 2026
Merged

kevinushey merged 12 commits into
mainfrom
bugfix/17777-import-dataset-digest

Conversation

@kevinushey

@kevinushey kevinushey commented May 28, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

Addresses #17777.

preview_data_import_async (in SessionData.cpp) spawns a --vanilla R subprocess to run the preview off the main session. That subprocess 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 there) and called into rs_sha256 via the embedding (also not available), so any CSV/readr/readxl/haven preview failed with:

Is this a valid CSV file? could not find function ".rs.digest"

The data viewer fingerprint just needs a stable, bounded identity token for collision detection, not a cryptographic hash. Replace .rs.digest with a closed-form vectorized Adler-32 in pure base R, living in Tools.R (already sourced by the subprocess). Drops rs_sha256 and its Crypto.hpp include.

Implementation notes

  • Adler-32 unrolled to a 3-line closed form so there's no R-level loop:
    a = 1 + sum(b)
    b' = n + (n+1)*sum(b) - sum(k*b[k])
    
    Both reduced mod 65521 (largest prime below 2^16, per the spec). Processed in chunks of 1024 bytes so every intermediate sum stays within R's signed 32-bit integer range; the hot expression b + k*a + sum_{i=1..k} (k+1-i)*chunk[i] bounds at 65520*(k+1) + 255*k*(k+1)/2, fitting up to k <= 3854.
  • Verified against the canonical Adler-32 of "abc" (0x024d0127) and against a byte-at-a-time reference. 50k random column names hash in ~4ms.
  • .rs.digest keeps the same API (raw or arbitrary R value in, fixed-size hex string out), so callers (.rs.dataViewer.colsFingerprint, the once = TRUE log-dedup path) work unchanged. The NA-on-digest-failure guards at both call sites are now unreachable and have been dropped.

Upgrade note

The fingerprint format changes from n:sha256 (#17595) to n:adler32. Any saved per-object data-viewer state (pin/width/sort/filter) carrying the old anchor will mismatch on first launch and get discarded -- one-time reset, no data loss beyond UI state. Mismatch handling itself is unchanged; only the anchor string differs. Since #17595 is still in an open milestone (Golden Wattle), no released build is affected.

Adjacent cleanups bundled in

These rode along while I was in the area; happy to peel any of them out if preferred:

  • rs_fromJSON gains a PACKAGE = "(embedding)" qualifier (src/cpp/r/R/Tools.R), matching the rest of the embedding-backed .Call sites.
  • Dead INTEGER_OR_NULL dlopen removed from SessionEnvironment.cpp; the symbol has no remaining references.
  • rstudio-tests auto-wraps itself under script -q /dev/null on macOS when stdin lacks a TTY, fixing the spurious RETCODE=139 from rsession's teardown-without-TTY SEGFAULT. Previously surfaced as a warning + Jenkins skip; now seamless, so both are gone.
  • Pane-layout Playwright tests migrated from closeAllBuffersWithoutSaving() to resetSourcePane() (avoids the no-tabs/has-tabs HIDE animation race from file.edit() can silently fail when invoked during an in-flight closeAllSourceDocs #17738; gives every test a known single-Untitled-tab starting state).

Test plan

  • ./rstudio-tests --filter "dataviewer|digest|log-message" -- 81 R tests pass (existing collision-distinguishing cases hold; new canonical-Adler-32 reference, pinned serialize() reference, and bracketed n=1023/1024/1025 boundary cases guard against algorithm and serialization-format drift)
  • ./rstudio-tests --scope rsession -- 229 C++ tests pass after removing rs_sha256
  • End-to-end repro of the failing scenario in a manually-recreated vanilla R subprocess now succeeds and returns correct column types
  • New Playwright E2E (e2e/rstudio/tests/panes/environment/import_dataset.test.ts) opens Import Dataset > From Text (readr), fills the CSV path, clicks Update, asserts the preview iframe populates with the three column headers. Verified to fail when the fix is reverted.

…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.
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).
@kevinushey kevinushey added this to the Blue Plumbago milestone May 28, 2026
@posit-snyk-bot

posit-snyk-bot commented May 28, 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.

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

Copy link
Copy Markdown
Member

Review Summary

Verdict: correct, well-tested, ready to merge with minor polish. All math, canonical reference values, and lookup paths verified independently.

Important (worth addressing before merge)

  1. Dead is.na(key) guard in src/cpp/session/modules/ModuleTools.R:53-60 — companion caller that was missed when colsFingerprint was cleaned up. Now unreachable since .rs.digest is total over character input. Same cleanup the PR already made for colsFingerprint, just at the second site.

  2. Out-of-scope changes not called out in the PR body:

    • rs_fromJSON PACKAGE = "(embedding)" qualifier at src/cpp/r/R/Tools.R:1140
    • macOS no-TTY warning at src/cpp/rstudio-tests.in:292-308
    • INTEGER_OR_NULL removal at src/cpp/session/modules/environment/SessionEnvironment.cpp:1831-1837 (confirmed safe — no remaining references in src/cpp/)

    All harmless and good cleanups, but a sentence in the PR body would explain why a digest-fix PR touches them.

  3. One-time saved-state loss after upgrade — fingerprint format changes from n:sha256 to n:adler32, so any user with saved column widths/sorts/filters from preserve dismissed summary sidebar across column pagination #17595 loses them once. Code handles this correctly (mismatched anchors are discarded), but worth a note in the PR body.

Suggestions (nice-to-have)

  1. Comment polish in src/cpp/r/R/Tools.R:1093-1106:

    • k <= 3854 is slightly conservative; actual int32 ceiling is k = 4103 (still proves 1024 is safe)
    • The expression sum((k+1-i)*chunk[i]) reads ambiguously — clarify as sum_{i=1..k} (k+1-i) * chunk[i]
    • Modulus 65521 (largest prime < 2^16) isn't named in the comment block
  2. Test coverage gaps (none blocking, but easy wins):

    • Pin a non-raw serialize() value: all chunked tests use charToRaw/as.raw. Real callers pass character vectors via serialize(). One pinned expect_identical(.rs.digest(c(\"a\",\"b\")), \"<hex>\") would catch R serialization-format drift across R versions.
    • Boundary at exactly n=1024 is more fragile than the existing n=2048 test. An off-by-one in end <- min(pos + size - 1L, n) would pass at 2048 and fail at 1024. The current "exact chunk boundary" comment at src/cpp/tests/testthat/test-dataviewer.R:191 is also misleading — 2048 is two full chunks, not the boundary case.
    • readxl/haven paths in the Playwright test — the bug affected all four import sources, current test only exercises readr.
  3. Playwright reliability: consider fileInput.fill(csvPath) instead of pressSequentially to avoid racing the 250 ms checkForTextBoxChange poll on slow CI workers (e2e/rstudio/tests/panes/environment/import_dataset.test.ts:67).

  4. Vague phrasing in src/cpp/rstudio-tests.in:292: "rsession's startup takes a different code path" is hand-wavy — either link to a tracking issue or just describe the symptom.

Recommended Action

  1. Clean up the stale is.na(key) guard at src/cpp/session/modules/ModuleTools.R:54.
  2. Add a sentence to the PR body about the bundled cleanups and the one-time saved-state reset.
  3. Optional: pin a serialize()-based reference value and an n=1024 boundary test.
  4. Optional: tighten the comments noted in PAM Session Prototype #4.

Nothing here is blocking.

@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! Some minor feedback but nothing blocking.

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.
- 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.
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.
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).
@kevinushey
kevinushey merged commit 9bc95f9 into main May 28, 2026
7 of 8 checks passed
@kevinushey
kevinushey deleted the bugfix/17777-import-dataset-digest branch May 28, 2026 18:15
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