Skip to content

avoid materializing duckdb data.frame rownames - #13544

Merged
kevinushey merged 3 commits into
mainfrom
bugfix/duckdb-avoid-materialization
Aug 24, 2023
Merged

kevinushey merged 3 commits into
mainfrom
bugfix/duckdb-avoid-materialization

Conversation

@kevinushey

Copy link
Copy Markdown
Collaborator

Intent

Addresses #13540.

Approach

When computing the dimensions for an R data.frame, check whether the row.names attribute is an ALTREP vector. If it is, then use ALTREP APIs for querying information about it.

Automated Tests

N/A

QA Notes

Will be verified by duckdb users.

Documentation

N/A

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

@kevinushey
kevinushey requested a review from sharon-wang August 23, 2023 20:13
{
// Use DATAPTR_OR_NULL to allow for ALTREP vectors
// https://github.com/rstudio/rstudio/pull/13544
const int* data = (const int*) DATAPTR_OR_NULL(rowNamesInfoSEXP);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Could use INTEGER_OR_NULL if you want to avoid the cast

@sharon-wang sharon-wang 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 🦆

@kevinushey
kevinushey merged commit 09a6f0e into main Aug 24, 2023
@kevinushey
kevinushey deleted the bugfix/duckdb-avoid-materialization branch August 24, 2023 16:49
kevinushey added a commit that referenced this pull request May 28, 2026
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.
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).
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