Skip to content

feat: Add arrow argument to dbConnect() to route data frames through Arrow - #796

Closed
krlmlr wants to merge 43 commits into
claude/elegant-tesla-mja103from
claude/elegant-tesla-mja103-arrow-option
Closed

krlmlr wants to merge 43 commits into
claude/elegant-tesla-mja103from
claude/elegant-tesla-mja103-arrow-option

Conversation

@krlmlr

@krlmlr krlmlr commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Stacked on #795 (base branch claude/elegant-tesla-mja103; retarget to main once #795 is merged). Adds dbConnect(..., arrow = FALSE): with arrow = TRUE, data frames travel through the native Arrow interface introduced in #795.

  • dbFetch() fetches its rows as Arrow arrays typed for that fetch, the way the default path types it, and converts them with one set of rules, in R/arrow-df.R: nanoarrow's conversions, except that int64 columns become integer when every value fits and follow the bigint argument otherwise, also in later fetches once a value needed 64 bits, and null columns become logical. A column that sees only NULL stays open until its first value, integers widen to double, a column without a value takes its declared type or logical, and the next fetch starts from these types, also after dbBind(). Times and timestamps travel as doubles in seconds, so they keep the default path's precision and range, times outside a day included, and text ends at its first NUL and is not checked for UTF-8, as on the default path; streams have microseconds, only times of day, and only text that is valid UTF-8 without NUL bytes, and make other values NULL with a warning. Three differences are documented: a real number after an integer too large for an integer makes the column a double, which rounds integers beyond 2^53, where the default path truncates the real; -2147483648 is a value here and NA on the default path; and a blob in a text column is text only if it is valid UTF-8 without NUL bytes, as in a stream, NA with a warning otherwise, where the default path cuts it at its first NUL (until fix: Validate blobs that are read into a text column #799). Once dbFetchArrow() or dbFetchArrowChunk() has fixed a result's types, data frame fetches keep them and the rules of a stream (microseconds; times outside a day, timestamps beyond the microseconds and invalid text become NULL), and hand out the rows kept for a schema or held back by the byte limits. dbFetch(n) gathers arrays until it has n rows, since feat: Implement the DBI Arrow interface natively #795 can end an array early. Date, hms, POSIXct (UTC) and blob columns come out as on the default path; fetching from a statement returns an empty data frame with the same warning as the default path. With arrow = TRUE, dbColumnInfo() answers from the Arrow columns: it names the types that a fetch of no rows returns and, like the default path, decides them for the next fetch, without converting the values of the next row.
  • dbAppendTable() writes the data frame as an Arrow stream through dbAppendTableArrow(), after the same preparation as the default path (factors to strings, lists of raw vectors to blobs, POSIXlt to POSIXct, which the default path can't write, and difftime, POSIXct and Date to their numbers in their own units). dbGetQuery(), dbReadTable() and dbWriteTable() follow, since they are built on these two.
  • The option is stored on the connection and propagated when a connection is cloned, together with bigint and extended_types, which a clone dropped before. It is documented in ?SQLite and in the "Data frames" section of ?"sqlite-arrow". Experimental, the default stays FALSE.
  • A data frame fetch through Arrow is covered by feat: Implement the DBI Arrow interface natively #795's guard against re-entry: a warning handler of the fetch that uses the same result gets an error instead of using freed memory.

Memory. A benchmark of this path (below) found three problems, fixed in 75ea617:

  • A fetch of n rows kept every chunk alive behind its data frame: nanoarrow's character vectors read from the Arrow array until they are touched. The strings are now copied out and the array released right away.
  • A fetch of all rows held the result twice, as Arrow arrays and as the data frame, because nanoarrow::convert_array_stream() collects every array of a stream of unknown size before it converts. Every dbFetch() now goes through result_fetch_arrow_df(), which hands it the arrays as a list with their lengths and formats: a single array is converted directly with its strings copied, and several are copied into columns allocated once with the row count known, each array released as soon as it has been copied.
  • A loop over dbFetchArrowChunk() that discards its chunks piled them up as garbage the collector does not see. dbFetchArrowChunk() now triggers a collection of the young generation after every 64 MB of arrays handed out; the "Chunking" section of ?"sqlite-arrow" says so and points to nanoarrow::nanoarrow_pointer_release() for tighter loops.
  • The check whether 64-bit integers fit into an integer vector moved to C++ (integer64_to_integer()), which spares the temporary vectors it needed in R.

Benchmark. experiments/2026-09-26-arrow-df-fetch/ records it in the shape of the shared experiments convention: bench.R fetches a synthetic table of one and five million rows (integers, reals, two text columns, NULLs) per strategy in fresh subprocesses and records wall time and peak RSS; the four CSV files hold the runs before (83bb24e) and after (75ea617) the fixes, and the README carries the tables and the findings. On five million rows: a full fetch through Arrow takes about a third less time than on the default path on every query (12.1 against 17.8 s for all columns), at 823 against 679 MB above the 100 MB floor (1,081 MB before the fixes); a chunked fetch of 10,000 rows runs at 7.1 s and 131 MB against 9.5 s and 99 MB on the default path (230 MB and growing before); a dbFetchArrowChunk() loop that discards its chunks stays at 113 MB (366 MB before). Re-measured at one million rows on d2013e3: full and chunked fetches are within noise of the record. Small fetches cost more than on the default path: 20,000 calls of dbFetch(rs, 1) take 2.3 s against 0.66 s. experiments/ is in .Rbuildignore, and the arrow argument's source carries a plain comment pointing at the record.

DBItest: tests/testthat/test-DBItest-arrow.R runs the whole suite a second time with arrow = TRUE through a second, non-default context, with the same skips as the default run. Both runs pass locally, as do the unit tests in tests/testthat/test-arrow-df.R, which compare both paths with expect_identical() on mixed, NULL-first, declared, blob and 64-bit columns over several sequences of small n and several bindings, and cover results larger than one chunk, arrays cut short by the byte limits, fractional times and timestamps, times outside a day, text that is not UTF-8, and the ownership of strings fetched in chunks. Random comparisons over thousands of tables found no differences beyond the documented ones. The tests pass with and without the arrow package installed (CI's smoke job does not install it; arrow is in Suggests since #795). The full suite has four errors here that need a local HTTP server or an installed RSQLite (test-httpvfs.R, the callr test in test-dbConnect.R).

Review

Two clean-context reviews: the first (2026-09-27) found one High finding (a small first fetch fixed the column types before a value was seen, and data was lost) and three Low ones; the second confirmed those fixes and found two Medium issues (sub-microsecond precision lost on times and timestamps, types reset by dbBind()) and five Low ones. All are fixed or documented, except the mixed-type warning once per result, which #800 replaces. #795 is merged up to 68a1cbc; the remaining limitations will be listed in an "Accepted limitations" comment after a final clean review of the whole stack.

What remains is listed under Accepted limitations.

The test fixtures this pull request adds live in tests/testthat/helper-arrow.R, so every test_that() block runs on its own right after load_all().

https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6


Generated by Claude Code

…ugh Arrow

With `dbConnect(arrow = TRUE)`, `dbFetch()` fetches rows as Arrow arrays through `dbFetchArrowChunk()`
and converts them with one set of rules,
and `dbAppendTable()` writes data frames as Arrow streams through `dbAppendTableArrow()`;
`dbGetQuery()`, `dbReadTable()` and `dbWriteTable()` follow.
The conversion is nanoarrow's, except that `int64` columns become `integer` when every value fits
and follow the `bigint` argument otherwise, and `null` columns become `logical`,
which reproduces the data frames of the default path.
The DBItest suite runs a second time with the option through a second, non-default context.
The default stays `FALSE`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6
@krlmlr
krlmlr added this pull request to stack #797 September 20, 2026 14:08
krlmlr and others added 5 commits September 26, 2026 12:27
`dbFetch()` on a connection with `arrow = TRUE` held more memory than the default path:
a data frame fetched in chunks kept every chunk alive through nanoarrow's lazy strings
until the garbage collector ran,
a full fetch held the whole result as Arrow arrays while the data frame was built from them,
and a loop over `dbFetchArrowChunk()` that discards its chunks piled them up as garbage
that the collector does not see.

A chunk fetched with `dbFetch(n)` now copies its strings out of the array and frees it right away.
A full fetch reads all chunks first, through a stream that hands each array out once,
so that the columns are allocated once with the row count known,
and each array is freed as soon as it has been copied into them.
`dbFetchArrowChunk()` triggers a collection of the young generation
after every 64 MB of arrays it handed out.
The check whether 64-bit integers fit into an integer vector moved to C++,
which spares the temporary vectors it needed in R.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6
An experiment under `experiments/`, in the shape of the shared convention,
measures how long it takes to fetch a large table into a data frame
and the peak memory of the fetch, per strategy,
on the head of this branch before the memory fixes and on the commit with them.
The `arrow` argument of `dbConnect()` leans on it,
through a plain comment in its source, since `experiments/` is not shipped.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6
…w-option' into claude/elegant-tesla-mja103-arrow-option
The formatting run regenerated two stubs with the absolute paths of its own library,
which no other machine can resolve.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EpBkzNMeuMBGy4nxTafYH6

krlmlr commented Sep 27, 2026

Copy link
Copy Markdown
Member Author

Review of this PR at 09c5111, by a Claude Code reviewer with clean context that read the diff against claude/elegant-tesla-mja103, ran targeted R snippets against a build of the whole stack, and posted nothing itself. Line numbers refer to that commit. "Confirmed" means reproduced by running code.

High

1. A small first fetch on arrow = TRUE freezes the column types before a value is seen, and data is lost. R/arrow-df.R:17 calls result_fetch_arrow_chunk(res@ptr, n) with the user's n, bypassing check_chunk_size(), and SqliteResultImpl::fetch_arrow_rows() (src/SqliteResultImpl.cpp:410-449 on #795) then runs finish_chunk(), where undecided columns fall back to the declared type or null, and freeze_arrow_columns() unconditionally. Confirmed with a table t (x, y INTEGER) holding (NULL, NULL), (1, 2.5), ('a', 3): on the default path dbFetch(rs, 0); dbFetch(rs) gives x = <int> NA 1 0 and y = <num> NA 2.5 3; with arrow = TRUE it gives x = <lgl> NA NA NA, every value dropped into a null column, and y = <int> NA 2 3, the real truncated to fit an int64 decided from the integer, plus a coercion warning. The same happens with dbFetch(rs, 1) first. The existing test only covers a first row without NULLs. Suggested fix: for n_max == 0 build the empty array from provisional types without deciding or freezing, and more generally keep a column open until its first non-NULL value on the data frame path, which does not hand out a schema before all chunks are read (dbFetch(-1)) and converts each dbFetch(n) chunk on its own, like the default path types each fetch; the Arrow stream keeps freezing, since its schema is a contract. Add NULL-first tests with n = 0 and n = 1. This is inherited by #800 to #807.

Low

2. dbAppendTable() on arrow = TRUE bypasses sqlData(), with one observed divergence. A difftime in minutes is written as 120 (seconds, through nanoarrow's duration) where the default path writes 2. Confirmed. Factors (with the same warning), latin1 strings (translated to UTF-8 by nanoarrow), logical NA, NaN, POSIXct instants and Dates matched. Suggested fix: convert difftime with as.numeric() in arrow_prepare_df(). Also, dbConnect(con) cloning now carries arrow, but still drops bigint and extended_types; that predates this PR (confirmed) and is a one-line fix in the same place.

3. "Freed as soon as converted" is one garbage collection later for the columns nanoarrow's convert_array_stream() fills: the converter only swaps the previous batch's external pointer out of its shelter (convert.c, nanoarrow_converter_set_array), so the memory returns at the next collection. Informational; the peak-RSS numbers in the experiment record stand, the wording in ?"sqlite-arrow" could say "released" rather than "freed".

Checked and found sound

  • integer64_to_integer() excludes INT_MIN; db_arrow_buffered_stream_init() calls fetch_arrow() directly, so exceptions propagate as C++ exceptions; character columns are copied before their array is released; the young-generation collection valve is per session and bounded.
  • An R-level warn_coercion() called from C++ (the stack above this PR) survives options(warn = 2) and an exiting handler through the lazy stream.
  • test-arrow-df.R passes on the build of the whole stack; empty results and zero-column statements behave the same on both paths.

Generated by Claude Code

@krlmlr krlmlr left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The findings of the clean-context review, placed on the code they concern; the summary comment above carries the full report and the checks that came out sound. Line positions refer to the current head, with #795 and main merged in.


Generated by Claude Code

Comment thread R/arrow-df.R Resolved
Comment thread R/arrow-df.R Resolved
Comment thread R/dbConnect_SQLiteConnection.R Resolved
Comment thread R/arrow.R Resolved
…mja103-arrow-option

Brings in the reworked #795: the merge of `main`, the fixes from its two reviews, and the corrected dependency rule.
The conflicts were additions on both sides.
The "Chunking" section of `?"sqlite-arrow"` takes the new description of the stream, followed by this branch's paragraph on the collection of discarded arrays.
`src/DbArrowStream.*` and `src/result.cpp` keep both the buffered stream and `integer64_to_integer()` from this branch and the test hooks of #795.
`R/cpp11.R` and `src/cpp11.cpp` are regenerated with `cpp11::cpp_register()`, `man/sqlite-arrow.Rd` with roxygen2, and `src/result.dd` lists the headers of both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The data frame path calls the release callback of each array once it is converted, and the memory goes back when its owners let go of it.
"Releases" says what the code does, "frees" promised more, as the review of the path pointed out for the arrays that nanoarrow's converter keeps until the next garbage collection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
With `arrow = TRUE`, `dbFetch()` fetched the requested `n` rows as the first Arrow chunk of the result, which fixed the types of all later chunks before a value had been seen.
After `dbFetch(rs, 0)` or `dbFetch(rs, 1)` over a NULL first row, a column without a declared type became the null type and dropped every later value, and an `INTEGER` column truncated the real numbers that followed.
A fetch of all rows had the same problem past the first 65,536 rows.

A data frame fetch now keeps the types open, the way the default path types each fetch.
A column that sees only NULL stays undecided across the arrays of a fetch, integers widen to double in any of them, and the arrays are conformed to the final types at the end of the fetch.
A column without a value takes its declared type, or `logical` without one, which the next fetch decides again.
The other types carry over to the next fetch, and so does the need for 64-bit integers, which keeps a column `integer64` in later fetches as on the default path.
Once an Arrow stream or `dbFetchArrowChunk()` has fixed the types of a result, data frame fetches keep them, and they also hand out the rows kept for a schema.
The one remaining difference is documented: a real number after an integer too large for an `integer` makes the column a double, where the default path truncates it.

`dbFetch(n)` gathers arrays until it has `n` rows or the result is complete, since an array can end early at the byte limits of a text or blob column or with the rows kept for a schema.
`n` is capped at 2^53 before it reaches the 64-bit cast in C++.
A fetch of `n` rows and a fetch of all rows now share one path, which allocates the data frame once with the row count known.
`dbFetch(n = 0)` on a statement no longer warns, like the default path.

The tests compare both paths over mixed and NULL-first columns for several sequences of small fetches, with one and two rows per array, and over a result larger than one array.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
With `arrow = TRUE`, `dbAppendTable()` handed a `difftime` column to nanoarrow, which writes it as a duration in seconds: two minutes became 120, two weeks 1,209,600.
The default path binds the number in the column's own units.
`arrow_prepare_df()` now turns `difftime` columns into those numbers before writing, which also covers `hms`, whose units are seconds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`dbConnect()` on an existing connection passed on the database, the VFS, the flags, the extensions and `arrow`, but not `bigint` and `extended_types`, so the clone fell back to `integer64` and to untyped dates and times.
It now passes both on.

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

On the default path, `dbFetch()` fails while rows that a stream's schema fetched are waiting.
With `arrow = TRUE`, `dbFetch()` reads through the Arrow arrays and hands them out, which the "Data frames" section of `?"sqlite-arrow"` now says next to the sentence on fixed types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
Since a fetch of `n` rows shares the path of a fetch of all rows, a `dbFetch(n)` loop over a large table copied every column of each array into newly allocated columns.
The extra garbage raised the peak of such a loop by 11 to 22 MB above the floor on three of the four queries of the benchmark in `experiments/2026-09-26-arrow-df-fetch/`, at one million rows in chunks of 10,000.
When one array holds all rows of a fetch, nanoarrow's columns now become the data frame, with the character vectors copied before the array is released, as before the shared path.
The peaks are back within a few MB of the build before it, and the timings and the fetch of all rows are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
krlmlr pushed a commit that referenced this pull request Nov 10, 2026
…legant-tesla-mja103-warnings

The coercion log takes over #795's design of the current row:
the storage class comes from `read_row()` and the bytes of a text value from `fetch_bytes()`,
so the UTF-8 check of a blob in a text column reads the bytes that the byte limits counted.
`append_row()` keeps the 1-based row number as its only argument, computed after the byte check,
so a row held back to the next chunk is logged with its own number.
The `AK_INT64` branch logs where it warned, after reading the value once.
The Arrow test helpers of #796 move to `helper-arrow.R` with the others,
and the tests that matched the old warning text match its class or its new text.
The dependency files are regenerated through the fixed rule, without absolute paths.

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

krlmlr commented Nov 10, 2026

Copy link
Copy Markdown
Member Author

Review of the fixes at 101248d (the merge of #795 in e425ac0 and the six commits after it), by a Claude Code reviewer with clean context that read the six commits and the merge's conflict resolutions, ran the package's Arrow and DBItest files, compared arrow = TRUE with arrow = FALSE over a fixed matrix and random tables, ran the rebuild paths under valgrind, and posted nothing itself. Line numbers refer to that commit. "Confirmed" means reproduced by running code.

The first review's findings

  • High 1, a small first fetch freezes the column types: fixed: the first review's table and dbFetch(rs, 0) / dbFetch(rs, 1) sequences now give the default path's data frames, and so do my own comparisons below, apart from the new findings.
  • Low 2a, difftime written in seconds: fixed: secs, mins, hours, days, weeks and hms columns are stored identically on both paths (Confirmed), and removing the two lines at R/arrow-df.R:149-150 makes the new test fail.
  • Low 2b, dbConnect(con) drops bigint and extended_types: fixed: removing the line at R/dbConnect_SQLiteConnection.R:11 makes the new test fail.
  • Low 3, "freed" versus "released": fixed: R/arrow.R:88-90 now says "releases", and devtools::document() leaves the man/ pages unchanged.

New findings

Medium

1. With extended_types = TRUE, times and timestamps lose everything below a microsecond on arrow = TRUE, in both directions, so a POSIXct or hms round trip is no longer exact. Confirmed with 1000 POSIXct values of one second of 2026 with random fractions and 1000 random hms values, written with dbWriteTable() and read with dbReadTable(): on the default path all 1000 of each come back identical; reading the default-written file through Arrow gives 224 identical timestamps (differences up to 4.8e-7 s) and 0 identical times; writing through Arrow stores only 229 of the 1000 timestamps exactly (up to 9.5e-7 s off). The read side is src/SqliteArrowColumn.cpp:473, which rounds seconds to int64 microseconds for time64[us] and timestamp[us]; the write side is nanoarrow's POSIXct conversion behind R/arrow-df.R:127. A double holds about 0.24 µs at today's epoch, so values from Sys.time() are affected. R/arrow.R:70-72 says these columns come back "as on the default path", and no test compares fractional seconds across the paths. This code comes from the base of the stack and is not changed by the six commits, but it breaks the equivalence that 50e7453 sets out to restore. The same line turns any value beyond about ±9.2e12 seconds into -9223372036854.775 (Confirmed with 9223372036855, 1e19 and 1e300 in a TIME or TIMESTAMP column; the cast of an out-of-range double to int64_t is also undefined behaviour), where the default path returns the number. Suggested fix: on the data frame path, carry times and timestamps as doubles in seconds and set the class in arrow_to_df(), and convert POSIXct columns to numbers in arrow_prepare_df() as is now done for difftime (which already makes hms exact on write); otherwise list it among the exceptions in ?"sqlite-arrow". Clamp or reject out-of-range values before the cast in either case.

2. dbBind() resets the column types on the Arrow path; the default path keeps them for the life of the result. after_set_params() clears arrow_columns_ (src/SqliteResultImpl.cpp:433), which also drops the 64-bit flags, whereas the default path's types survive a new binding. Confirmed with CREATE TABLE t (k, v, w, s) holding (1, 1.5, 4294967296, 'a'), (2, NULL, 1, NULL), (3, 2, 2, 5), (4, 'x', 2.5, 1.5) and SELECT v, w, s FROM t WHERE k = ?, binding 1, 2, 3, 4, 99 in turn and fetching each: the default path returns <numeric>, <integer64>, <character> every time, including for the empty result of 99; arrow = TRUE returns <logical>, <integer>, <logical> for 2, <integer>, <integer>, <integer> for 3, <character>, <numeric>, <numeric> for 4 (v = "x" where the default path gives 0) and three logical columns for 99. One binding with several parameter rows matches on both paths. The per-binding typing is arguably the saner one, but it is not listed as an exception and a bind-and-fetch loop gets columns that change class. Suggested fix: carry each column's type and 64-bit flag over in after_set_params() when the data frame path is the reader (a stream still has to start afresh), or document the difference; add a test that binds twice.

Low

3. -2147483648 comes back as NA on the default path and as a value on the Arrow path. note_integer() (src/SqliteArrowColumn.cpp:291) treats it as needing 64 bits, which is right for R, while the default path stores it as a 32-bit integer, where it is NA_integer_. Confirmed: SELECT -2147483648 AS x UNION ALL SELECT 1 gives <integer> NA 1 by default and <integer64> -2147483648 1 through Arrow. The Arrow result is the correct one; the suggested fix is to name it among the exceptions in R/arrow.R:76-80, or to fix the default path separately.

4. The exception for a real after a wide integer costs integer precision, which the documentation does not say. R/arrow.R:79-80 says the column becomes a double where the default path truncates the real. Confirmed that 9007199254740993 in such a column comes back as 9007199254740992 and 9223372036854775807 as 9223372036854775808, for every bigint setting, where the default path keeps the integers exact and truncates the real. Suggested fix: one more clause in that sentence.

5. A mixed-type warning is given once per result on the Arrow path and once per fetch on the default path. warned is set at src/SqliteArrowColumn.cpp:533 and never cleared. Confirmed with a column holding 1, 'a', 'b', 2, 'c' fetched one row at a time: three warnings by default, one through Arrow, and the wording speaks of an "Arrow type int64 decided from the first values" on a path that returns data frames. Suggested fix: clear the flag at the start of fetch_arrow_df() (src/SqliteResultImpl.cpp:296).

6. A text value with an embedded NUL fails the fetch on the Arrow path and the rows of that fetch are lost. Confirmed with CAST(x'610062' AS TEXT): the default path returns "a", arrow = TRUE stops with embedded nul in string: 'a\0b' from the conversion at R/arrow-df.R:56-57 (or :77), after dbGetRowCount() has advanced past the rows of the fetch. Not introduced by these commits. Suggested fix: document it, or cut at the first NUL when appending to a utf8 column on the data frame path.

7. A fetch of few rows costs about twice what it did before these commits, and about ten times the default path. Confirmed with 20000 calls of dbFetch(rs, 1) on a three-column table: 1.0 s by default, 5.6 s at e425ac0, 9.7 s at 101248d. A profile puts most of it in R: arrow_df_ptype() reading child$format (R/arrow-df.R:100), array$length through the array proxy (:51, :70) and [<-.data.frame (:57). Fetching all 2 million rows of a table is faster through Arrow (1.5 s against 2.6 s), as is fetching it in chunks of 50000 (1.6 s against 2.1 s). Suggested fix: return the formats and the first array's length from result_fetch_arrow_df(), and replace df[] <- lapply(...) by a loop over the character columns.

Checked and found sound

  • Typing of each fetch: 57600 comparisons over six tables (NULL-first, mixed storage classes, declared and undeclared types, blobs, 64-bit integers, dates and times, empty, all-NULL), five queries, fifteen sequences of dbFetch(n) with n from 0 to 100 and -1, four bigint settings, extended_types on and off, one to three rows per array, and byte limits lowered with arrow_set_bytes_limits() to (1, 2), (3, 5) and (1, 1e9). Data frames, dbGetRowCount() and dbHasCompleted() match after every fetch, except for the documented real-after-wide-integer case. 11500 random tables with random declared types, values, sequences, array sizes and byte limits differ only by findings 1, 3 and 4; 6000 further random tables without those value combinations show no difference at all.
  • The rebuild of earlier arrays (src/SqliteArrowColumn.cpp:241-275): a null-typed array followed by each of int64, double, utf8, binary, date32, time64 and timestamp, and int64 followed by double, across up to 40 arrays per fetch, with and without byte limits, runs without a valgrind report and gives the default path's values.
  • 101248d: the result is identical to the copying path in all comparisons above; reading a nanoarrow string vector after its array was released is clean under valgrind.
  • An error in the middle of a fetch (a warning under options(warn = 2)) leaves the result usable: the row that raised it is read again by the next fetch, and the earlier rows of the failed fetch are gone, as on the default path.
  • Rows kept for a schema: after dbFetchArrow() has fetched its first chunk, dbFetch(rs, 0), dbFetch(rs, n) and dbFetch(rs) hand the kept rows out with the frozen types and correct row counts, a stream read in between continues after them, and dbBind() discards them and makes the old stream fail with a clear message.
  • Statements, zero-row results, duplicate and empty column names, row.names, n of NA, Inf, 2^53 + 2 and 1e308, a cleared result and an unbound query behave the same on both paths.
  • The merge e425ac0 keeps both sides in R/arrow.R, src/DbArrowStream.*, src/result.cpp, and the generated files match the registered functions.
  • Tests, with NOT_CRAN=true: test-arrow-df.R (89 expectations), test-arrow.R (167, the opt-in large test skipped) and both DBItest files (8388 expectations each) pass. Reverting each of the typing fixes locally makes a test fail.

Generated by Claude Code

…me path

With `extended_types = TRUE` and `arrow = TRUE`, times and timestamps travelled as `time64[us]` and `timestamp[us]`, so everything below a microsecond was lost in both directions.
A value like those of `Sys.time()` needs more, and a `POSIXct` or `hms` round trip was no longer exact as on the default path.

A data frame fetch now stores times and timestamps as doubles in seconds, the numbers the default path reads, and `arrow_to_df()` gives them the classes `hms` and `POSIXct` in UTC.
Every Arrow entry point selects the arrays it builds, so streams and `dbFetchArrowChunk()` keep microseconds.
Before writing, `POSIXct` and `Date` columns become their numbers like `difftime` columns, which the default path binds as they are.
After a stream has fixed the types of a result, data frame fetches keep its microseconds, which `?"sqlite-arrow"` says.

The out-of-range cast of a time or timestamp to microseconds stays on the stream path and is left to #795.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
On the default path, the column types of a result survive `dbBind()`: a bind-and-fetch loop gets the same classes every time, also for a binding without rows.
On the Arrow path, a new binding cleared the columns with their types and 64-bit flags, so the classes changed with the values of each binding, and a text value could come back where the default path coerces it.

The types and 64-bit flags that the last data frame fetch left are now kept, and the first data frame fetch of a new execution starts from them, the null type undecided.
An Arrow stream still decides its types afresh, since its schema describes the rows of one execution.
The test binds six times on both paths and compares the data frames for three sequences of fetches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
#795 marks a result busy while one of its fetches or binds runs, so that a handler of a warning raised by the fetch cannot use the statement under it.
`DbResult::fetch_arrow_df()`, the data frame fetch of `arrow = TRUE`, now takes the same guard; without it, a handler that fetched from the result crashed the session.
The test runs `dbFetch()`, `dbBind()`, `dbClearResult()`, `dbColumnInfo()` and `dbFetchArrowChunk()` from a handler of the mixed-type warning, and checks that the result is usable afterwards.

A fetch of no rows reads the storage classes of the next row without converting any value, so it no longer marks the row as held back, which would make the default path refuse it.
`?"sqlite-arrow"` now says that data frame fetches hand out a row held back by the byte limits and keep the range of times and timestamps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`withr::defer()` registers its cleanup with `on.exit()` on the test's frame, and a later `on.exit()` without `add = TRUE` replaced it.
The connections of `local_arrow_con()` were then left open, hence a "call dbDisconnect()" warning, and the test that lowers the Arrow byte limits never restored them, so that a later test file in the same session cut its chunks at 150 bytes.
The `on.exit()` calls of `test-arrow-df.R` now add to the cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in the time-of-day check for `time64` and the UTF-8 check for `utf8` columns.
The data frame path keeps its own rules, which match the default path.
Its time branch, which appends doubles in seconds, still runs before the range check,
so a time outside a day keeps its value there.
Its text values are still cut at the first NUL and are not checked for UTF-8,
while blobs in a text column are checked on both paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…e checks of #795

The data frame path through Arrow keeps a time outside a day as an `hms` duration,
and passes text through unchecked up to its first NUL, as the default path does,
where a stream now makes such values `NULL`.
A blob in a text column is checked as in a stream,
where the default path ends it at its first NUL byte.
Once a stream or chunk has fixed the types, data frame fetches follow the rules of a stream.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…hat is not UTF-8

The test that expected an Arrow chunk to keep the bytes after a NUL now expects `NULL`,
which is what #795 makes of such text.
Both data frame paths are compared on times outside a day and on text that is not valid UTF-8,
in one fetch and in several,
and a stream and the data frame fetches after a chunk are checked to make them `NULL`.
A blob in a text column is checked on the data frame path too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`SqliteResult.cpp` includes `SqliteResultImpl.h`, which has included the Arrow headers since the Arrow interface came in,
but its `.dd` file still listed the headers of before.
Regenerated with `g++ -MM` through `src/Makevars.deps`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in arrow in Suggests, for the test that runs Arrow's full validation behind a skip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
krlmlr pushed a commit that referenced this pull request Nov 10, 2026
…nt-tesla-mja103-schema

Brings in #800 at dc4776e, with #796 and #795 below it.
The column builder takes #800's open typing of data frame fetches (`data_frame`, `storage_kind()`, `seconds_class()`, `carry_over()`, `get_kind()`, `discard_coercions()`) and keeps this branch's kinds, unit, time zone and `append_*()` functions.
`append_string()` takes #800's NUL cut for text in a data frame and its UTF-8 check of text and blobs in a stream, for `utf8` and `large_utf8`; numbers into text stay silent here.
`append_time()` replaces #795's time branch: it parses, then hands a data frame its seconds, then checks the range of the unit and the day, for decided and requested types alike.
A requested type wins: a new `requested` flag keeps it out of the seconds storage of a data frame fetch and out of `carry_over()` after `dbBind()`.
`DbResult::set_arrow_schema()` and `get_column_names()` take `BusyScope` like the other entry points.
`arrow_df_column_ptype()` falls back to nanoarrow's prototype for the other formats that a requested type gives, `uint64` is an `integer64`, and `large_utf8` columns are copied like `utf8` before their array goes.
The arrow-schema test reads the arrays of a data frame fetch from the new list of `result_fetch_arrow_df()`.
The generated dependency files are unchanged, and NAMESPACE keeps the import that the development roxygen2 drops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`dbColumnInfo()` still ran the default path's peek of the next row, which knows nothing of the Arrow columns.
It reported the type of the next row instead of that of the data frames, did not fix the types before the first fetch as the default path does, and converted a waiting blob to text in place, which changed what the next fetch returned.

With `arrow = TRUE`, `dbColumnInfo()` now runs a data frame fetch of no rows.
That fetch reads the storage classes of the next row without converting a value, decides the types for the next fetch as the default path's peek does, and names them as the default path names them.
It also answers before the parameters are bound, from the declared types, like the default path.
The comparison test asks `dbColumnInfo()` before every fetch of its sequences, and a new test covers the cases of the review: a mixed column after two fetches, a NULL-first `INTEGER` column, blobs in a text column, an unbound query and a statement.

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

`?SQLite` said that fetching a large table in chunks takes much less time through Arrow.
The measurements show less, not much less: about 1.4 against 1.5 s for chunks of 10,000 rows of one million, and 1.8 against 2.7 s for the whole table.
A fetch of a few rows costs more: 20,000 calls of `dbFetch(rs, 1)` take about 2.3 s against 0.7 s.
The `arrow` argument now says "less" for whole and chunked fetches and names the cost of small ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`arrow_prepare_df()` converted `POSIXlt` columns to `POSIXct` only after the check of list columns, and a `POSIXlt` column is a list, so `dbAppendTable()` failed with "Can only write lists of raw vectors (or NULL)" before reaching the conversion.
The conversion now comes first, and the column is written as the seconds of a `POSIXct`.
The default path can't write such a column ("Parameter 2 does not have length ..."), which `?"sqlite-arrow"` now says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in the CI hook that runs the Arrow test with real column sizes.

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

krlmlr commented Nov 10, 2026 •

Copy link
Copy Markdown
Member Author

Accepted limitations

Two clean reviews of this pull request, at 09c5111 and 101248d, the first integration review (its findings 1, 8 and 10, fixed in c1e6800, 30cbe91 and f925e3d) and the second integration review (which found nothing new in this layer; #796's own ISNAN() call is now std::isnan() in 33e0809, and result_fetch_arrow_df() releases parked results) are addressed up to 33e0809, which closes the review rounds for the stack. Every High and Medium finding is fixed; the mixed-type warning given once per result (Low finding 5 of the second review) is replaced by the warning per fetch of #800. These remain:

  • R/arrow.R#L96: a real number that follows an integer too large for an integer makes the column a double, which keeps the real number but rounds the integers beyond 2^53 (9007199254740993 comes back as 9007199254740992), where the default path keeps the integers and truncates the real number. Relevance: low; reviewer's confidence: high. (recorded)
  • R/arrow.R#L99: -2147483648 is a value that needs 64 bits and follows bigint, where the default path reads it as a 32-bit integer, which is NA in R. Relevance: low; reviewer's confidence: high. (recorded)
  • R/arrow.R#L85: a blob in a text column becomes text only if it is valid UTF-8 without NUL bytes, as in a stream, and NA with a warning otherwise, where the default path ends it at its first NUL byte without a check; fix: Validate blobs that are read into a text column #799 brings the default path in line. Relevance: low; reviewer's confidence: high. (recorded)
  • R/arrow.R#L101: once dbFetchArrow() or dbFetchArrowChunk() has fixed the types of a result, later data frame fetches keep them and the rules of a stream: times and timestamps in microseconds, times of day only, and text checked like a blob, with the values a stream makes NULL coming back as NA. Only hit when Arrow and data frame fetches are mixed on one result. Relevance: low; reviewer's confidence: high. (recorded)
  • R/arrow.R#L110: a fetch holds its rows as Arrow arrays while the data frame fills, so it peaks above the default path: 823 against 679 MB above the floor for a full fetch of five million rows (261 against 155 MB for the numeric columns alone), and 131 against 99 MB for a loop over chunks of 10,000 rows, as recorded in experiments/2026-09-26-arrow-df-fetch/. Relevance: low; reviewer's confidence: high. (recorded)
  • R/arrow.R#L140: the garbage collector does not see the memory of the arrays that dbFetchArrowChunk() hands out, so a loop that discards them holds up to 64 MB of them as garbage before the collection of the young generation that RSQLite then triggers; a tighter loop has to release each array with nanoarrow::nanoarrow_pointer_release(). Relevance: low; reviewer's confidence: high. (recorded)

Generated by Claude Code

…mja103-arrow-option

Brings in the busy mark reset through `R_ExecWithCleanup()`, the checks of Arrow parameters,
the 64-bit row counter and the UTF-16 text in binary columns.

The data frame fetch through Arrow now runs its body through `run_guarded()`,
like the other guarded methods of `DbResult`, with the same body and return value.
`src/result.cpp` keeps both includes, `<climits>` and `integer64.h`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in the bytes of a blob in a `utf8` column kept as they are, also in a UTF-16 database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in the state of the Arrow test hooks kept in each result:
the byte limits and the count of rethrown unwinds belong to a result,
set with `result_set_bytes_limits()` and read with `result_rethrown_unwinds()`.

`SqliteResultImpl` keeps the carried data frame types next to the byte limits of the result,
and `src/result.cpp` keeps `integer64_to_integer()` next to the new hook.
`src/cpp11.cpp`, `R/cpp11.R` and `src/result.dd` are regenerated.

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

The global test hook is gone: the test of a fetch across arrays cut short
sets the byte limits of its own result after it is sent, with no limits to restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in Arrow streams read safely on worker threads, with the "Threads" section of `?"sqlite-arrow"`,
the scanner tests, the memory cleanup of the large tests with `helper-memory.R`, and the longjmp tests.

The chunking section keeps the paragraph on the garbage collection of `dbFetchArrowChunk()` arrays,
and the new "Threads" section follows it.
The data frame path through Arrow adds no R call to the stream callbacks:
its buffered stream is read on R's main thread by `result_fetch_arrow_df()`.
`src/connection.dd` lists `DbArrow.h`, which `DbArrowStream.h` includes on this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…mja103-arrow-option

Brings in the atomic busy mark that records the thread holding a result,
the stream's execution checked inside it, the atomic row count and completion,
the results that streams let go of on other threads closed from the main-thread entry points,
NaN tested without R in the column builders, and the tests that read streams on a thread of their own.

`DbResult` keeps the data frame fetch next to the new parameters of `arrow_schema()` and `fetch_arrow()`.
`result_fetch_arrow_df()`, the data frame fetch of this branch, drops the parked results first,
like `result_fetch()`, and `result_fetch_arrow_chunk()` keeps its list with the bytes of the array.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The time and timestamp branch of the data frame path still used R's `ISNAN()`,
which the column builders no longer call, as they may run on a thread other than R's main thread.
It now uses `std::isnan()` like the rest of them.

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

`local_arrow_con()` and `fetch_sequence()` move from the top of `test-arrow-df.R` into `helper-arrow.R`, which `pkgload::load_all()` sources.
Every `test_that()` block now runs on its own after `load_all()`.
Each helper keeps its code, and `local_arrow_con()` gains a comment saying what it is for.

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

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Marked as a draft, as decided: this pull request is the reference for the reworked Arrow stack, which carries its changes in smaller, separately reviewed pull requests (see the plan). So far: #855, #856, #857, #859 to #867 (GitHub stack 851 on #830 and #850), and #852, #853, #854 and #858 from main. It will be closed once its replacements are merged.


Generated by Claude Code

krlmlr commented Nov 30, 2026

Copy link
Copy Markdown
Member Author

Closed as superseded, as decided: the Arrow work is rebuilt from main as a chain of smaller pull requests, planned on #880. The data-frame path through Arrow that this stack carries (group D) is tracked in #881. The branch stays as a reference.


Generated by Claude Code

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