Skip to content

feat: Build Arrow arrays from text and blob columns - #860

Draft
krlmlr wants to merge 18 commits into
claude/arrow-numeric-columnsfrom
claude/arrow-text-columns
Draft

krlmlr wants to merge 18 commits into
claude/arrow-numeric-columnsfrom
claude/arrow-text-columns

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Fifth step of the Arrow rework (plan: #829 (comment)): the internal Arrow engine of #859 now builds arrays from text and blob columns. The entry point result_fetch_arrow_chunk() stays internal, so nothing changes for users.

This branch merges claude/utf8-infra (#845) with a merge commit, for its validator rsqlite_is_utf8_string(). Until #845 lands, its changes show in this diff: src/utf8.cpp, src/utf8.h, src/utf8.dd, the registration of utf8_valid(), tests/testthat/helper-utf8.R and tests/testthat/test-utf8.R. The change of this pull request is in the three commits that aren't merges: the feature, and the fixes of its two reviews. A second merge commit brings in the current head of #859.

What changes:

  • SqliteArrowColumn types a column whose first value that is not NULL is text as utf8, and one whose first such value is a blob as binary. A column whose values in the first chunk are all NULL takes the type of its declared affinity, now also utf8 for TEXT (TEXT, CHAR(n), CLOB, ...) and binary for BLOB, as the data-frame path maps them. This replaces the error "Arrow arrays of text and blobs are not supported yet." of feat: Build Arrow arrays from the integer, real and NULL columns of a result #859, and its test.
  • Values that don't fit the type of their column follow feat: Implement the DBI Arrow interface natively #795 at 43db19f with its refinements up to 3436358 (e273dfb, 2521ae0, b85c0e7, 22c4927):
    • Numbers in a utf8 or binary column are the text SQLite renders, as the data-frame path reads them.
    • Text in a binary column is its UTF-8 bytes, also in a UTF-16 database, as the data-frame path reads it.
    • A blob in a utf8 column keeps its bytes, which must be valid UTF-8. sqlite3_column_text() would take them for text in the encoding of the database and transcode them in a UTF-16 one.
    • Text and blobs in an int64 or double column are read as SQLite reads them: the leading integer, or the leading real. Where SQLite would saturate the leading integer of text or a blob, the value is NULL, as feat: Build Arrow arrays from the integer, real and NULL columns of a result #859 already does for a real beyond the range of int64 (22c4927). To tell a saturated integer from 2^63 - 1, the column reads the digits as SQLite does, as text in the encoding of the database: unlike feat: Implement the DBI Arrow interface natively #795, which read the raw bytes of a blob, this sees the digits of a blob in a UTF-16 database, where SQLite reads them as UTF-16.
    • In the chunk that decides the types, text and blobs that an int64 column has read as integers take the readings as reals they would have in a double column when a real widens the column later in that chunk, so 1, '2.5', 3.5 gives 1, 2.5, 3.5 in any order of the rows. feat: Implement the DBI Arrow interface natively #795 kept the integer reading (2), and NULL for a saturating integer, so the values depended on the order of the rows. Once the first chunk has fixed the type, text in an int64 column keeps its integer reading. While the type is open, the column keeps the reading as a real of each such value that differs from its integer reading, 16 bytes each, and releases them once the first chunk fixes the type. For one integer followed by 5 million text values in one chunk, words such as 'abc1' keep nothing (peak +40 MB, as without this rule) and values such as '1.5' keep 80 MB (peak +164 MB). Reading every such value as a real also takes time: for 2 million words, the chunk takes 0.21 s instead of 0.15 s.
    • Text and blobs in a utf8 column that are not valid UTF-8 are NULL: SQLite doesn't enforce UTF-8 for text, and a blob keeps any bytes. Arrow requires valid UTF-8 in utf8 arrays, and its full validation rejects a chunk that holds anything else.
    • Any value in a column of the null type stays NULL, as in feat: Build Arrow arrays from the integer, real and NULL columns of a result #859.
  • A value whose conversion runs out of memory fails the fetch at once, which completes the result like any other error. SQLite reports such a conversion as a NULL pointer from sqlite3_column_text() or sqlite3_column_blob() and fails only the next step, but after a full chunk that step only reads ahead, and keeps its error for the next fetch: the chunk would come back with an empty string, a NULL or a zero in place of the value. The size of a blob is read before sqlite3_column_blob(), which tells a zeroblob() that can't expand from a blob of no bytes, and text read into a double column is read as UTF-8 text first, so that sqlite3_column_double() has nothing left to allocate. A blob read into a double or open int64 column is read with sqlite3_column_double() alone, so that a zeroblob() isn't expanded just to read 0; SQLite reports running out of memory while copying a blob for that reading only through the error code of the connection, which is compared with its value before the call, as a code left from an earlier call can't be told apart (the next step then fails, as before).
  • Text is checked with feat: Add a UTF-8 validator for strings read from SQLite #845's rsqlite_is_utf8_string() itself. feat: Implement the DBI Arrow interface natively #795's is_utf8_text() wrapper is not carried over, since the validator has its own ASCII fast path.
  • Text with an embedded NUL byte is NULL in a utf8 column, and keeps all its bytes in a binary column. This is feat: Implement the DBI Arrow interface natively #795's rule, and it is what the validator implements, so the two don't conflict. Arrow itself allows NUL in utf8, but R strings can't hold it: nanoarrow fails when a converted string with a NUL is used, and arrow refuses to convert it unless arrow.skip_nul is set. Ending the text at the first NUL, as the data-frame path does, would change the value without a trace, while NULL treats a NUL like the other bytes that are not text.

None of these conversions is reported yet. The task left the choice between #795's simpler warning and saying what I chose: I kept them silent, as #859 keeps its own conversions (a real in a fixed int64 column, a value in a column of the null type) silent until pull request 7. One rule then holds for every conversion of a column, and pull request 7 adds the report for all of them at once instead of replacing a warning that only some of them raise. #795's warning is raised once per column from inside the fetch loop, where its handlers run while the busy guard holds the result; it is about 30 lines if reviewers prefer it in the meantime.

Where the values differ from dbFetch():

  • Text that is not valid UTF-8 is NULL, where dbFetch() passes it through; the tests pin both.
  • Text with a NUL byte is NULL, where dbFetch() ends it at the first NUL; the tests pin both.
  • In a UTF-16 database, a blob in a text column is its bytes, where dbFetch() transcodes them from UTF-16 on this base. The tests pin only the Arrow value, since fix: Validate blobs that are read into a text column #799 reads such blobs as bytes on the data-frame path too.
  • Later chunks keep the types of the first chunk, as in feat: Build Arrow arrays from the integer, real and NULL columns of a result #859, where dbFetch() types each fetch anew.
  • Text read into a column of integers: dbFetch() keeps the integer reading after a real widens the column ('2.5' gives 2), and gives -1 or 0 for a saturating integer in a 32-bit column.

Deliberately left out:

  • Reporting conversions once per chunk with their rows is pull request 7.
  • Byte limits for the 32-bit offsets of utf8 and binary arrays are pull request 8. Until then, a chunk whose values in one column exceed 2^31 - 1 bytes fails with "Can't append to Arrow array", which completes the result like any other error of a fetch.
  • Dates, times and timestamps are pull request 6, requested types such as large_utf8 are pull requests 13 and 14, and the DBI methods are pull request 16.
  • The data-frame path is unchanged.

Tested:

  • New tests/testthat/test-arrow-text.R: text and blob columns with empty strings, empty blobs and NULL among them; numbers and blobs in a utf8 column and text and numbers in a binary one; text and blobs in int64 and double columns, with the saturating cases; mixed types within the first chunk and converted in a later chunk, also into columns typed by TEXT and BLOB affinity and into the null type; text that is not valid UTF-8 (cast from blobs: a stray continuation byte, a truncated sequence, an overlong form, a surrogate, beyond U+10FFFF, an invalid byte between runs of 20 ASCII bytes, and a sequence truncated after them), in utf8 and in binary columns; embedded NUL bytes at the start, middle and end; values up to 2 MB; chunks of 1, 2, 3 + 4 and all rows up to one past the end, with the read-ahead row starting the next chunk; a UTF-16 database with non-ASCII text, a blob in a text column, a lone surrogate at the end of the text, which makes it NULL, and one before another character, which SQLite merges into one code point (x'780000d86100' becomes "x\U00010061", the same in dbFetch()), and a NUL character; the digits of blobs in a UTF-16 database read into an int64 column, in the chunk that decides the type and in a later one; whitespace and a sign before saturating integers; text in an int64 column that a real widens, in three orders of the rows; and values that run out of memory as the last row of a full chunk, in utf8, int64, double and binary columns and as a blob in a double column, and a zeroblob() in a double column that reads as 0 under a heap limit below its size. Where the rules agree, each chunk is compared with dbFetch() in the same chunk sizes, with dbHasCompleted() and dbGetRowCount() after each chunk.
  • tests/testthat/test-arrow-columns.R: the test of all-NULL columns covers each affinity, with TEXT, CHAR(1) and BLOB added.
  • tests/testthat/helper-arrow.R: arrow_values() converts utf8 to character and binary to blob, as dbFetch() returns them, and the new expect_valid_chunk() checks every chunk that the tests build: nanoarrow's full validation, which reading the chunk back from the Arrow IPC format runs, and valid UTF-8 in its utf8 columns, which nanoarrow doesn't check. expect_same_chunks() calls it for every chunk, and takes mixed = TRUE where dbFetch() warns of mixed types.
  • The out-of-memory test sets SQLite's hard heap limit, which can't be lifted again, so it runs in an R session of its own through callr, and skips unless that session loads the RSQLite under test: after pkgload::load_all() it skips, and it runs in R CMD check and against an installed copy. It also skips on CRAN, as it takes about 100 MB. Against an installed copy of this branch it passes; against 689a5c5 each chunk comes back without an error, and against 3ac16c6 the zeroblob() fails with "out of memory". It is also the test of an error while a chunk is built, which feat: Build Arrow arrays from the integer, real and NULL columns of a result #859's removed "not supported yet" test was; the overflow beyond 2^31 - 1 bytes is left for the small limits of pull request 8.
  • Each test_that() block of the two Arrow test files passes on its own after pkgload::load_all() at the head, where the out-of-memory test skips; both files pass in full against an installed copy, with that test.
  • By hand, arrow 26.0.1's ValidateFull() accepts all 71 chunks that the two test files build (arrow is not a test dependency here).
  • Mutations: without the UTF-8 check, four blocks fail; reading blobs with sqlite3_column_text() fails the UTF-16 block; without the saturation check, the int64 block fails; reading the raw bytes of a blob for the saturation check, as feat: Implement the DBI Arrow interface natively #795 did, fails the int64 block; the previous head fails the widening and the out-of-memory blocks.
  • Each test_that() block passes on its own in a fresh session right after pkgload::load_all().
  • devtools::test() with NOT_CRAN=true: no failures beyond the three errors in test-httpvfs.R that also happen on main (test: Run the HTTP VFS tests for real, and make their errors fail the check #832, testthat hides a test's error when the test records another result after it #837).
  • Under AddressSanitizer (gcc, -O1), on an installed copy of 3ac16c6, before the second review's fixes, test-arrow-text.R with the out-of-memory test, test-arrow-columns.R, test-utf8.R, test-read-ahead.R and test-encoding.R pass without a report; before the review fixes, so did test-dbSendQuery.R, test-dbClearResult.R, test-error.R, test-dbBind.R and test-blob.R. So does a script with chunks of several sizes over text, blobs, invalid UTF-8, NUL bytes and a zeroblob(), rebinding between text, integers and blobs, and arrays converted after their result was cleared and the connection closed, also under gctorture(TRUE).
  • No R CMD check: nothing in the build, DESCRIPTION, NAMESPACE or the documentation changes, beyond the files of feat: Add a UTF-8 validator for strings read from SQLite #845.

Cost of the UTF-8 check, measured on one million 50-byte values in one column, fetched in one chunk, median of nine runs in each of three rounds, against a build that skips the check: ASCII text takes 0.159 s instead of 0.148 s (about +7 %), text with 40 bytes of é 0.187 s instead of 0.149 s (about +26 %), and text with 39 bytes of 日 0.189 s instead of 0.153 s (about +24 %). dbFetch() takes 0.55 s to 0.60 s for the same columns. The ASCII figure is close to the 5 % that #795 measured; the cost for non-ASCII text lies in #845's validator, which checks such text sequence by sequence.

The UTF-8 check is unchanged by the review fixes, which add only a test for a NULL pointer to reading text.

Sits on #859, which is on #857, #856, #855, #830 and #850, and merges #845.

Size

About 295 hand-written lines of C++ (SqliteArrowColumn.cpp and .h, about 45 of them replacing #859's lines, and 120 from the review fixes) and 510 lines of tests, not counting #845's files.

Review

Two review rounds (first, second) led to 3ac16c6 and 32dea06; see the accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

claude and others added 8 commits November 11, 2026 13:51
`rsqlite_is_utf8_string()`, declared in `src/utf8.h` and defined in `src/utf8.cpp`, tells whether a byte range is well-formed UTF-8 without a NUL byte, which is what an R string can hold.
It follows RFC 3629, so it rejects overlong forms, surrogates, and code points beyond U+10FFFF.
ASCII text is checked eight bytes at a time.

Nothing calls the validator yet, so there is no user-visible change.
It is the shared infrastructure for checking text that is read from SQLite, in the data frame path and in the Arrow path.
The unexported `utf8_valid()` exposes it for the tests, which compare it with `validUTF8()` from base R.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The test hook utf8_valid() now copies each input into a buffer with three continuation bytes behind it.
A validator that reads past the end then sees a truncated sequence as valid, and the truncation tests fail.
Empty input is passed to the validator as NULL, which the header allows, so the empty-input test covers it.
The non-raw input test now checks for cpp11's "expected 'raw'" message instead of accepting any error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The build regenerated it with system headers, and the previous commit picked that up by mistake.
The includes did not change, so the committed file stands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`load_all()` sources `tests/testthat/helper*.R` but not the top level of a test file.
`utf8_reference()`, `hex()`, `ascii()`, `pad()` and `expect_utf8()` move to `helper-utf8.R`.
Helper files are shared by every test file, so the generic `hex()`, `ascii()` and `pad()` become `raw_hex()`, `raw_ascii()` and `raw_pad()`.
Every `test_that()` block of `test-utf8.R` now runs on its own after `load_all()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The CI's auto-update regenerated `src/cpp11.dd` and `src/utf8.dd` with GCC,
whose dependency output indents continuation lines by one space,
which the filter in `src/Makevars.deps` does not drop,
so the files gained hundreds of absolute and vendored paths (#836).
This restores them as they were and keeps the auto-update's formatting of `src/utf8.cpp`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
`SqliteArrowColumn` types a column whose first value that is not NULL is text as `utf8`,
and one whose first such value is a blob as `binary`.
A column of NULL values declared with TEXT or BLOB affinity takes that type,
where the fetch failed before.

Values that don't fit the type of their column follow #795.
Numbers in a `utf8` or `binary` column are the text SQLite renders,
text in a `binary` column is its UTF-8 bytes,
and text and blobs in an `int64` or `double` column are read as SQLite reads them.
A blob in a `utf8` column keeps its bytes, also in a UTF-16 database.
Text or a blob in a `utf8` column must be valid UTF-8 without a NUL byte,
as `rsqlite_is_utf8_string()` checks it, or the value is NULL,
so that the arrays pass Arrow's full validation and convert to R strings.
An `int64` column takes NULL where SQLite would saturate the leading integer of text,
as it already does for a real beyond the range of int64.
None of these conversions is reported yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
@krlmlr
krlmlr added this pull request to stack #851 November 12, 2026 18:45

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 689a5c5, by a Claude Code reviewer with clean context that read the description, the commit's diff against #859 (90753dc), the surrounding fetch loop and read-ahead in SqliteResultImpl.cpp, #845's validator (context only), #795's SqliteArrowColumn.cpp at 3436358 and SQLite 3.54.1's sqlite3Atoi64(), valueToText() and columnMallocFailure(). I built the pull request and its base, a sanitizer build and two mutants, and ran the tests and my own reproducers. I posted nothing myself.

What was run

  • The changed tests (test-arrow-text.R, test-arrow-columns.R, test-utf8.R) against the pull request (all pass) and the base (the new tests fail with "not supported yet", as expected); each changed or added test_that() block alone after pkgload::load_all() (all pass).
  • devtools::test() with NOT_CRAN=true: 10929 passed, only the three known test-httpvfs.R errors; the 1 GB test of test-blob.R passed.
  • A fuzzer: about 1250 chunks of random sizes over mixed integers, reals, infinities, text, invalid UTF-8, NUL bytes, blobs and zeroblobs, each checked with nanoarrow's IPC round trip, arrow 26.0.1's ValidateFull(), and an oracle written in R independently of the C++ (R's validUTF8() for text, a digit-string parse for saturation).
  • Targeted probes for saturation edge cases, UTF-16LE and UTF-16BE databases, SQLite's hard heap limit, a column of 3 × 1.1 GB per chunk, and timing with and without the UTF-8 check.
  • AddressSanitizer and UBSan (gcc 13, -O1) over the changed tests, test-read-ahead.R, test-encoding.R and a script with gctorture(TRUE): no report.

What holds

  • Every chunk passes both validations: offsets, validity bitmaps, empty strings and blobs, zeroblob(0), NULLs, values up to 1.1 GB. Negative controls confirm that the IPC round trip catches bad offsets and that ValidateFull() catches invalid UTF-8.
  • The conversions match feat: Implement the DBI Arrow interface natively #795 and the description, and differ from dbFetch() only where the description says. leading_integer_fits() agrees with SQLite on whitespace (\t–\r), signs, leading zeros, ±2^63 and trailing text. Reading blobs as text in the encoding of the database in integer_value() is more faithful than feat: Implement the DBI Arrow interface natively #795's raw read: in UTF-16, x'3900…' × 20 is NULL as SQLite saturates it, where feat: Implement the DBI Arrow interface natively #795 would give 2^63 − 1.
  • sqlite3_column_text()/_blob() always come before _bytes(), and every pointer is copied before the next step.
  • A chunk over 2^31 − 1 bytes in one column fails with "Can't append to Arrow array", completes the result (row count 0) and leaves the connection usable. The message names neither the column nor the limit, which pull request 8 is to add.
  • The cost of the check (median of 9, 1M rows): none measurable on 50-byte ASCII, about +10 % on 100 MB of long ASCII, +8 to +26 % on é or CJK text. All of these stay well below dbFetch().
  • Keeping all conversions silent until pull request 7 seems acceptable to me while the entry point is internal: the header says so and the tests pin the values. Pull request 7 has to land before pull request 16 exposes the entry point.
  • SqliteArrowColumn.dd gains only utf8.h, a relative path; the scope matches the title.

High

None.

Medium

  1. On out of memory, the last row of a full chunk is delivered with a wrong value instead of failing the fetch.

    struct ArrowBufferView SqliteArrowColumn::value_bytes(int column_type) const {
    // sqlite3_column_text() or sqlite3_column_blob() converts the value,
    // and must come before sqlite3_column_bytes()
    const void* data = (column_type == SQLITE_BLOB)
    ? sqlite3_column_blob(stmt, j)
    : sqlite3_column_text(stmt, j);
    struct ArrowBufferView out;
    out.data.data = data;
    out.size_bytes = sqlite3_column_bytes(stmt, j);
    if (data == NULL) {
    // A blob of no bytes, or out of memory while converting the value,
    // which fails the next step with SQLITE_NOMEM
    out.data.data = "";
    out.size_bytes = 0;
    }
    return out;
    }
    (also L280-L287). The comment assumes that a failed conversion "fails the next step with SQLITE_NOMEM". But the step after the last row of a full chunk is read_ahead(), which keeps that error for the next fetch. (Confirmed) In a UTF-16 database with PRAGMA hard_heap_limit set after the first step, fetch_arrow_chunk(res, 1) on a 20M-character text returns a chunk whose value is "", and only the next fetch fails with "out of memory". The same happens in an int64 column: '9223372036854775807' followed by 20M characters comes back NULL instead of 2^63 − 1. With n = -1 the error surfaces in the same fetch. dbFetch() crashes R in the same situation, which is pre-existing. A consumer that writes chunks as they arrive has already written the wrong chunk.

    Suggested fix: when sqlite3_column_text() returns NULL, or sqlite3_column_blob() returns NULL while sqlite3_errcode(sqlite3_db_handle(stmt)) == SQLITE_NOMEM, throw. The fetch loop then completes the result and the chunk is discarded. Correct both comments.

Low

  1. Within the first chunk, text converted before a real widens an int64 column keeps its integer reading, so values depend on row order.

    void SqliteArrowColumn::append_value(int column_type) {
    switch (kind) {
    case AK_INT64:
    if (column_type == SQLITE_FLOAT && !frozen) {
    // The type is still open: a real value widens the column
    promote_to_double();
    append_value(column_type);
    return;
    }
    append_int64(column_type);
    break;
    (Confirmed) 1, '2.5', 3.5, '99999999999999999999' gives 1, 2, 3.5, 1e20. 1, '99999999999999999999', x'2d39…' (-1e22), 3.5 gives 1, NA, NA, 3.5, while the same values with the real first give 3.5, 1, 1e20, -1e22. The final column is double in both orders. This is inherited from feat: Implement the DBI Arrow interface natively #795's promote_to_double(). dbFetch() gives 2 as well, and -1 and 0 for the saturated values.

    Suggested fix: let text or a blob whose leading integer saturates widen an open int64 column as a real does. Otherwise state the order dependence in the header and pin it in a test.

  2. Parts of the saturation check, and the error path for building a chunk, have no test.

    return true;
    }
    // SQLite saturates the leading integer of text and blobs,
    // which it reads as text in the encoding of the database
    const char* text =
    reinterpret_cast<const char*>(sqlite3_column_text(stmt, j));
    return text != NULL &&
    leading_integer_fits(text, sqlite3_column_bytes(stmt, j));
    (Confirmed) A mutant that reads blobs with sqlite3_column_blob(), as feat: Implement the DBI Arrow interface natively #795 did, passes all tests, yet returns 2^63 − 1 for UTF-16 digits in a blob. (by reading) No test has whitespace or + before a saturating integer. The removed feat: Build Arrow arrays from the integer, real and NULL columns of a result #859 test was the only one in which building a chunk throws; the overflow path now has no test, and my probe shows it works. The description doesn't mention the deviation from feat: Implement the DBI Arrow interface natively #795.

    Suggested fix: add ' \t99999999999999999999', '+9223372036854775808' and a UTF-16 blob of digits to the int64 tests, mention the deviation in the description, and test the overflow error with the small limits of pull request 8.

  3. The description and a test comment overstate what is pinned.

    # A blob in a utf8 column keeps its bytes, where the default path
    # transcodes them from UTF-16 (#799);
    # a lone surrogate and a NUL character make the text NULL
    (Confirmed) "The tests pin both" doesn't hold for the UTF-16 blob in a text column: only Arrow's "ab" is checked, and dbFetch() gives U+6261. "A lone surrogate makes the text NULL" holds only at the end of the text: SQLite merges x'780000d86100' into "x" followed by U+10061, which is valid UTF-8, the same in dbFetch().

    Suggested fix: pin dbFetch()'s value or reword the description. Say that a lone surrogate is NULL only at the end of the text, and that elsewhere SQLite's transcoding changes it.


Generated by Claude Code

SQLite reports a conversion that runs out of memory
as a NULL pointer from `sqlite3_column_text()` or `sqlite3_column_blob()`,
and fails only the next step.
After a full chunk that step only reads ahead and keeps its error for the next fetch,
so the chunk came back with a wrong value:
text as an empty string, a saturating integer as NULL, a real as zero.
The column now fails the fetch where the conversion fails,
which completes the result like any other error.
A blob gives its size before `sqlite3_column_blob()`,
so that a zeroblob() that can't expand is told from a blob of no bytes,
and text and blobs read into a double column are read as UTF-8 text first.

In the chunk that decides the types,
text and blobs that an int64 column has read as integers
take the readings as reals they would have in a double column
when a real widens the column later in that chunk,
so that their values don't depend on the order of the rows.

The tests force the out-of-memory case with SQLite's hard heap limit
in an R session of its own, as the limit can't be lifted again,
and add whitespace and a sign before saturating integers
and the digits of a blob in a UTF-16 database.
A test comment claimed that a lone surrogate makes UTF-16 text NULL anywhere;
it does so only at the end of the text.

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 12, 2026
…actly

`append_date()` and `append_time()` read text through `value_text()` of #860,
so that a conversion of text that runs out of memory fails the chunk at once,
as for the other columns, instead of becoming NULL.
`fetch_arrow_chunk_out_of_memory()` takes setup statements and `extended_types`,
and a new test runs it on DATE, TIME and TIMESTAMP columns
whose text is computed as it is read.

Reals are rounded to microseconds with `std::nearbyint()`,
to the nearest integer, halves to even in the default rounding mode.
`std::floor(x * 1e6 + 0.5)` rounded an odd count between 2^52 and 2^53 one up,
such as `5000000000.000001` seconds, where the count is exact and adding 0.5 makes a tie.
`std::llround()` would round halves away from zero,
but is unspecified for an infinity or a value beyond 64 bits,
which the range check after rounding handles as it is.
The tests pin that example, its negative, and two exact halves,
and the dates that `dbFetch()` makes of huge and infinite reals in a DATE column,
which the Arrow array holds as NULL.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of the fixes in this pull request at 3ac16c6 (the commits since 689a5c5), by a Claude Code reviewer with clean context that read the diff of 3ac16c6 against its parent f6f6b3e (the merge of #859's head, taken as context), the description, the first review, the fetch loop and read-ahead in SqliteResultImpl.cpp, and SQLite 3.54.1's valueToText(), sqlite3VdbeMemGrow(), sqlite3ValueBytes(), sqlite3_value_blob() and sqlite3MemRealValueRC(). I built 3ac16c6 and f6f6b3e, a sanitizer build and a mutant, and ran the tests and my own reproducers. I posted nothing myself.

What was run

  • test-arrow-text.R, test-arrow-columns.R and test-utf8.R from 3ac16c6 against an installed 3ac16c6 (all 330 pass, the out-of-memory test runs) and an installed f6f6b3e (14 failures, all in the widening and out-of-memory blocks).
  • Each of the 11 blocks of test-arrow-text.R alone right after pkgload::load_all(): all pass; the out-of-memory block skips, also with NOT_CRAN=true and an installed copy of the branch on the library path.
  • devtools::test() with NOT_CRAN=true: 10947 passed, only the three known test-httpvfs.R errors.
  • An out-of-memory matrix, one R process per case, with PRAGMA hard_heap_limit set after the first chunk: text, numbers and zeroblobs in utf8, binary, open and fixed int64 and double columns, in UTF-8 and UTF-16, and values that need only the terminating NUL. Each on both builds.
  • A fuzzer: 450 first chunks of an int64 column in UTF-8, UTF-16le and UTF-16be, with integers, reals, text, blobs, zeroblobs and NULLs in random order and random chunk splits, checked against CAST(v AS REAL) and between the two builds. A double column of the same kinds of values against dbFetch() and CAST(v AS REAL).
  • Memory (VmHWM, VmRSS) and time (median of 9) for text in int64 and double columns and for a zeroblob in a double column.
  • AddressSanitizer and UBSan (gcc 13, -O1) over the three test files with the callr test, test-read-ahead.R, test-encoding.R, the first review's script under gctorture(TRUE), the out-of-memory matrix and the fuzzer.

What holds

  • The Medium of the first review is fixed. Wherever f6f6b3e returns "", NULL, 0 or an empty blob for a value whose conversion runs out of memory, 3ac16c6 fails the fetch with "Column `x`: out of memory while reading a value.". The result is then complete with a row count of 1, and the connection works afterwards.
  • The edge where only the terminating NUL fails is covered. When sqlite3VdbeMemGrow() can't add the terminator, it sets the value to NULL, and valueToText() returns NULL (by reading). (Confirmed) A 2 KB unhex() blob in a double column needs nothing but the terminator: f6f6b3e gives 0, and 3ac16c6 fails. Text in a fixed int64 column that SQLite reads without converting it ('12' followed by 20M characters) still gives 12, and the error is kept for the next fetch, as before.
  • Reading the size of a blob first is safe. sqlite3ValueBytes() returns n + nZero for any blob without converting it, and x'' and zeroblob(0) give empty blobs. Pointers are used before the next sqlite3_column_*() call.
  • Low 1 of the first review is fixed. All 184 fuzzed chunks that widen to double equal CAST(v AS REAL) in every row order and encoding (f6f6b3e: 86 mismatches), and so do their later chunks. All 238 chunks that stay int64 are identical to f6f6b3e.
  • Reading text and blobs as UTF-8 before reading them into a double column gives the same values as dbFetch() and CAST(v AS REAL) in all three encodings. The cases include lone surrogates, NUL, U+0130, Arabic digits and blobs that SQLite reads as UTF-16. The peak memory for 100M characters of UTF-16 text is the same as on f6f6b3e.
  • Lows 2 and 3 are fixed as suggested, and the description says what the code does.
  • The callr test exercises the installed code under test: it fails on f6f6b3e. Each run takes about 2.4 s, and it passed every time, also under the sanitizers. Its margins are wide: 40 MB is held, the conversion needs 60 MB more, and the limit is 50 MB.
  • The Arrow code gets no sanitizer report. The only report is UBSan's memcpy from NULL for an empty blob in SqliteColumnDataSource::fetch_blob(), on the data-frame path, which is unchanged from main.
  • No .dd file changes, and the scope matches the title.

High

None.

Medium

None.

Low

  1. The readings as reals take 16 bytes per text value of an open int64 column, and stay allocated until the result is cleared.

    if ((column_type == SQLITE_TEXT || column_type == SQLITE_BLOB) && !frozen) {
    // For a real that may widen the column later in this chunk
    text_reals.push_back(std::make_pair(array->length, text_real()));
    }
    (with clear() in L65-L72). (Confirmed) I used a column whose first value is an integer, followed by 5M text values, fetched in one chunk. 3ac16c6 peaks at 251 MB against 127 MB on f6f6b3e, although the int64 array itself takes 40 MB. Another 78 MB is still held after the chunk is released and collected, until dbClearResult(): clear() keeps the vector's capacity, and the column never reads it again once frozen. For 2M rows, the fetch takes 0.265 s against 0.158 s. Nearly every stored reading equals the integer reading ('abc' gives 0 and 0.0). The description doesn't mention this cost.

    Suggested fix: store a reading only when it differs from the integer reading, or when the integer reading is NULL, and release the storage in freeze() (std::vector<...>().swap(text_reals)).

  2. A zeroblob() in a double or open int64 column is now expanded, only to read 0.

    // Text or a blob as SQLite reads it into a real.
    // Reading it as UTF-8 text first tells a failed conversion from a zero,
    // and leaves sqlite3_column_double() nothing to allocate.
    double SqliteArrowColumn::text_real() const {
    value_text();
    return sqlite3_column_double(stmt, j);
    }
    (Confirmed) For iif(column1 = 1, 1.5, zeroblob(500000000)), the fetch of the second row peaks 477 MB higher on 3ac16c6 and 0 MB higher on f6f6b3e. Both give 0. Under a 50 MB heap limit, 3ac16c6 fails that fetch, while f6f6b3e returns the correct 0 and its next fetch succeeds. SQLite reads a zeroblob as 0 without expanding it, because sqlite3MemRealValueRC() returns 0 when z == NULL.

    Suggested fix: for blobs, call sqlite3_column_double() and tell a failed conversion by sqlite3_errcode(sqlite3_db_handle(stmt)) == SQLITE_NOMEM, which columnMallocFailure() sets right away. Otherwise, say in the comment and the description that a zeroblob is expanded.


Generated by Claude Code

…olumn

An open `int64` column kept the reading as a real of every text or blob value
for a real that may widen it later in the chunk,
16 bytes each, also when the reading equals the integer,
and kept their capacity until the result was cleared.
It now keeps only the readings that differ from the integer,
and releases them once the first chunk fixes the type.

A blob in a `double` or open `int64` column is read as a real
with `sqlite3_column_double()` instead of as text first,
so that a zeroblob() isn't expanded just to read 0.
Running out of memory while copying a blob for that reading
shows only in the error code of the connection,
which is compared with its value before the call,
since a code left from an earlier call can't be told apart.

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

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.

Two review rounds: the first found that running out of memory on the last row of a full chunk returned a wrong value (Medium) and that the first chunk's values depended on row order when an int64 column widened, plus test and wording gaps; 3ac16c6 fixed all of them and merged #859's head. The second found nothing above Low: no path returns a wrong value on out of memory any more, and widened values equal CAST(v AS REAL) in every row order in UTF-8 and both UTF-16 encodings. Its two Lows are fixed in 32dea06 (only differing real readings are kept and released when the type is fixed; a zeroblob() in a numeric column is no longer expanded). These remain:

  • src/SqliteArrowColumn.cpp#L236-L246: in the first chunk, every text value in a not-yet-fixed int64 column is also read as a real (2M text values: 0.21 s against 0.15 s before the widening fix), and each reading that differs from the integer costs 16 bytes until the chunk ends (5M fractions: +164 MB peak against +40 MB). This is the price of values that do not depend on row order; the description states it. Relevance: low; reviewer's confidence: high.
  • src/SqliteArrowColumn.cpp#L381-L395: a blob read into a numeric column goes through sqlite3_column_double(), whose out-of-memory failure shows only in the connection's error code; when the code already held SQLITE_NOMEM from an earlier call, the failure is not detected there and the next step fails instead. Text keeps the reliable NULL-pointer check. Relevance: low; reviewer's confidence: medium.
  • src/SqliteArrowColumn.cpp#L253: a chunk whose values in one column exceed 2^31 − 1 bytes fails with "Can't append to Arrow array", naming neither the column nor the limit; the failure completes the result and leaves the connection usable. Pull request 8 ends chunks before the offsets overflow. Relevance: medium (internal entry point only until pull request 16); reviewer's confidence: high.
  • src/SqliteArrowColumn.h: conversions (invalid UTF-8 or NUL text to NULL, values between text, blob and number types) are silent here; feat: Report values converted to an Arrow column's type once per chunk, with their rows #862 reports them once per chunk. Relevance: medium (internal entry point only); reviewer's confidence: high.
  • src/SqliteColumnDataSource.cpp#L92: UBSan reports a memcpy() from a NULL pointer for empty blobs on the data-frame path, unchanged from main and unrelated to this pull request. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: drop the reading as a real of text in an open int64 column?

In the first chunk, every text value in an int64 column whose type is still open is also read as a real, so that a real arriving later in the chunk widens it with the same values in any order of the rows (src/SqliteArrowColumn.cpp#L235-L246). That takes time (2 million text values: 0.21 s instead of 0.15 s), and each reading that differs from the integer costs 16 bytes until the chunk ends (5 million fractions: +164 MB peak instead of +40 MB). The description states these figures.

  • Keep it: it is the price of values that don't depend on row order (recommended)
  • Go back to feat: Implement the DBI Arrow interface natively #795's rule, which keeps the integer reading after a real widens the column, so that 1, '2.5', 3.5 gives 1, 2, 3.5 and the values depend on row order

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


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: detect running out of memory while reading a blob as a number in every case?

A blob read into a double or open int64 column goes through sqlite3_column_double(), which reports running out of memory only through the error code of the connection (src/SqliteArrowColumn.cpp#L386-L397). When that code already held SQLITE_NOMEM from an earlier call, the failure isn't detected there, and the next step fails instead. Text keeps the reliable check for a NULL pointer. A reproducer needs a heap limit that fails exactly that copy after an earlier call left SQLITE_NOMEM, which isn't practical as a script.

  • Accept it: it needs two failed allocations in a row, and the next step still fails (recommended)
  • Read the blob's bytes with sqlite3_column_blob() and convert them as SQLite does, which brings back the NULL-pointer check but expands a zeroblob() again

Kirill decides. If nobody decides, the check stays as it is, and the limitation stays checked in the "Accepted limitations".


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: name the column and the limit when a chunk's text or blobs exceed 2^31 − 1 bytes?

utf8 and binary arrays have 32-bit offsets. A chunk whose values in one column exceed 2^31 − 1 bytes fails with "Can't append to Arrow array", naming neither the column nor the limit (src/SqliteArrowColumn.cpp#L326-L328, and for blobs #L220-L222). The failure completes the result and leaves the connection usable. A reproducer needs more than 2 GB of values in one chunk, for example two rows of zeroblob(1200000000) fetched with n = -1; it wasn't run for this question.

  • Accept it until pull request 8 of the plan ends chunks before the offsets overflow (recommended)
  • Name the column and the limit in the error in this pull request

Kirill decides. If nobody decides, the message stays until pull request 8, and the limitation stays checked in the "Accepted limitations".


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: report the conversions of text and blob values in this pull request?

Values that don't fit the type of their column are converted or become NULL without notice (src/SqliteArrowColumn.h#L23-L24): text that isn't valid UTF-8 or holds a NUL byte, and values between text, blob and number types. Against this pull request's head:

library(DBI)
con <- dbConnect(RSQLite::SQLite())
res <- dbSendQuery(con, "
  SELECT CAST(x'ff' AS TEXT) AS bad_utf8, 'a' || char(0) || 'b' AS nul,
    CAST('12abc' AS TEXT) AS t
  UNION ALL SELECT 'ok', 'ok', 3
")
# Invalid UTF-8 and text with a NUL byte become NULL, and the number 3
# becomes the text "3", all without notice
# (expected: a warning, or a report as #862 adds)
nanoarrow::convert_array(RSQLite:::result_fetch_arrow_chunk(res@ptr, -1L))
#>   bad_utf8  nul     t
#> 1     <NA> <NA> 12abc
#> 2       ok   ok     3
dbClearResult(res)
dbDisconnect(con)

Kirill decides. If nobody decides, the conversions stay silent until #862, and the limitation stays checked in the "Accepted limitations".


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Two review rounds: the first found that running out of memory on the last row of a full chunk returned a wrong value (Medium) and that the first chunk's values depended on row order when an int64 column widened, plus test and wording gaps; 3ac16c6 fixed all of them and merged #859's head. The second found nothing above Low: no path returns a wrong value on out of memory any more, and widened values equal CAST(v AS REAL) in every row order in UTF-8 and both UTF-16 encodings. Its two Lows are fixed in 32dea06. The UBSan report of a memcpy() from a NULL pointer for empty blobs on the data-frame path, which the previous copy listed, is fixed on main by #869, which this branch includes. These remain:


Generated by Claude Code

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants