Skip to content

feat: Fetch a result as Arrow struct chunks through a row sink - #954

Draft
krlmlr wants to merge 6 commits into
claude/rb-vendor-nanoarrowfrom
claude/rb-arrow-chunks
Draft

krlmlr wants to merge 6 commits into
claude/rb-vendor-nanoarrowfrom
claude/rb-arrow-chunks

Conversation

@krlmlr

@krlmlr krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

No change of behavior for users: this adds the first Arrow feature behind an unexported entry point. result_fetch_arrow_chunk(res, n) fetches at most n rows of a result, all of them for n = -1, into a nanoarrow_array of a struct type, with its schema in the tag of the external pointer as the nanoarrow package expects. RSQLite creates both external pointers itself (arrow_owning_xptr() in src/result.cpp): a struct allocated with malloc() and a NULL release callback until it is filled, the class nanoarrow_array or nanoarrow_schema, and a C finalizer that calls release if it is set and frees the struct, as nanoarrow/r.h of nanoarrow 0.4 to 0.9 does; the array's tag holds the schema's external pointer and keeps it alive. Other values of n are refused. No DBI method calls it yet.

The rows go through a new SqliteArrowChunkSink, the second implementation of the SqliteRowSink from #950, so an Arrow chunk shares the fetch loop with dbFetch(): the one-row read-ahead and its kept error (#933), the busy guard (#934), an error that ends the fetch and completes the result (#935), and the row count of rows returned. DbArrow.h holds check_arrow(), which turns a nanoarrow error code into a C++ exception so that the arrays under construction are released on every error; SqliteResultImpl.h and DbResult.h only declare the Arrow structs.

Scope of this layer: each chunk types its columns on its own, int64 once a value is an integer and the null type while all values are NULL (also for a chunk of no rows). A real, text or blob value fails the chunk with "Column x: Arrow arrays of real values are not supported yet." (or text, blob), which ends the execution like any error of a fetch. Doubles and the rule that the first chunk fixes the types come in the next layer, text and blobs after it.

An SQLite error that ends an Arrow fetch is raised as the usual RSQLite_error but without a rows field: the sink's finish(failed = TRUE) returns NULL and builds no array, so rows read before the error are lost (they still count in dbGetRowCount()). A partial chunk would be cheap to build in C++, but returning it would need the RSQLite_fetch_error path of result_fetch() and an R wrapper around the entry point; it can be added when a DBI method wraps the entry point. The warnings of dbFetch() about statements without columns and about rows dropped by dbSendStatement() are not raised for Arrow chunks.

A result is fetched either as data frames or as Arrow arrays, whichever reads rows first (SqliteResultImpl::claim_fetch_kind(), right after the one check that the result is bound). The other kind then fails with an error of class RSQLite_error_fetch_kind from abort_fetch_kind() in R/fetch-kind.R, also after a new dbBind(). dbFetch(n = 0), dbColumnInfo(), dbHasCompleted(), dbGetRowCount(), dbGetRowsAffected(), dbBind(), and fetches refused before they read rows (unbound result, invalid n, inactive result) don't claim it, and a refused fetch leaves the result as it was. A data-frame fetch of a statement without columns claims the result before its "should only be used with SELECT" warning and keeps the claim when options(warn = 2) turns the warning into an error, since a data frame is what the user asked for.

DESCRIPTION adds nanoarrow (>= 0.4.0) to Suggests only, for the tests: the C library is the vendored one from #953, and the external pointers are created in RSQLite, so nanoarrow is not a build dependency (#954 (comment)).

Tests in tests/testthat/test-arrow-chunks.R with fixtures in helper-arrow.R, all skipped without nanoarrow: int64 and null columns, int64 at -2^63, 2^63 - 1 and beyond 2^53; per-chunk typing; chunk boundaries (n = 1, k, exactly the row count, -1, past the end), comparing values, dbHasCompleted() and dbGetRowCount() after each chunk with dbFetch() on a separate result; a chunk ending on the last row releasing the read lock; an empty result and a statement without columns; a kept read-ahead error raised by the next chunk, and a step error inside a chunk ending the fetch, both without a rows field; a busy handler that can neither clear the result nor fetch from it during an Arrow chunk; real, text and blob values failing the chunk and completing the result; an unbound query, invalid n and a cleared result; exclusivity in both directions, with snapshots of the messages; the claim kept by a data-frame fetch whose warning fails under options(warn = 2); and a chunk that nanoarrow's as_nanoarrow_array(), infer_nanoarrow_schema(), print(), nanoarrow_array_set_schema(validate = TRUE) and convert_array() accept, with its schema outliving it. Each test_that() block passes on its own right after pkgload::load_all(). Full suite with NOT_CRAN=true: FAIL 0, WARN 3 (locale warnings in test-encoding.R), SKIP 63, PASS 11594. The vendored nanoarrow's symbols stay out of the shared object's exports; chunks built under gctorture2(1) validate and convert correctly with nanoarrow 0.4.0 and 0.9.0, and valgrind reports no leaks or memory errors for fetching, converting, dropping and failing chunks.

Questions carried over from #859: the question on values after the first chunk typed their column as null (#859 (comment)) does not apply to this layer, since each chunk types its columns on its own, but comes back with the next layer, which fixes the types with the first chunk. The question on chunks kept after RSQLite is unloaded (#859 (comment)) still applies: the release callback and the finalizer live in RSQLite's shared library, and a chunk kept across detach("package:RSQLite", unload = TRUE) still crashes R at the next garbage collection (checked against this head).

