Skip to content

feat: Implement the DBI Arrow interface natively - #795

Closed
krlmlr wants to merge 55 commits into
mainfrom
claude/elegant-tesla-mja103
Closed

krlmlr wants to merge 55 commits into
mainfrom
claude/elegant-tesla-mja103

Conversation

@krlmlr

@krlmlr krlmlr commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Query results are written from the SQLite statement straight into nanoarrow arrays, and Arrow arrays are bound straight to statement parameters, without passing through R vectors.

  • dbSendQueryArrow() returns the new SQLiteResultArrow class. dbFetchArrow() returns a lazy nanoarrow_array_stream that fetches one chunk per get_next(), and dbFetchArrowChunk() returns one such array per call. A result set is never materialized as a whole on the Arrow path.
  • A chunk holds at most chunk_size rows (default 65536; it must be finite and is capped at 2^53), and it ends early before any text or blob column would pass the 2^31 - 1 bytes its 32-bit offsets can address. Rows read ahead to determine the schema are kept and handed out by later fetches, also smaller ones; dbHasCompleted() and dbGetRowCount() count them only once they are handed out, and a data-frame dbFetch() fails while such rows, or a row held back by the byte limit, wait. Fetched rows are counted in 64 bits, so a stream can read past INT_MAX rows; dbGetRowCount() returns the count as an integer while it fits, as before, and as a double beyond.
  • The stream shares ownership of the C++ result, so it stays readable after dbClearResult() (which is what dbGetQueryArrow() needs), while other queries run, and after dbDisconnect(); until it is read to the end or released, it keeps the statement, a read transaction and the database file open. It fails once its result is bound to new parameters with dbBind() or dbBindArrow(). After dbDisconnect(), an SQLite error raised through it carries only SQLite's generic message for the error code.
  • dbBindArrow() binds Arrow streams batch by batch, executing the statement once per row; dbAppendTableArrow(), dbWriteTableArrow() and dbCreateTableArrow() build on it. Named placeholders are matched to column names like dbBind() does it. Binding a result to a stream of its own rows is rejected; a parameter row that fails to bind ends the execution, and a failed first row requires a new bind. The indices of a dictionary column are checked against the dictionary, and text and blobs are bound with 64-bit sizes, so a value beyond SQLite's length limit gives its "string or blob too big" error.
  • A result refuses to be fetched from, bound, inspected or cleared while one of its own fetches or binds is running, as from a handler of a warning that the fetch raised; before, such re-entry could use freed memory. The mark is reset through R_ExecWithCleanup(), so also when an R error leaves the fetch by a longjmp instead of through cpp11 (a raw allocation that fails, an ALTREP parameter, a parameter stream of another package that calls R); such a longjmp still skips the C++ destructors of the frames it leaves.
  • Result columns keep the SQLite values intact: integers are always int64, reals double, text utf8, blobs binary, and with extended_types = TRUE the declared DATE, TIME and DATETIME/TIMESTAMP columns become date32, time64[us] and timestamp[us, UTC]. SQLite is dynamically typed, so the first chunk decides the types (the first non-NULL value, widening int64 to double if a real turns up, the declared type for columns that only held NULL). Values an Arrow array cannot hold become NULL with a warning, so every array passes Arrow's full validation: text or blobs in a utf8 column that are not valid UTF-8 without NUL bytes, times outside a day, and timestamps beyond the int64 microseconds. Text in a binary column is its UTF-8 bytes, also in a UTF-16 database, as on the data frame path. A blob in a utf8 column keeps its bytes for the UTF-8 check, also in a UTF-16 database, where SQLite would otherwise transcode it. See ?"sqlite-arrow" for the full mapping, the parameter mapping, and the chunking rules.
  • The nanoarrow C library 0.9.0 is vendored in src/vendor/nanoarrow (with NANOARROW_NAMESPACE set to RSQLite, documented in the README there), and the nanoarrow package is a new dependency; arrow is suggested, for a test that runs Arrow's full validation where it is installed. The result external pointer now owns a shared pointer, the same idiom the connections use.
  • SQLite errors raised while fetching are C++ exceptions rather than R errors, so that they can cross the Arrow stream callbacks (nothing may longjmp through the consumer's C frames); cpp11 turns them into the same R errors at the entry points. The stream callbacks continue a cpp11::unwind_exception with R_ContinueUnwind(), as cpp11's own wrapper does, except when RSQLite binds one of its own streams, where they rethrow it through C++ so that RSQLite's frames unwind.
  • src/Makevars.deps now drops system headers on every line of the generated .dd files, including gcc's one-space continuation lines; before, CI's auto-update could commit absolute runner paths into them, which breaks a source install anywhere else.
  • Arrow streams can be read on any thread, one call at a time, as the C stream interface allows: arrow's scanner, Acero (behind its dplyr verbs) and arrow::write_dataset() call get_next() on worker threads, and the scanner and Acero read ahead in the background while R goes on. On a thread other than R's main thread, RSQLite calls no R API: values that would be converted with a warning fail the stream with the warning's message instead. A result is used by one thread at a time, under an atomic busy mark that records whether R's main thread or another thread holds it; while another thread reads, fetching from, binding or describing the result on R's main thread fails with a message that says so, while dbClearResult(), dbGetRowCount(), dbHasCompleted() and the next query on the connection keep working and the stream reads on. A result that a stream lets go of on another thread has its statement finalized at once if nothing else holds it, and is otherwise destroyed on R's main thread when its result object is cleared or at the next result operation there.
  • The tests with real column sizes (chunks of 1 GiB and 2 GiB blobs, a parameter of 2^31 bytes) peak at about 2.5 GB each and release their memory before the next test (the test process peaks at about 3.3 GB), and run only with RSQLITE_TEST_LARGE_ARROW=true, which the custom/after-install hook sets for the GitHub Actions checks; CRAN, the R-hub containers and users running the tests skip them.
  • On the default path, dbBind() of an unnamed list to a query without placeholders now says "Query does not require parameters." where main said "Named parameters not used in query: ".

DBItest: the whole suite passes. Twelve Arrow round trip specs are skipped and explained in tests/testthat/helper-DBItest.R (arrow_read_table_arrow, arrow_read_table_arrow_empty, and the roundtrip_integer, _logical, _character, _blob and _mixed variants of arrow_write_table_arrow and arrow_append_table_arrow), and only when RSQLite with its own dbFetchArrow() method is installed, so the copies of the helper in DBItest and DBI skip nothing. SQLite integers are 64-bit, so an R integer column comes back as int64, which nanoarrow converts to double by default, and the specs compare against R integer columns with expect_identical(). This is a property of SQLite rather than of the implementation (DuckDB and ADBC map SQLite integers to 64 bits too); the alternative, reading declared INTEGER columns as int32, would fail on values above 2^31 that turn up after the first chunk. A DBItest tweak that relaxes the comparison for 64-bit backends would let the specs run. #831, on top of the stack, declares the DBItest version in the helper.

Review

Three clean-context reviews: the first (2026-09-27) found one High, four Medium and two Low issues; the second confirmed those fixes and found one Medium (the per-row size check slowed text columns by about 30 %, now about 6 %) and six Low ones; the third confirmed those and found one Medium (a heap use after free from a warning handler that re-enters its own result, found with AddressSanitizer) and three Low ones. Reviews of the pull requests above and the integration review found more issues located here (out-of-range times and timestamps, times outside a day, text that is not valid UTF-8, arrow missing from Suggests, unchecked dictionary indices and 32-bit sizes of parameters, the 32-bit row counter, UTF-16 bytes for text in a binary column), and the busy mark could stay set after an R error that bypassed cpp11. All High and Medium findings are fixed, AddressSanitizer is clean on the reviewers' reproducers and on test-arrow.R, and CI is green on c7ab2b6. The review of the fixes up to c7ab2b6 found that Arrow's Acero engine and write_dataset() read the stream on a worker thread, where its callbacks called R; that is fixed in 033dded. The second integration review of the stack found the date and time parsers still calling R's ISNAN() there, arrow's read-ahead running into the busy mark, and a stream released on a worker thread keeping its statement open; all three are fixed up to 68a0575, where an interposer counts no R call off R's main thread. That was the last review round for the stack. What remains is listed under Accepted limitations. #830, from main, fixes the restart of a result after an SQLite error and the state after a failed bind, and merges in here. The three failures of test-httpvfs.R that CI logs show are pre-existing on main and hidden from testthat's summary there; they are discussed in #829.

Part of a series: the stacked follow-up #796 adds dbConnect(arrow = TRUE), which routes dbFetch() and dbAppendTable() through this Arrow path with one unified conversion to data frames.

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

Query results are written from the SQLite statement straight into nanoarrow arrays,
and Arrow arrays are bound straight to statement parameters, without passing through R vectors.
`dbSendQueryArrow()` returns the new `SQLiteResultArrow` class,
`dbFetchArrow()` returns a lazy stream that fetches one chunk of at most `chunk_size` rows per `get_next()`,
`dbFetchArrowChunk()` returns one such array per call,
and `dbBindArrow()`, `dbAppendTableArrow()`, `dbWriteTableArrow()` and `dbCreateTableArrow()` consume Arrow streams.
Result columns keep the SQLite values intact:
integers are `int64`, reals `double`, text `utf8`, blobs `binary`,
and the extended date and time types become `date32`, `time64[us]` and `timestamp[us, UTC]`.
The nanoarrow C library 0.9.0 is vendored in `src/vendor/nanoarrow`,
and the result external pointer now owns a shared pointer so that a stream can outlive `dbClearResult()`.
SQLite errors raised while fetching are C++ exceptions, so that they can cross the stream callbacks.
Twelve DBItest Arrow round trip specs are skipped with a comment:
SQLite integers are 64-bit, and the specs expect R integer columns back.

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 0979775, by a Claude Code reviewer with clean context that read the diff against main, ran targeted R snippets against builds of this branch and of the whole stack, and posted nothing itself. Line numbers refer to that commit. "Confirmed" means reproduced by running code.

High

1. A chunk can overflow the int32 offsets of a text or blob column. src/SqliteResultImpl.cpp:429-442 checks variable_bytes() against the 1 GiB cut only every 1024 rows, while utf8 and binary columns use 32-bit offsets. Confirmed: SELECT zeroblob(1100000000) FROM cnt with two rows fails with array_stream->get_next(): [5] Can't append to Arrow array on dbGetQueryArrow() (nanoarrow returns EOVERFLOW from ArrowArrayAppendBytes()), and through #796 also dbGetQuery() with arrow = TRUE; the default path returns both blobs. Any table whose rows average more than about 1 MiB is affected. Suggested fix: check variable_bytes() after every row (one buffer-size read), cut the chunk before appending a value that would cross INT32_MAX, or promote the column to large_utf8/large_binary; and give the error a message that names the column and the limit. The docs in R/arrow.R:71 ("cut once a string or binary column holds one gigabyte") promise more than the code keeps.

Medium

2. chunk_size = Inf passes validation and produces an endless stream of empty arrays. check_chunk_size() in R/arrow.R:77-83 accepts Inf; static_cast<int64_t>(Inf) in result_fetch_arrow() is undefined and in practice negative, so fetch_arrow_rows() appends nothing and get_next() returns length-0 arrays forever. Confirmed: as.data.frame(dbFetchArrow(rs, chunk_size = Inf)) never terminates. Suggested fix: require is.finite(chunk_size) and cap it, e.g. at 2^53.

3. dbBind() while a lazy stream is alive leaves the stream with a stale schema. StreamState::schema is cached once (src/DbArrowStream.cpp:10,21-29), and after_set_params() (src/SqliteResultImpl.cpp:293-303) clears arrow_columns_, so the next chunk is retyped from the new values. Confirmed: SELECT ? AS a bound to 1L gives a stream with an int64 schema; rebinding to 2.5 makes get_next() return 4.6e18 silently, rebinding to "text" gives nanoarrow's Expected array with 2 buffer(s) but found 3. Same-width mismatches are silent wrong data. Suggested fix: an execution counter on the result that the stream records with its schema, so get_next_impl() errors once it changed, or invalidation of outstanding streams in after_set_params(). The schema argument of #801 pins the types and narrows this without closing it.

4. The documented stream invalidation does not exist. DbConnection::is_current_result() always returns true (src/DbConnection.cpp:48-54), so the check in DbResult::fetch_arrow() (src/DbResult.cpp:85-93, "Result set was closed before the Arrow stream was consumed") can never fire, and R/arrow.R:68 ("invalidated when another query is sent on the same connection") is not true. Confirmed: after dbSendQuery() on the same connection (with the "Closing open result set" warning) the old stream still returns all rows, and after dbClearResult() plus dbDisconnect() it still reads, because the SQLite handle lives on until the stream is collected; dbDisconnect() then warns "There are N result in use" where N counts live streams, which reads confusingly after every result was cleared. Suggested fix: either implement the invalidation (clearing or replacing the result closes the shared object and fetch_arrow() checks a closed flag) or correct the docs and the warning wording, and say in either case that an unconsumed stream keeps the statement, its read transaction and the file handle open until garbage collection.

Low

5. The pending chunk ignores a later chunk_size. SqliteResultImpl::fetch_arrow() (src/SqliteResultImpl.cpp:243-247) returns pending_chunk_ whatever n_max is. Confirmed: dbFetchArrowChunk(rs, chunk_size = 5) after get_schema() on a chunk_size = 50 stream returns 50 rows. Document it or slice the chunk.

6. R_ContinueUnwind() from inside RSQLite's own C++ consumers. When an RSQLite lazy stream is bound as parameters, e.g. dbAppendTableArrow(con2, "t", dbGetQueryArrow(con1, sql)), SqliteArrowParamSource::next_batch() (src/SqliteParamSource.cpp:185-218) calls the stream's get_next, whose R_ContinueUnwind() on an interrupt (the check_user_interrupt() every 1024 rows) or a warning turned error longjmps over the frames of result_bind_arrow(): the std::vector<int> leaks, no crash, SQLite is left mid-bind and the R-level savepoint rolls back. By reading only. Suggested fix: rethrow instead of continuing the unwind when the callback runs inside an RSQLite entry point (a flag set by the entry points), or consume RSQLite streams through a C++ interface.

7. Nit. ARROW_MAX_VAR_BYTES is defined a second time, unused, in src/SqliteArrowColumn.cpp:9.

8. Pre-existing on both paths, inherited by the stream. After an SQLite error in the middle of a result (json_extract on a malformed row), the next fetch yields a NULL row and the statement restarts from row 1, since sqlite3_step() resets after an error, and dbHasCompleted() stays FALSE. Confirmed identical on the default path. Worth marking the result complete or invalid after a step error, but not introduced here.

Checked and found sound

  • The stream callbacks: C++ exceptions become EIO with last_error, and a cpp11::unwind_exception is continued with R_ContinueUnwind() after the try block with no C++ objects alive. Verified by running an exiting tryCatch(warning = ) and options(warn = 2) through as.data.frame(dbGetQueryArrow()) on this build; the session stays healthy afterwards.
  • Ownership: the DbResultPtr is shared by the external pointer and StreamState, stream_release in the finalizer drops the share, the destructors make no R API calls, the connection is kept alive through pConn_, and a fully consumed stream releases the result at end of stream.
  • The order of sqlite3_column_* calls: the storage class is read once per row before any conversion, and column_text/column_blob precede column_bytes.
  • Packaging: Collate complete, no :::, NAMESPACE exports the new classes and methods, the vendored nanoarrow 0.9.0 with NANOARROW_NAMESPACE documented in its README, cleanup scripts and .Rbuildignore updated. The nanoarrow (>= 0.6.0) requirement holds: the 0.5.0 and 0.6.0 tags both ship the nanoarrow_output_*_from_xptr() helpers in r.h.
  • test-arrow.R passes on this build; duplicate and empty column names, dbFetch(NA), empty results and zero-column statements behave the same on both paths.

Test coverage worth adding: chunks crossing 1 GiB and 2 GiB, dbBind() under a live stream, an exiting handler or options(warn = 2) through the lazy stream (today only expect_warning() on dbFetchArrowChunk(), an entry point, is tested), and chunk_size = Inf.


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, the checks that came out sound, and the test coverage worth adding. Line positions refer to the current head, with main merged in.


Generated by Claude Code

Comment thread src/SqliteResultImpl.cpp Resolved
Comment thread R/arrow.R Resolved
Comment thread src/DbArrowStream.cpp Resolved
Comment thread src/DbResult.cpp Resolved
Comment thread R/arrow.R Resolved
Comment thread src/SqliteResultImpl.cpp Resolved
Comment thread src/SqliteParamSource.cpp Resolved
Comment thread src/SqliteArrowColumn.cpp Resolved
Comment thread tests/testthat/helper-DBItest.R Resolved
claude and others added 10 commits November 10, 2026 09:44
The byte limit of a chunk was checked only every 1024 rows,
so rows of large text or blob values could take a `utf8` or `binary` column past the 32-bit offsets within one window,
and the fetch failed with "Can't append to Arrow array".
Now a chunk ends after the row at which such a column reaches 1 GiB, checked after every row,
and before a row whose values would take a column past `INT32_MAX` bytes.
An empty chunk takes any row, as a single value never exceeds `INT32_MAX` bytes.

The storage class of each value is read once per row, before the size check converts any value.
The documentation of the cut is corrected, and the unused second definition of the limit is gone.
The tests lower both limits through an internal entry point;
a test with the real limits needs about 3 GB of memory and runs only with `RSQLITE_TEST_LARGE_ARROW=true`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`chunk_size = Inf` passed the validation,
and its conversion to a 64-bit integer was undefined,
in practice negative, so the stream returned empty arrays forever.
`Inf` and `NaN` are now rejected like the other invalid sizes,
and sizes beyond 2^53, which doubles no longer hold as whole numbers, are capped there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
A lazy stream caches its schema,
while `dbBind()` and `dbBindArrow()` execute the statement again and decide the column types anew.
A stream fetched before the new parameters went on reading the new rows with the old schema,
which gave wrong values silently when the widths matched and an invalid array otherwise.

The result now counts its executions,
and a stream records the count when it is created and fails once it has changed.
A new `dbFetchArrow()` reads the new rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The Arrow fetch checked `is_active()` to fail a stream whose result had been replaced,
but `DbConnection::is_current_result()` always returns `true`, so the check could never fire,
and the documentation promised an invalidation that did not happen.
Making it real would break reading a lazy stream while other statements run on the connection,
as in `dbWriteTableArrow(con, "copy", dbGetQueryArrow(con, sql))`,
since `dbGetQueryArrow()` clears its result before the stream is read.
SQLite supports several statements on one connection, so the stream now keeps reading by design.

The dead checks are gone.
The documentation says that a stream stays readable after `dbClearResult()`,
while other queries run, and after `dbDisconnect()`,
and that until it has been read to the end or released it keeps the statement, a read transaction and the database file open.
The warning of `dbDisconnect()` now says that the results in use include those held by Arrow streams.

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

DBItest and DBI copy `helper-DBItest.R` into their own tests,
where an RSQLite with DBI's default Arrow methods passes the integer round-trip specs.
The list of specs to skip is now empty unless RSQLite defines its own `dbFetchArrow()` method,
and unless RSQLite is installed at all.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
When a stream's schema is requested before its first array,
the first chunk is fetched to decide the column types and kept for the next fetch.
That fetch returned the whole chunk whatever its own `chunk_size`,
so `dbFetchArrowChunk(rs, chunk_size = 5)` could return 50 rows.
A fetch with a smaller chunk size now gets a copy of the next rows of the kept chunk,
and the rest stays for the fetches after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
A lazy stream continues an R error or interrupt raised in its callbacks with `R_ContinueUnwind()`,
which is right for a consumer written in C.
When RSQLite binds one of its own lazy streams as parameters,
as in `dbAppendTableArrow(con2, "t", dbGetQueryArrow(con1, sql))`,
the consumer is RSQLite's C++ code, and that longjmp skipped its destructors.
The parameter source now marks such a stream when it takes it over,
and the callbacks rethrow the `cpp11::unwind_exception`,
so that the unwind continues at the entry point after the C++ frames have been left.

The new test turns the warning about a mixed type into an error with `options(warn = 2)`,
and with an exiting handler, in a stream read by nanoarrow and in a stream bound by RSQLite.
It checks that the error surfaces and the append is rolled back;
the skipped destructors themselves are not observable from R.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
An R condition raised inside a stream callback is continued with `R_ContinueUnwind()`
unless RSQLite's own C++ code reads the stream.
A C++ consumer of another package, such as arrow, has its frames skipped by that jump,
which the C stream interface leaves no way around.
The comment on the callbacks now says so, and which conditions can arise.

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 2e3d3b8 (the eight commits after the merge of main in 36b28c4), by a Claude Code reviewer with clean context that read the first review and the diff 36b28c46..2e3d3b81, ran test-arrow.R and test-DBItest.R on a build of that commit, ran targeted R snippets against it, reverted the fixes to see which tests fail, and compared timings with a build of 36b28c4, and posted nothing itself. Line numbers refer to that commit. "Confirmed" means reproduced by running code.

The first review's findings

  • 1, int32 offset overflow of a text or blob chunk (High): fixed. The cut is checked after every row and a row that would pass 2^31 - 1 starts the next chunk (src/SqliteResultImpl.cpp:445-467, :594-612); nanoarrow rejects only offset + size > INT32_MAX, so the limit is exact. Confirmed with the limits lowered to 100/150 through arrow_set_bytes_limits(): 26 size patterns at and around both limits (99+1, 100, 99+51, 99+52, 150, 151, 75+75, 75+76, empty strings, NULLs, mixed storage classes, two variable-width columns) cut where expected and lose or repeat no row. The real 2 GiB case is covered only by the opt-in test, which I did not run. The request for an error message naming the column is moot, because a single value cannot exceed the limit. The documentation sentence is corrected (R/arrow.R:77-79).
  • 2, chunk_size = Inf (Medium): fixed. Confirmed: Inf, -Inf, NaN, NA error, 2^60 and 1e300 are capped at 2^53 (R/arrow.R:85-92).
  • 3, stale schema after dbBind() (Medium): fixed. Confirmed: a half-read stream fails with "The result was bound to new parameters ..." on every later get_next(), also after dbBindArrow() and when the schema was never requested; a failed bind (wrong parameter count) leaves the counter alone; a multi-row dbBind() does not invalidate the stream between parameter rows; a new dbFetchArrow() reads the new rows.
  • 4, documented invalidation that does not exist (Medium): fixed by documenting the real behaviour and removing the dead check. Confirmed on a file database: the stream reads on after dbClearResult(), another query and dbDisconnect(); the file descriptors stay open until the stream is read to the end, released or collected, and are closed afterwards; while it is half read, DROP TABLE fails with "database table is locked" and a writer on a second connection with "database is locked", as the new text says. The warning wording is clearer.
  • 5, pending chunk ignores a later chunk_size (Low): fixed. Confirmed with nine combinations of the two chunk sizes over int, real, text, blob, date, time, timestamp, all-NULL and int-promoted-to-double columns with NULLs: all slices pass arrow's ValidateFull() and concatenate to the whole result.
  • 6, R_ContinueUnwind() through RSQLite's own consumer (Low): fixed by reading; no test can show it (new finding 4). Confirmed that options(warn = 2) and an exiting tryCatch(warning = ) unwind cleanly with the bound stream read from dbAppendTableArrow(), dbBindArrow(), dbFetch(), an outer lazy stream read by nanoarrow and one read by arrow; 200 repetitions with gc() leave the session healthy, the savepoint rolls back and no transaction stays open.
  • 7, duplicate ARROW_MAX_VAR_BYTES (nit): fixed.
  • 8, restart after an SQLite error in the middle of a result (pre-existing): not addressed, as expected; new finding 5 is the same defect reached through a bound stream.
  • Inline thread on tests/testthat/helper-DBItest.R: the guard is fixed. Confirmed: with CRAN RSQLite 3.53.3 installed the helper yields NULL without error or skip, without RSQLite installed also NULL, and on this branch the twelve specs are skipped; test-DBItest.R passes (0 failures, 8328 expectations). The second half of that thread is not taken up: dbitest_version is still "1.8.1" (tests/testthat/helper-DBItest.R:10).
  • Test coverage asked for: added for the byte limits, dbBind() under a live stream, warn = 2 and an exiting handler through the lazy stream, and chunk_size = Inf. With the fixes reverted, the tests for findings 1, 2, 3 and 5 fail; the one for finding 6 does not.

New findings

Medium

1. The per-row fit check makes text columns about 40 % slower to fetch. Confirmed with optimized builds (-O2, best of 11): reading 2 million rows of SELECT i, s, r, s2 (two text columns) through the stream takes 0.47 to 0.52 s at 36b28c4 and 0.65 to 0.68 s at 2e3d3b8; with only the call to arrow_row_fits() at src/SqliteResultImpl.cpp:451 disabled it is 0.45 s again, while checking arrow_chunk_full() on every row costs nothing measurable. Forty integer columns are within noise. SqliteArrowColumn::value_bytes() (src/SqliteArrowColumn.cpp:137-154) calls sqlite3_column_text() or sqlite3_column_blob() and sqlite3_column_bytes() for every value, and append_value() calls them again (:312-314, :327-328). Suggested fix: read pointer and length once per value, keep them in the column object, and let both the fit check and the append use them; or run the check only for columns of kind utf8 or binary through a precomputed index list and compare against a running byte count.

Low

2. A cut before a blob in a utf8 column drops the mixed-type warning. Confirmed with limits 100/150 and a 90-byte string followed by a 120-byte blob: with the cut between the rows no warning is raised, without it "Column x: mixed type ... coercing values of type blob" is. arrow_row_fits() converts the value with sqlite3_column_text() before the loop breaks, and the next chunk reads the storage class of the same row again (src/SqliteResultImpl.cpp:445-453), which SQLite documents as undefined after a conversion and which now reports text. The data is the same. Suggested fix: keep the storage classes of a row that was held back and reuse them for the first row of the next chunk.

3. After dbDisconnect(), an SQLite error raised through the stream loses its message. Confirmed: SELECT json_extract(x, '$.a') over a malformed row gives "malformed JSON" through a stream of an open connection and "bad parameter or other API misuse" once the connection was disconnected, because sqlite3_errmsg() is called on the handle that sqlite3_close_v2() left as a zombie (src/SqliteResultImpl.cpp:631-632). The documentation now promises reading "even after dbDisconnect()" (R/arrow.R:67-69). Suggested fix: fall back to sqlite3_errstr() of the code returned by sqlite3_step() when the connection is no longer valid, or say in the documentation that error messages are lost.

4. The regression test for the rethrow cannot fail. Confirmed: with the call to db_arrow_stream_read_from_cpp() removed (src/SqliteParamSource.cpp:109), "an R error while the stream is read unwinds cleanly" (tests/testthat/test-arrow.R:348) still passes, since the longjmp only leaked the std::vector<int> of result_bind_arrow(). The R-level infer_nanoarrow_schema() in db_bind_arrow() fetches the first chunk before any C++ consumer runs, so the constructor of SqliteArrowParamSource is not reachable with a pending condition either. Suggested fix: say so in the test comment, or expose a test-only counter of live SqliteArrowParamSource objects or of rethrown unwinds.

5. After an R error from a bound stream in the middle of a fetch, the outer result stays usable and returns wrong rows. Confirmed: with SELECT $x AS x bound to a lazy stream over the values 1, 2, 'three', 4 (chunk size 2) and options(warn = 2), the first dbFetch() fails with the converted warning, and a second dbFetch() returns NA, 2, 0, 4: a NULL row from the finished statement, the last parameter row executed again, and 'three' coerced without a warning, because warned is set before the warning is raised (src/SqliteArrowColumn.cpp:418). The same happens with an exiting tryCatch(warning = ). This is finding 8 of the first review reached through step_done() (src/SqliteResultImpl.cpp:384-392), not introduced by these commits, and dbAppendTableArrow() is safe because it clears the result and rolls back. Suggested fix: mark the result complete or invalid when step() or bind_row() throws.

6. dbHasCompleted() is TRUE while rows wait in the kept chunk. Confirmed: after get_schema() on a stream with chunk_size = 100 over 20 rows, dbHasCompleted(rs) is TRUE and dbGetRowCount(rs) is 20, before and after dbFetchArrowChunk(rs, chunk_size = 5) returned the first five. The kept chunk predates these commits (src/SqliteResultImpl.cpp:224-228); the slicing spreads it over more calls, so a while (!dbHasCompleted(rs)) loop around dbFetchArrowChunk() now stops with rows unread instead of returning them in one oversized chunk. Suggested fix: have complete() also require an empty kept chunk, or document it.

7. Binding a result to its own stream leaks the statement. Confirmed: dbBindArrow(rs, dbFetchArrow(rs)) fails as it should ("Can't read the parameters: The result was bound to new parameters ..."), but the parameter source kept by the result (src/SqliteResultImpl.cpp:285) owns the stream, which owns a share of the result, so after dbClearResult() and gc() the connection still reports "1 results in use" on dbDisconnect(). A corner case; rejecting a stream whose result is the one being bound, or dropping params_ when the first row fails to bind, would close it.

Checked and found sound

  • The storage classes of a row are read for all columns before any conversion (src/SqliteResultImpl.cpp:445-447), and value_bytes() calls sqlite3_column_text() or sqlite3_column_blob() before sqlite3_column_bytes(); undecided and fixed-width columns return 0 without touching the value.
  • The byte arithmetic is in int64_t, an empty chunk takes any single value, and a chunk of zero rows cannot be produced by a cut, so the stream cannot end early or loop.
  • copy_pending_rows() leaves the kept chunk and its offset untouched when it throws, releases the chunk with its last slice, and handles the null, date32, time64 and timestamp storage types; after_set_params() resets the offset.
  • The execution counter is read only while the stream holds its share of the result, impl cannot be null there, and a stream read to the end stays at its end after a rebind.
  • The rethrown cpp11::unwind_exception only crosses C++ frames (ArrowArrayStreamGetNext() is static inline in the header, so it is compiled as C++), reaches a cpp11 entry point or the outer stream callback that continues the unwind, and no catch (...) on the way swallows it; the flag is set only on a stream whose release is RSQLite's own, after it was moved out of the R object.
  • test-arrow.R passes (one skip, the opt-in large test), man/sqlite-arrow.Rd matches the roxygen comments, and the helper guard needs only methods and short-circuits when RSQLite is absent.

Coordinator's note: separately from this review, the CI auto-update commit d71a1e7 wrote absolute runner paths into src/cpp11.dd and src/result.dd, because the filter in src/Makevars.deps misses gcc's one-space continuation lines; a fix for the filter and the two files is being prepared on this branch.


Generated by Claude Code

…files

gcc wraps long dependency lists with a single leading space on continuation lines.
The filter only dropped lines starting with exactly two spaces, so absolute paths survived.
The CI auto-update committed about 740 lines of runner paths into `cpp11.dd` and `result.dd`.
Those files are included by make, so a source install elsewhere failed with "No rule to make target".

Join continuation lines of any indentation before splitting, so that every entry is normalised to the two-space form.
The absolute, Windows drive, `vendor` and `..` filters then apply on every line.
Regenerate `cpp11.dd` and `result.dd` with the fixed rule.

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

The check that a row fits the 32-bit offsets read every text and blob value with `sqlite3_column_text()` or `sqlite3_column_blob()` and `sqlite3_column_bytes()`,
and the append read it again.
Each column now keeps the storage class, pointer and size of the value of the current row,
so that the check and the append share one read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
When a row would take a text or blob column past the 32-bit offsets,
the size check has already converted some of its values,
and the next chunk read the storage classes of that row again,
which SQLite leaves undefined after a conversion.
A blob in a `utf8` column then read as text, and its mixed-type warning was lost.
The columns now keep the storage classes of such a row for the next chunk,
and only a step to the next row reads them anew.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
An Arrow stream reads on after `dbDisconnect()`,
but `sqlite3_close_v2()` leaves a handle whose `sqlite3_errmsg()` only reports API misuse,
so an error of the statement read "bad parameter or other API misuse".
Once the connection is closed, the error now carries `sqlite3_errstr()` of the code that `sqlite3_step()` returned,
and says that no details are available.
The documentation of the stream's lifetime says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`dbGetRowCount()` and `dbHasCompleted()` take no busy mark,
so they keep working while arrow's scanner or Acero reads a stream of the result ahead on another thread.
They read the row count, the completion and the kept chunk of the result as plain fields,
which that thread was writing at the same time.

The row count, the completion and the number of kept rows not handed out yet
are now atomic values with acquire and release ordering,
written by one thread at a time under the busy mark,
so reading them is no data race, never fails,
and follows the rows read on the other thread.
`n_rows_fetched()` reads the kept rows before the row count, which counts them first,
so that the count stays between zero and the rows read and never goes down while a stream is read.
`complete()` checks the kept rows instead of the kept chunk.
The other values that the R side reads without the busy mark need no change:
`dbGetRowsAffected()` reads SQLite's change count and a start value that only binds on R's main thread set,
`dbGetStatement()` reads the R object, `dbIsValid()` reads no field of the result,
and the show method and `dbGetInfo()` call these.

The test of a result held by another thread now also calls these accessors in that state,
and a new test polls `dbGetRowCount()` and `dbHasCompleted()` while arrow's scanner reads 200,000 rows ahead:
the count never goes down and ends at all rows, and the completion turns true and stays.
`?"sqlite-arrow"` says that both follow the rows read on the other thread.

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

Superseded: Accepted limitations

Superseded by this comment.

Three clean reviews of this pull request, four findings that reviews of the layers above located here, the first integration review, the review of the fixes up to c7ab2b63 and the second integration review are addressed up to 68a0575, which closes the review rounds for this pull request. Every High and Medium finding is fixed: on a thread other than R's main thread RSQLite calls no R API (an interposer counts none), a result is used by one thread at a time under an atomic busy mark, and AddressSanitizer is clean on the tests and on a stress run against arrow's read-ahead. Whether R should wait for a stream read on another thread instead of failing is an open question on #829. The maintainer's other decisions are in: the busy mark is reset through R_ExecWithCleanup() also after a raw longjmp, the process-global test hooks are gone, the large Arrow tests run in GitHub Actions, the restart after an error and the failed bind are fixed from main in #830, mixing data-frame and Arrow fetches is r-dbi/DBI#773, and the DBItest declaration is #831. These remain:

  • R/arrow.R#L22: text and blobs in a utf8 column must be valid UTF-8 without NUL bytes, which SQLite does not enforce; other values become NULL with a warning, where the default data-frame path passes text through unchecked. The check costs about 5 % on text-heavy reads, with an ASCII fast path. Relevance: medium; confidence: high. (recorded)
  • R/arrow.R#L48: with extended_types = TRUE, a timestamp beyond the int64 microseconds and a time outside a day (L50) become NULL with a warning, so the arrays pass Arrow's full validation; the default path keeps such times as hms durations. Relevance: low; confidence: high. (recorded)
  • src/SqliteResultImpl.cpp#L417: after an SQLite error in the middle of a result, the next fetch restarts the statement and dbHasCompleted() stays FALSE, on both the Arrow and the data-frame path. Pre-existing on main, fixed there in fix: Never restart a statement after an error in dbFetch() or dbBind() #830, which merges into this branch; the variant through a bound Arrow stream is closed by 63d4817. Relevance: medium; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L165: a list dbBind() whose first row fails keeps its parameters, so the next dbFetch() raises the bind error once more and then completes; only the Arrow bind asks for a new bind. Pre-existing, fixed on main in fix: Never restart a statement after an error in dbFetch() or dbBind() #830, which merges into this branch. Relevance: low; confidence: high.
  • src/DbResult.cpp#L12: a raw longjmp out of a fetch, bind or clear (out of memory in a raw allocation of the data-frame path, an ALTREP vector, a foreign parameter stream that calls R) no longer leaves the result refusing further calls, since R_ExecWithCleanup() resets its busy mark; it still skips the C++ destructors of the frames it leaves, so their objects leak, including R vectors that cpp11 preserved for them, and the statement can be left mid-step. Relevance: low; confidence: high. (recorded)
  • src/DbArrowStream.cpp#L149: releasing a stream from a handler of its own get_next() would free its state under the callback; the Arrow C stream interface forbids it and the guard does not cover it. Relevance: low; confidence: high.
  • src/SqliteResultImpl.cpp#L195: dbFetch(n = 0) and dbColumnInfo() on a row held back by a byte cut type the zero-row data frame from sqlite3_column_type() after the byte check called sqlite3_column_bytes(), which SQLite documents as undefined after a conversion. With the bundled SQLite 3.54.1 the original type is kept (the conversion keeps the INTEGER or FLOAT flag next to the text flag), so no wrong type was observed; it is a reliance on undocumented behavior. The Arrow output is unaffected. Relevance: low; confidence: high.
  • R/arrow.R#L81: a data-frame dbFetch() fails while rows kept for the Arrow schema (L81) or a row held back by a byte cut (L85) wait, instead of returning them; before, it skipped them silently. Only hit when Arrow and data-frame fetches are mixed on one result, which the DBI specification does not cover: Mixing data-frame and Arrow fetches on one result set is not specified DBI#773. Relevance: low; confidence: high. (recorded)
  • R/arrow.R#L71: an unread stream keeps the statement, a read transaction and the database file open, even past dbDisconnect(), so it can block writers; after dbDisconnect(), statement errors carry only SQLite's generic message (L70). Relevance: medium; confidence: high. (recorded)
  • src/DbArrowStream.cpp#L93: a C++ consumer from another package, such as arrow, has its frames skipped by the longjmp when an interrupt or a warning turned error happens in a callback; arrow 26.0.1 survived both cases in testing. Relevance: low; confidence: medium. (recorded)
  • src/SqliteResultImpl.cpp#L271: a fetch can return fewer than chunk_size rows before the end, because of the byte cut or the rest of a kept chunk; callers that need exactly n rows must loop. The byte cut is documented, the kept remainder is not. Relevance: low; confidence: high.
  • src/SqliteResultImpl.cpp#L501: the per-row byte check costs about 6 % on text columns (down from about 30 %), close to the noise. Relevance: low; confidence: medium (noisy machine).
  • .github/workflows/custom/after-install/action.yml: the tests with real 1 GiB and 2 GiB sizes and with 2^31-byte parameters peak at about 2.6 GB, so they run only where RSQLITE_TEST_LARGE_ARROW=true: in this repository's GitHub Actions checks, which set it through this hook, but not on CRAN, in R-hub's sanitizer and valgrind containers, or on users' machines. Relevance: low; confidence: high. (recorded)
  • tests/testthat/helper-DBItest.R#L10: dbitest_version stays at 1.8.1, so the six schema specs from feat: Specify the schema of Arrow results DBItest#571 are not enabled in DBItest's copy in this layer; test: Declare DBItest 1.8.3.6 in the DBItest contexts #831 on top of the stack declares the version the six specs need. Relevance: low; confidence: high.
  • src/result.cpp#L59: rows are counted in 64 bits, and dbGetRowCount() returns an integer while the count fits and a double beyond INT_MAX, so its type changes for results of more than 2^31 - 1 rows. Relevance: low; confidence: high.
  • R/arrow.R#L27-L30: in a UTF-16 database, a blob in a text column reads "ab" through Arrow but "扡" through dbGetQuery() on this branch, because the data frame path transcodes it; fix: Validate blobs that are read into a text column #799 reads such blobs as bytes on the data frame path, so the two agree once both are merged. Relevance: low; reviewer's confidence: high.
  • R/arrow.R#L95: on a worker thread, such as arrow's scanner and Acero use, a value that would be converted with a warning fails the stream with that message instead, as the C stream interface has no channel for warnings. The read can't be interrupted from R there, a busy handler that is an R function is not called, so a locked database fails the statement, and the second row of parameters bound with dbBind() fails the stream; parameters bound with dbBindArrow() work. Relevance: medium; confidence: high. (recorded)
  • src/DbResult.cpp#L68: while arrow reads a stream ahead on another thread, dbFetch(), dbFetchArrowChunk(), dbBind(), dbBindArrow() and dbColumnInfo() on its result fail rather than wait, and such a call on R's main thread fails the read on the other thread in turn; dbGetRowCount(), dbHasCompleted(), dbGetRowsAffected() and dbClearResult() keep working and follow the rows read there. Whether to wait instead is the open question on chore: Coordinate the review of the open pull requests #829. Relevance: low; confidence: high. (recorded)
  • src/DbArrowStream.cpp#L54: a stream that arrow is still reading keeps its statement and read transaction open after dbClearResult() until arrow releases it, for Acero also after its reader has been dropped. Relevance: low; confidence: high. (recorded)
  • src/DbResult.cpp#L68: rows read by a fetch that fails by an R error or longjmp, such as an exhausted vector heap or an interrupt, are lost with that fetch but counted by dbGetRowCount(); the next fetch continues after them. This was already so for errors that cpp11 sees. Relevance: low; confidence: high.

Generated by Claude Code

The fixtures at the top of `test-arrow.R` move 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 those without one gain a comment saying what they are for.

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

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

CI note for the whole Arrow stack (#795, #796, #800, #801, #802, #807 and #831), after the push that moved the test fixtures into tests/testthat/helper-arrow.R: the smoke test failed before any R code ran, because the runners could not resolve the Ubuntu package mirrors while installing aspell (Temporary failure resolving 'security.ubuntu.com'), as on every pull request of this repository since about 14:00 UTC (see #832). That is the runners' network, not these changes, and there is no fix to port. The jobs will be re-run once the mirrors resolve again.


Generated by Claude Code

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Three clean reviews of this pull request, four findings that reviews of the layers above located here, the first integration review, the review of the fixes up to c7ab2b63 and the second integration review are addressed up to 68a0575, which closes the review rounds for this pull request. Every High and Medium finding is fixed: on a thread other than R's main thread RSQLite calls no R API (an interposer counts none), a result is used by one thread at a time under an atomic busy mark, and AddressSanitizer is clean on the tests and on a stress run against arrow's read-ahead. Whether R should wait for a stream read on another thread instead of failing is an open question on #829. The maintainer's other decisions are in: the busy mark is reset through R_ExecWithCleanup() also after a raw longjmp, the process-global test hooks are gone, the large Arrow tests run in GitHub Actions, the restart after an error and the failed bind are fixed from main in #830, mixing data-frame and Arrow fetches is r-dbi/DBI#773, and the DBItest declaration is #831. These remain:

  • R/arrow.R#L22: text and blobs in a utf8 column must be valid UTF-8 without NUL bytes, which SQLite does not enforce; other values become NULL with a warning, where the default data-frame path passes text through unchecked. The check costs about 5 % on text-heavy reads, with an ASCII fast path. Relevance: medium; confidence: high. (recorded)
  • R/arrow.R#L48: with extended_types = TRUE, a timestamp beyond the int64 microseconds and a time outside a day (L50) become NULL with a warning, so the arrays pass Arrow's full validation; the default path keeps such times as hms durations. Relevance: low; confidence: high. (recorded)
  • src/SqliteResultImpl.cpp#L417: after an SQLite error in the middle of a result, the next fetch restarts the statement and dbHasCompleted() stays FALSE, on both the Arrow and the data-frame path. Pre-existing on main, fixed there in fix: Never restart a statement after an error in dbFetch() or dbBind() #830, which merges into this branch; the variant through a bound Arrow stream is closed by 63d4817. Relevance: medium; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L165: a list dbBind() whose first row fails keeps its parameters, so the next dbFetch() raises the bind error once more and then completes; only the Arrow bind asks for a new bind. Pre-existing, fixed on main in fix: Never restart a statement after an error in dbFetch() or dbBind() #830, which merges into this branch. Relevance: low; confidence: high.
  • src/DbResult.cpp#L12: a raw longjmp out of a fetch, bind or clear (out of memory in a raw allocation of the data-frame path, an ALTREP vector, a foreign parameter stream that calls R) no longer leaves the result refusing further calls, since R_ExecWithCleanup() resets its busy mark; it still skips the C++ destructors of the frames it leaves, so their objects leak, including R vectors that cpp11 preserved for them, and the statement can be left mid-step. Relevance: low; confidence: high. (recorded)
  • src/DbArrowStream.cpp#L149: releasing a stream from a handler of its own get_next() would free its state under the callback; the Arrow C stream interface forbids it and the guard does not cover it. Relevance: low; confidence: high.
  • src/SqliteResultImpl.cpp#L195: dbFetch(n = 0) and dbColumnInfo() on a row held back by a byte cut type the zero-row data frame from sqlite3_column_type() after the byte check called sqlite3_column_bytes(), which SQLite documents as undefined after a conversion. With the bundled SQLite 3.54.1 the original type is kept (the conversion keeps the INTEGER or FLOAT flag next to the text flag), so no wrong type was observed; it is a reliance on undocumented behavior. The Arrow output is unaffected. Relevance: low; confidence: high.
  • R/arrow.R#L81: a data-frame dbFetch() fails while rows kept for the Arrow schema (L81) or a row held back by a byte cut (L85) wait, instead of returning them; before, it skipped them silently. Only hit when Arrow and data-frame fetches are mixed on one result, which the DBI specification does not cover: Mixing data-frame and Arrow fetches on one result set is not specified DBI#773. Relevance: low; confidence: high. (recorded)
  • R/arrow.R#L71: an unread stream keeps the statement, a read transaction and the database file open, even past dbDisconnect(), so it can block writers; after dbDisconnect(), statement errors carry only SQLite's generic message (L70). Relevance: medium; confidence: high. (recorded)
  • src/DbArrowStream.cpp#L93: a C++ consumer from another package, such as arrow, has its frames skipped by the longjmp when an interrupt or a warning turned error happens in a callback; arrow 26.0.1 survived both cases in testing. Relevance: low; confidence: medium. (recorded)
  • src/SqliteResultImpl.cpp#L271: a fetch can return fewer than chunk_size rows before the end, because of the byte cut or the rest of a kept chunk; callers that need exactly n rows must loop. The byte cut is documented, the kept remainder is not. Relevance: low; confidence: high.
  • src/SqliteResultImpl.cpp#L501: the per-row byte check costs about 6 % on text columns (down from about 30 %), close to the noise. Relevance: low; confidence: medium (noisy machine).
  • .github/workflows/custom/after-install/action.yml: the tests with real 1 GiB and 2 GiB sizes and with 2^31-byte parameters peak at about 2.6 GB, so they run only where RSQLITE_TEST_LARGE_ARROW=true: in this repository's GitHub Actions checks, which set it through this hook, but not on CRAN, in R-hub's sanitizer and valgrind containers, or on users' machines. Relevance: low; confidence: high. (recorded)
  • tests/testthat/helper-DBItest.R#L10: dbitest_version stays at 1.8.1, so the six schema specs from feat: Specify the schema of Arrow results DBItest#571 are not enabled in DBItest's copy in this layer; test: Declare DBItest 1.8.3.6 in the DBItest contexts #831 on top of the stack declares the version the six specs need. Relevance: low; confidence: high.
  • src/result.cpp#L59: rows are counted in 64 bits, and dbGetRowCount() returns an integer while the count fits and a double beyond INT_MAX, so its type changes for results of more than 2^31 - 1 rows. Relevance: low; confidence: high.
  • R/arrow.R#L27-L30: in a UTF-16 database, a blob in a text column reads "ab" through Arrow but "扡" through dbGetQuery() on this branch, because the data frame path transcodes it; fix: Validate blobs that are read into a text column #799 reads such blobs as bytes on the data frame path, so the two agree once both are merged. Relevance: low; reviewer's confidence: high.
  • R/arrow.R#L95: on a worker thread, such as arrow's scanner and Acero use, a value that would be converted with a warning fails the stream with that message instead, as the C stream interface has no channel for warnings. The read can't be interrupted from R there, a busy handler that is an R function is not called, so a locked database fails the statement, and the second row of parameters bound with dbBind() fails the stream; parameters bound with dbBindArrow() work. Relevance: medium; confidence: high. (recorded)
  • src/DbResult.cpp#L68: while arrow reads a stream ahead on another thread, dbFetch(), dbFetchArrowChunk(), dbBind(), dbBindArrow() and dbColumnInfo() on its result fail rather than wait, and such a call on R's main thread fails the read on the other thread in turn; dbGetRowCount(), dbHasCompleted(), dbGetRowsAffected() and dbClearResult() keep working and follow the rows read there. Whether to wait instead is the open question on chore: Coordinate the review of the open pull requests #829. Relevance: low; confidence: high. (recorded)
  • src/DbArrowStream.cpp#L54: a stream that arrow is still reading keeps its statement and read transaction open after dbClearResult() until arrow releases it, for Acero also after its reader has been dropped. Relevance: low; confidence: high. (recorded)
  • src/DbResult.cpp#L68: rows read by a fetch that fails by an R error or longjmp, such as an exhausted vector heap or an interrupt, are lost with that fetch but counted by dbGetRowCount(); the next fetch continues after them. This was already so for errors that cpp11 sees. Relevance: low; confidence: high.

Generated by Claude Code

krlmlr pushed a commit that referenced this pull request Nov 11, 2026
`step()` sets the result complete again before its error leaves it, as it did before the merge with `claude/fetch-row-ahead`, in addition to the catch in `fetch_rows()`.
On this branch, the other callers of `step()` are the first step of a result, which destroys it, and `dbBind()`, which leaves the result unbound, so no behavior changes here.
It matters for a caller without such a catch, such as the Arrow fetch of #795, which this keeps from stepping a failed statement again and restarting it.

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 11, 2026
A calling handler of a warning raised by `dbFetch()` or `dbColumnInfo()`, or a busy handler called while a fetch or `dbBind()` steps, runs R code while the C++ code of the result is on the stack.
When such a handler called `dbClearResult()` on that result, the result and its statement were freed under that code, and R crashed when the fetch went on or was left.
Since 1d0d70f, this also happened when the handler left the fetch with an error, because the catch of `fetch_rows()` resets the statement.
A result is now marked busy while one of its fetches or binds runs, or while `dbColumnInfo()` reads its first row.
`dbClearResult()` on a busy result fails with "Can't clear a result while one of its fetches or binds is running, as from a handler of a warning that it raised.", and leaves the result as it is.
A fetch, a bind or `dbColumnInfo()` of a busy result fails with "Can't use a result while one of its fetches or binds is running, as from a handler of a warning that it raised."
A new query on the same connection from such a handler therefore fails too, because it clears the open result first.
The mark is released on every exit path, also when an R error longjmps past the C++ frames, through `R_ExecWithCleanup()`.
Handlers of `base::tryCatch()`, `on.exit(dbClearResult(res))` and garbage collection of a result work as before.
The guard and its messages are those of #795, without its Arrow and thread parts, so that a merge can keep #795's version.

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