Repository navigation
feat: New experimental dbClearArrowChunk() to release a fetched Arrow chunk - #797
Conversation
…ow chunk The memory ownership of a chunk returned by `dbFetchArrowChunk()` was unspecified. The new generic documents that the caller owns the chunk, and gives backends a portable hook to free its memory early. The default method for `DBIResultArrow` is a no-op returning `TRUE` invisibly. Part of #758. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd3s7NRVkLyg3an422b
Resolved: Which DBItest spec tests should cover
|
Resolved: Should the default
|
…from the fetch docs The default method signals an error when `chunk` is missing, instead of silently returning `TRUE`. `dbFetchArrowChunk()` and the Arrow data retrieval flow now point to `dbClearArrowChunk()`. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd3s7NRVkLyg3an422b
|
Is it possible to configure a chunk in such a way on creation that the memory is freed as soon as it's converted to a data frame? Could a subclass achieve it? Should this be something that nanoarrow provides? |
|
Short answer: partly with a subclass, and fully only in nanoarrow. Details are from the nanoarrow 0.9.0 sources and experiments with the installed package. Is releasing after conversion safe? Converting a chunk to a data frame copies numeric, logical and list columns into ordinary R vectors. String columns stay zero-copy, as ALTREP vectors that point at the Arrow buffers. For a struct chunk, which is what Could a subclass do it? Yes, for
"Free on conversion" would then depend on which function the caller happens to use. Should nanoarrow provide it? That would be the right long-term home. nanoarrow already consumes streams this way: The direction is a separate question below. Generated by Claude Code |
Resolved: How should "free the chunk on conversion" be pursued, next to
|
|
Create a reproducer to post to the nanoarrow repo as a comment here. |
|
Reproducer for an issue in apache/arrow-nanoarrow, drafted here and not posted there. It runs against nanoarrow 0.9.0, the current CRAN release. Proposed title: Option to release a Proposed text (everything below the line):
Request: an option that releases the array after conversion, for example # Motivation: a DBI backend returns record batches via dbFetchArrowChunk();
# callers want each batch's memory freed as soon as it is converted to a data frame.
library(nanoarrow)
df <- data.frame(i = 1:3, s = c("a", "b", "c"))
# 1. A stream is released by as.data.frame() ...
stream <- as_nanoarrow_array_stream(df)
invisible(as.data.frame(stream))
nanoarrow_pointer_is_valid(stream) # FALSE: released
#> [1] FALSE
# ... but a struct array is not: its buffers are held until the R object is GC'ed
array <- as_nanoarrow_array(df)
invisible(as.data.frame(array))
invisible(convert_array(array))
nanoarrow_pointer_is_valid(array) # TRUE: still holds its buffers
#> [1] TRUE
# 2. Releasing a struct array explicitly after conversion is safe
n <- 1e6
array <- as_nanoarrow_array(data.frame(s = sprintf("value-%07d", seq_len(n))))
res <- as.data.frame(array)
nanoarrow_pointer_release(array)
invisible(gc())
res$s[c(1, n)] # "value-0000001" "value-1000000"
#> [1] "value-0000001" "value-1000000"
# 3. For a top-level string array, release after convert_array() is a use-after-free:
# the ALTREP vector reads freed memory (garbage, error, or segfault).
# Run in a child process so this session survives.
crash <- function() {
library(nanoarrow)
array <- as_nanoarrow_array(sprintf("value-%05d", 1:20000))
v <- convert_array(array)
nanoarrow_pointer_release(array)
invisible(replicate(50, sprintf("zzzzzzzzzz-%05d", 1:20000)))
c(v[1], v[20000]) # expected: "value-00001" "value-20000"
}
tryCatch(
callr::r(crash),
error = function(e) conditionMessage(if (is.null(e$parent)) e else e$parent)
)
#> [1] "! callr subprocess failed: could not start R, exited with non-zero status, has crashed or was killed"
# Request: an option (e.g. `as.data.frame(x, release = TRUE)` / in `convert_array()`)
# that releases the array after conversion, safe also for the top-level case.Created on 2026-11-29 with reprex v2.1.1 Generated by Claude Code |
|
Filed apache/arrow-nanoarrow#1043 . We want the new generic anyway because users might do Arrow-y things with each chunk. Change the implementation to free the chunk if it's a nanoarrow Array. File an issue in DBItest to add a test that a backend either overrides both fetch and clear methods for chunks, or none. |
Resolved: How should the DBItest issue for the fetch/clear override test be filed?This session could not attach r-dbi/DBItest: the permission check refused the request. A search of DBItest issues for "ArrowChunk" and for "arrow chunk" found no existing issue. The draft is below, with the title Check that backends override both
gh issue create -R r-dbi/DBItest \
--title 'Check that backends override both `dbFetchArrowChunk()` and `dbClearArrowChunk()`, or neither' \
--body-file - <<'BODY'
DBI is gaining an experimental generic `dbClearArrowChunk(res, chunk, ...)` (r-dbi/DBI#797, for r-dbi/DBI#758). It releases a chunk returned by `dbFetchArrowChunk()`. DBI's default method for `DBIResultArrow` frees the chunk with `nanoarrow::nanoarrow_pointer_release()` if it is a nanoarrow array, and does nothing otherwise.
A backend that overrides `dbFetchArrowChunk()` knows how its chunks own their memory, and DBI's default clear method does not. A backend that overrides only one of the two methods can end up with a clear method that does not match how its chunks are produced. DBItest should check that a backend's result class overrides both methods or neither.
- [ ] Add a spec test, for example in `spec-arrow-fetch-arrow-chunk.R` or a new `spec_arrow_clear_arrow_chunk` topic, that checks that the result class of `dbSendQueryArrow()` either has its own methods for both `dbFetchArrowChunk()` and `dbClearArrowChunk()`, or for neither (it inherits both from DBI).
- [ ] Skip the test when the installed DBI has no `dbClearArrowChunk()`.
- [ ] Once released, DBI inherits the spec text through `@inherit DBItest::spec_...`.
Sketch of the check (not run, needs DBI with r-dbi/DBI#797):
```r
res <- DBI::dbSendQueryArrow(con, "SELECT 1 AS a")
cls <- class(res)
own <- function(generic) {
m <- methods::selectMethod(generic, cls)
!identical(m@defined[[1]], "DBIResultArrow")
}
testthat::expect_identical(own("dbFetchArrowChunk"), own("dbClearArrowChunk"))
DBI::dbClearResult(res)
```
BODYFiled as r-dbi/DBItest#609. Generated by Claude Code |
…ethod The default method for `DBIResultArrow` now releases chunks that are nanoarrow arrays and still does nothing for other objects. A data frame converted from a struct chunk stays valid after the release. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd3s7NRVkLyg3an422b
Also fixes a semantic line break in the documentation. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd3s7NRVkLyg3an422b
Resolved: Apply the closed-issue rule to the open issues by Kirill that this work touched?Under the new rule, an issue by Kirill in a repository he maintains stays closed as "not planned", and the label
For each issue, applying the rule means a closing comment that says why, closing it as "not planned", and adding Options:
Generated by Claude Code |
) * feat: Specify `dbClearArrowChunk()` and add it to the DBI generics DBI 1.4.0 adds the experimental generic `dbClearArrowChunk()` (r-dbi/DBI#797), which made DBItest's own test of the generics list fail. The list now includes it, the test and the reexport spec drop it when the installed DBI lacks it, and backends only need to reexport it from `dbitest_version = "1.9.0.1"` on. New `spec_arrow_clear_arrow_chunk` specs the contract that DBI's default method guarantees; they skip with older tweaks and older DBI. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd43pnoHuAnGBgMih89 * fix: Drop the spec for calling `dbClearArrowChunk()` without a chunk DBI documents no error for a missing `chunk`; only its default method raises one, so backends cannot be held to it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd43pnoHuAnGBgMih89 * feat: Allow DBI to export generics that DBItest does not know yet The test of the generics list now checks only that DBI still exports every generic DBItest knows, via the new internal `missing_dbi_generics()`, so a later DBI release that adds a generic no longer breaks a released DBItest. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd43pnoHuAnGBgMih89 * chore: Add a release bullet for rerunning `create_generics()` Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Hr1rd43pnoHuAnGBgMih89 --------- Co-authored-by: Claude <[email protected]>
This PR adds a new experimental generic
dbClearArrowChunk(res, chunk, ...). Who owns the memory of a chunk returned bydbFetchArrowChunk()has not been specified so far. Under tight memory, users currently release chunks through nanoarrow directly, which ties their code to one Arrow implementation. The generic gives them a portable way to say that a chunk is no longer needed, and gives backends a hook to free that memory early. It is useful also when users do other Arrow work with each chunk rather than converting it to a data frame.The signature takes
resas well aschunk, and dispatch is onres, likedbBindArrow(res, params, ...). The backend that produced the chunk knows how its memory was allocated, so the result class is the natural dispatch target. A backend can then override the method without defining methods on nanoarrow or arrow classes. The result classes of adbi and duckdb inherit fromDBIResultArrow, so they reach the default method.Semantics, as documented in the roxygen: the caller owns the chunk returned by
dbFetchArrowChunk(). The chunk stays valid until it is garbage collected or passed todbClearArrowChunk(), also after further chunks are fetched and afterdbClearResult(). AfterdbClearArrowChunk()the chunk must not be used again, and a chunk handed to another library must not be cleared before that library is done with it. The result set stays valid and more chunks can be fetched. Clearing a chunk twice is harmless, and clearing afterdbClearResult()is allowed. Calling the function is optional. A missingchunkis an error.The default method for
DBIResultArrowreleases a chunk that is a nanoarrow array withnanoarrow::nanoarrow_pointer_release(), does nothing for any other chunk, and returnsTRUEinvisibly. A data frame converted from a fetched chunk withas.data.frame()stays valid after the release, string columns included, because nanoarrow 0.9.0 moves the columns of a struct array out on conversion. Vectors converted from a non-struct array are not safe after a release; an option in nanoarrow to release on conversion is requested in apache/arrow-nanoarrow#1043.The new function is listed in the Arrow section of the pkgdown reference, linked from
dbFetchArrowChunk(), and named as an optional step in the Arrow data retrieval flow ofdbBind().vignettes/spec.mdandspec.htmlare regenerated fromman/accordingly. Tests intests/testthat/test-arrow.Rcover the default method. Spec tests belong in DBItest: r-dbi/DBItest#609 asks for a check that a backend overrides bothdbFetchArrowChunk()anddbClearArrowChunk(), or neither.Name-clash check: a GitHub code search for
dbClearArrowChunkand forclearArrowChunkreturned no results, so no backend defines a function of that name.Part of #758.
https://claude.ai/code/session_01Hr1rd3s7NRVkLyg3an422b
Generated by Claude Code