Layer F1a of the rebuilt chain, planned in #880; based on #953. Ported from #859 (draft), onto the row sink instead of #859's fetch_loop() template, and cut down to int64 and null columns.

Coordinating session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4


Generated by Claude Code

The internal `result_fetch_arrow_chunk(res, n)` fetches at most `n` rows, all of them for -1,
into a `nanoarrow_array` of a struct type with its schema in the tag of the external pointer.
No DBI method calls it yet.
`SqliteArrowChunkSink` collects the rows as a second `SqliteRowSink`,
so a chunk gets the read-ahead, the kept error, the busy guard and the row count of `dbFetch()`.

Each chunk types its columns on its own:
int64 once a value is an integer, the null type while all values are NULL.
A real, text or blob value fails the chunk with an error that names the column,
which ends the execution like any error of a fetch.
An SQLite error that ends an Arrow fetch carries no rows.

A result is fetched either as data frames or as Arrow arrays, whichever reads rows first.
The other kind fails with an error of class `RSQLite_error_fetch_kind`, also after `dbBind()`.
`dbFetch(n = 0)`, `dbColumnInfo()`, the state of the result, `dbBind()`,
and fetches refused before reading rows don't claim it.

nanoarrow goes to `LinkingTo` for `nanoarrow/r.h`, and to `Suggests` for the tests.

Ported from #859.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
@krlmlr
krlmlr added this pull request to stack #928 December 1, 2026 04:36

krlmlr commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

Question: keep Arrow chunks valid after RSQLite is unloaded?

Carried over from #859's question, which nobody answered; it still applies to this pull request, which ports #859's chunks onto the row sink: a chunk still held after detach("package:RSQLite", unload = TRUE) crashes R at the next gc(), reproduced on this head. The links below point at #859's lines.

An Arrow chunk kept after detach("package:RSQLite", unload = TRUE) crashes R at the next garbage collection, because its release callback lives in RSQLite's shared library, which .onUnload() unloads (src/result.cpp#L50). A connection kept across the unload crashes the same way already. Against this pull request's head:

# Run in a separate R process because it crashes
res <- try(callr::r(function() {
  library(RSQLite)
  con <- DBI::dbConnect(RSQLite::SQLite())
  rs <- DBI::dbSendQuery(con, "SELECT 1 AS x")
  chunk <- RSQLite:::result_fetch_arrow_chunk(rs@ptr, -1L)
  DBI::dbClearResult(rs)
  DBI::dbDisconnect(con)
  detach("package:RSQLite", unload = TRUE)
  # Expected: the chunk is released without a crash
  rm(chunk)
  gc()
  "survived"
}, libpath = .libPaths()), silent = TRUE)
cat(attr(res, "condition")$stderr)
#> 
#>  *** caught segfault ***
#> address 0x7ff09a075d10, cause 'memory not mapped'
#> An irrecoverable exception occurred. R is aborting now ...
  • Accept it, as for connections: unloading a package with live objects is rare (recommended)
  • Keep RSQLite's shared library loaded while a chunk exists, for example by skipping library.dynam.unload() in .onUnload() then

Kirill decides. If nobody decides, the behavior stays, and the limitation stays checked in the "Accepted limitations".


Generated by Claude Code

krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member Author

Question: should RSQLite take nanoarrow as LinkingTo only for nanoarrow/r.h?

This pull request adds nanoarrow (>= 0.4.0) to LinkingTo (and to Suggests for the tests). The C library itself is vendored (#953), so the R package is needed at build time only for nanoarrow/r.h, which creates the external pointers that hand an ArrowArray and ArrowSchema to R as nanoarrow objects. LinkingTo makes nanoarrow a build dependency of RSQLite on every platform and for every reverse dependency that builds RSQLite from source, although nothing in RSQLite calls nanoarrow's R code. The old #859's review suggested creating the two external pointers in RSQLite instead (about 30 lines: allocate the structs, set the class nanoarrow_array/nanoarrow_schema and a finalizer that calls release), which keeps nanoarrow in Suggests only.

  • Create the external pointers in RSQLite and drop nanoarrow from LinkingTo (recommended: no new build dependency for an internal feature, about 30 lines, and the objects stay compatible with nanoarrow's R functions as long as the class and finalizer contract hold)
  • Keep LinkingTo: nanoarrow, which follows nanoarrow's own helpers exactly and costs a build dependency

Implemented on 2026-12-01: the recommended option is in 6a955b9; no box is ticked, and ticking another option changes it.

If nobody decides, the recommended option goes in with the fixes of this pull request's review.


Generated by Claude Code

krlmlr and others added 5 commits December 1, 2026 04:42
RSQLite no longer links to nanoarrow at build time:
nanoarrow stays in Suggests for the tests.
result_fetch_arrow_chunk() makes the external pointers itself,
with the class, the finalizer and the schema in the array's tag
that the nanoarrow package expects, see its nanoarrow/r.h.
A test checks that nanoarrow converts, prints and validates a chunk,
and that its schema outlives it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
The claim moves from DbResult to SqliteResultImpl,
right after the one check that the result is bound,
so that check_ready() runs once per fetch and stays private.
The errors and their order are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
A data-frame fetch of a statement without columns
claims the result before its warning,
and keeps the claim when options(warn = 2) makes the warning an error:
the user asked for a data frame.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4

This branch has not been deployed

No deployments
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