Skip to content

feat: New experimental dbClearArrowChunk() to release a fetched Arrow chunk - #797

Merged
krlmlr merged 5 commits into
mainfrom
claude/db-clear-arrow-chunk
Nov 29, 2026
Merged

krlmlr merged 5 commits into
mainfrom
claude/db-clear-arrow-chunk

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

This PR adds a new experimental generic dbClearArrowChunk(res, chunk, ...). Who owns the memory of a chunk returned by dbFetchArrowChunk() 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 res as well as chunk, and dispatch is on res, like dbBindArrow(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 from DBIResultArrow, 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 to dbClearArrowChunk(), also after further chunks are fetched and after dbClearResult(). After dbClearArrowChunk() 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 after dbClearResult() is allowed. Calling the function is optional. A missing chunk is an error.

The default method for DBIResultArrow releases a chunk that is a nanoarrow array with nanoarrow::nanoarrow_pointer_release(), does nothing for any other chunk, and returns TRUE invisibly. A data frame converted from a fetched chunk with as.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 of dbBind(). vignettes/spec.md and spec.html are regenerated from man/ accordingly. Tests in tests/testthat/test-arrow.R cover the default method. Spec tests belong in DBItest: r-dbi/DBItest#609 asks for a check that a backend overrides both dbFetchArrowChunk() and dbClearArrowChunk(), or neither.

Name-clash check: a GitHub code search for dbClearArrowChunk and for clearArrowChunk returned no results, so no backend defines a function of that name.

Part of #758.

https://claude.ai/code/session_01Hr1rd3s7NRVkLyg3an422b


Generated by Claude Code

…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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: Which DBItest spec tests should cover dbClearArrowChunk()?

This PR adds dbClearArrowChunk(res, chunk, ...) as an experimental generic. Its default method for DBIResultArrow is a no-op that returns invisible(TRUE), so no backend has to implement it. Spec tests belong in DBItest, in a new spec_arrow_clear_arrow_chunk topic, which DBI would then inherit with @inherit and @inheritSection. No DBItest issue has been opened, and none will be without your go.

  • (recommended) Behavior only. The call returns TRUE invisibly. The result set stays valid, so the next dbFetchArrowChunk() works. Calling it twice is harmless, and so is calling it after dbClearResult(). Every backend passes these tests with the default method, and backends can still implement a real release later.
  • The behavior tests, plus a test that a chunk fetched before another one stays usable as long as it is not cleared. This pins down that the caller owns the chunk, which an implementation that reuses buffers would fail.
  • No spec tests yet, until a backend such as duckdb implements a real release.
  • A DBItest test that a backend overrides either both the fetch and the clear methods for chunks, or neither (answered in feat: New experimental dbClearArrowChunk() to release a fetched Arrow chunk #797 (comment)).

The answer asks for the override test only; the options above were not ticked.


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: Should the default dbClearArrowChunk() method release the chunk, or do nothing?

The default method for DBIResultArrow is currently a no-op. Backends such as adbi and duckdb have result classes that inherit from DBIResultArrow, and they use this default until they add their own method. With a no-op default, dbClearArrowChunk(res, chunk) frees nothing for a duckdb chunk, which is the case #758 is about. Users would still have to call nanoarrow::nanoarrow_pointer_release() themselves. The clean review found that nanoarrow_pointer_release() is safe to call twice, and that a data frame already converted from the chunk, including ALTREP strings, stays readable afterwards. That was checked in a local experiment and is not covered by a test.

  • (recommended) Release chunks that inherit from nanoarrow_array with nanoarrow::nanoarrow_pointer_release(), and do nothing for any other chunk. This makes the generic useful at once for every backend that returns nanoarrow arrays, and it matches the documented rule that the chunk must not be used after the call. The cost is that code which keeps using the chunk afterwards breaks instead of working by accident.
  • Keep the no-op. It is safe for every caller, but memory is freed only once each backend implements its own method, so Memory ownership after dbFetchArrowChunk() not specified #758 stays unsolved in practice.

Answered in #797 (comment): the default frees the chunk if it is a nanoarrow array (the first option).


Generated by Claude Code

…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
@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 11:06
@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

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?

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

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 dbFetchArrowChunk() returns, nanoarrow first moves each string column out into its own independent owner (array_xptr_ensure_independent() in src/array.h). Releasing the chunk after as.data.frame() is therefore safe: in a test with 2e6 rows and int, double, string and list columns, every column stayed readable after the release and gc(). The string memory stays alive for as long as the data frame holds it, so an early release frees less than one might expect. One caveat: for a top-level string array that is not a struct, releasing after convert_array() crashes R, because nothing was moved out. The same goes for an array that was handed to another library with nanoarrow_pointer_export(), the route arrow takes, which still points at the original top-level buffers.

Could a subclass do it? Yes, for as.data.frame() only. A class c("dbi_arrow_chunk", "nanoarrow_array") with an as.data.frame() method that calls NextMethod() and then nanoarrow_pointer_release() works, and a second conversion errors cleanly with "already been released". But each of these skips the subclass, so the chunk stays alive:

  • convert_array(), which dispatches on to and not on the array
  • tibble::as_tibble()
  • basic_array_stream() with convert_array_stream()
  • nanoarrow_pointer_export(), the route arrow takes
  • access through $children

"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: as.data.frame.nanoarrow_array_stream() always releases its stream. It owns the ALTREP and move rules, so it could also make the top-level string case safe. nanoarrow_pointer_move() exists, but no option releases an array on conversion, and an issue search found no request for one.

The direction is a separate question below.


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: How should "free the chunk on conversion" be pursued, next to dbClearArrowChunk()?

Releasing a struct chunk right after as.data.frame() is safe, as the previous comment shows. The choices differ in where the automatic release lives and how many conversion paths it covers.

  • (recommended) Keep dbClearArrowChunk() as the explicit, portable hook in this PR, and propose upstream in apache/arrow-nanoarrow an option for as.data.frame() / convert_array() to release the array after conversion, the way the stream method already does. This covers every conversion path once nanoarrow has it, including the top-level string case. It needs an upstream issue (not opened without your go) and later a version dependency.
  • In addition, make the default dbFetchArrowChunk() chunks a DBI subclass whose as.data.frame() method releases the chunk. This frees memory now for the most common call, but silently does nothing for convert_array(), tibble, streams and arrow. It also changes the class of what dbFetchArrowChunk() returns.
  • Only dbClearArrowChunk(), with no automatic release anywhere.

Answered in #797 (comment): the generic stays, because users might do Arrow-y things with each chunk, and apache/arrow-nanoarrow#1043 is filed upstream (the first option).


Generated by Claude Code

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Create a reproducer to post to the nanoarrow repo as a comment here.

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

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 nanoarrow_array after conversion to a data frame

Proposed text (everything below the line):


as.data.frame() on a nanoarrow_array_stream releases the stream, but as.data.frame() and convert_array() on a nanoarrow_array keep the array alive until it is garbage collected. Database interfaces that hand out record batches one at a time, such as DBI's dbFetchArrowChunk(), would like each batch's memory to be freed as soon as it has been converted. For a struct array, releasing it explicitly after conversion is safe, because the columns are moved out first. For a top-level string array, the same release is a use-after-free: the ALTREP vector keeps pointing at the freed buffers. In four runs, the child process below crashed twice and failed twice with "negative length vectors are not allowed".

Request: an option that releases the array after conversion, for example as.data.frame(x, release = TRUE) or an argument to convert_array(), that is also safe for the top-level case.

# 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

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

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.

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

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 dbFetchArrowChunk() and dbClearArrowChunk(), or neither.

  • (recommended) You file it with the command below, which has not been run. It prints the new issue's URL. Reply here with that URL, and the PR will link it.
  • Allow this session to attach r-dbi/DBItest, for example by adding a permission rule for add_repo or by answering the prompt next time, and the session files it.
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)
```
BODY

Filed 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

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

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 status: open records that its work is still open. These open issues by Kirill came up in this session's work. They stay open until this is answered.

For each issue, applying the rule means a closing comment that says why, closing it as "not planned", and adding status: open, with the label created where it is missing. The search also found 3 more open issues by Kirill in r-dbi/DBI and 24 more in r-dbi/DBItest that this work did not touch, so they are not listed here.

Options:

  • (recommended) Apply the rule to the six issues listed. This session cannot attach r-dbi/DBItest, so it applies the rule to the two DBI issues and hands the four DBItest ones over as commands to run.
  • Apply it to the two DBI issues only.
  • Leave all of them open for now.
  • Apply it to every existing issue by Kirill in r-dbi/DBI and r-dbi/DBItest (answered in chat). Done on 2026-11-29: 5 issues in DBI and 28 in DBItest are closed as "not planned" with a comment and carry status: open.

Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 18:29
@krlmlr
krlmlr merged commit 8aa8040 into main Nov 29, 2026
9 checks passed
@krlmlr
krlmlr deleted the claude/db-clear-arrow-chunk branch November 29, 2026 18:29
krlmlr added a commit to r-dbi/DBItest that referenced this pull request Dec 1, 2026
)

* 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]>
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