Skip to content

fix: dbFetch() raises "out of memory" instead of crashing when SQLite cannot convert a text value - #890

Merged
krlmlr merged 3 commits into
mainfrom
claude/fix-889-null-text-oom
Nov 14, 2026
Merged

krlmlr merged 3 commits into
mainfrom
claude/fix-889-null-text-oom

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

When SQLite runs out of memory while it converts a column value, for instance while transcoding a large text value from a UTF-16 database under a heap limit, sqlite3_column_text() and sqlite3_column_blob() return NULL and set SQLITE_NOMEM on the connection. With check_utf8 = FALSE (the default, and the only behavior of RSQLite 3.53.3 from CRAN), fetch_string() passed that NULL to Rf_mkCharCE() and R crashed. With check_utf8 = TRUE, fetch_checked_string() returned "" and relied on the next sqlite3_step() failing in the same fetch; with the read-ahead of #850, that step runs ahead and keeps its error, so the "" would reach the caller. The extended_types date, datetime and time readers passed the NULL on to their parsers.

What changes

  • SqliteColumnDataSource gets check_out_of_memory(), which raises Cannot read column <j>: out of memory (SQLite's own message) when a text or blob pointer is NULL and sqlite3_errcode() is SQLITE_NOMEM, as the SQLite documentation describes for these functions. A NULL for a NULL value, or a NULL blob with sqlite3_column_bytes() == 0 (an empty blob), is never an error: the connection can still hold SQLITE_NOMEM from an earlier read of the same row, and such a value reads as "", as before.
  • fetch_text() wraps sqlite3_column_text() with that check; fetch_string() (with check_utf8 = FALSE), fetch_date(), fetch_datetime_local() and fetch_time() use it. fetch_checked_string() runs the check on both its text and its blob pointer, so it no longer depends on the following step, and its comment no longer claims that the "" never reaches the caller.
  • fetch_blob() already raised an error for a NULL blob with a nonzero size and is unchanged.
  • Two internal, unexported entry points in src/rsqlite.cpp, sqlite_heap_limits() and sqlite_memory_used(), let the tests cap SQLite's heap and lift the cap afterwards. PRAGMA hard_heap_limit can only lower the limit, and lowering the hard limit also lowers the soft limit for the whole process; leaving the soft limit behind made test-transactions.R fail with "database is locked" in an earlier draft, so the helper restores both.

Left out

Other SQLite accessors that return NULL on out of memory, such as sqlite3_column_name() and sqlite3_column_decltype(), are not part of this change; sqlite3_column_decltype() returning NULL is already handled as "no declared type".

Tests

tests/testthat/test-out-of-memory.R, with fixtures in helper-heap-limit.R, caps the heap at 16 MB above SQLite's current use and reads a 4-million-character value from an in-memory UTF-16 database: both check_utf8 settings and a DATE column with extended_types = TRUE now raise "Cannot read column 2: out of memory". Measured on Linux, the error appears for headroom from about 8.5 MB (below that the step itself fails with "out of memory") up to 24 MB, and the value reads in full from 26 MB on, so 16 MB sits in the middle; because the sizes depend on SQLite's allocator, these two blocks are skipped on CRAN. A third block reads the same row again after the error and expects the step's "out of memory", not an error blamed on an empty blob in an earlier column. Two further blocks, which also pass on main, read the value in full without a cap and read empty text, X'' and zeroblob(0) as "" in a UTF-16 database with both check_utf8 settings.

devtools::test() with NOT_CRAN=true: no failures besides the three in test-httpvfs.R that main shows too (#832, #837), and test-dbConnect.R's busy-handler test, which needs an installed RSQLite in its callr child and has none in this environment.

The review's reproducer (heap limit of 16 MB, 4 MB text in a UTF-16 file database) under valgrind 3.22.0: on main with check_utf8 = FALSE, "Invalid read of size 1" and a segfault; on main with check_utf8 = TRUE, "out of memory" from the next step; on this branch, "Cannot read column 2: out of memory" for both settings and 0 valgrind errors. The new test file under valgrind also reports 0 errors and no definite leaks. RSQLite 3.53.3 from CRAN segfaults on the same experiment at limits of 10 to 24 MB.

Place in the stack

Based on main (3f746a0) and independent of the open stack. Once #850 lands on top, check_utf8 = TRUE raises the error in the fetch that reads the value rather than returning "" and deferring the error to the next fetch.

Review and accepted limitations: Accepted limitations; the pre-existing sqliteCopyDatabase() crash found in review is #891.

Closes #889.

Coordinating session: https://claude.ai/code/session_01Hr1rd7mthffYErGmWTGDfQ


Generated by Claude Code

claude and others added 3 commits November 13, 2026 20:13
…te cannot convert a text value

`sqlite3_column_text()` and `sqlite3_column_blob()` return `NULL`
when SQLite runs out of memory,
for instance while transcoding a large value from a UTF-16 database.
With `check_utf8 = FALSE`, `fetch_string()` passed that `NULL` to `Rf_mkCharCE()` and crashed R;
with `check_utf8 = TRUE`, `fetch_checked_string()` returned `""`
and relied on the next step to fail.
The date, datetime and time readers passed the `NULL` on to their parsers.

All of them now raise an R error with SQLite's message
when the pointer is `NULL` and `sqlite3_errcode()` is `SQLITE_NOMEM`,
as the SQLite documentation describes.
Empty strings and empty blobs read as `""` as before.

The tests cap SQLite's heap through two internal entry points,
`sqlite_heap_limits()` and `sqlite_memory_used()`,
because `PRAGMA hard_heap_limit` cannot lift the limit again
and lowering it also lowers the soft limit for the rest of the process.

Closes #889.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7mthffYErGmWTGDfQ
…out of memory

A second `dbFetch()` after an out-of-memory error reads the same row again,
with `SQLITE_NOMEM` still on the connection.
With `check_utf8 = TRUE`, the `NULL` that `sqlite3_column_blob()` returns
for an empty blob in an earlier column then raised
"Cannot read column <j>: out of memory" for that column.

A `NULL` blob with `sqlite3_column_bytes() == 0` is now an empty blob,
and a `NULL` text pointer for a NULL value is never an error;
the next step reports the out-of-memory error instead.

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

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 2b03480, by a Claude Code reviewer with clean context that read the description, issue #889, the diff against main (3f746a0) and the code around it in src/SqliteColumnDataSource.cpp, src/DbColumnStorage.cpp, src/SqliteResultImpl.cpp and SQLite's own error-code handling (sqlite3Step(), columnMallocFailure(), apiHandleError()). It built the pull request, its base, and the base with only the new test hooks (src/rsqlite.cpp, src/cpp11.cpp, R/cpp11.R) into separate libraries, ran the tests and its own reproducers on all of them, and ran the issue's experiment and the new tests under valgrind. It posted nothing itself.

What was run

  • tests/testthat/test-out-of-memory.R on the pull request (6 expectations pass) and on the base with the hooks (blocks 1 and 2 fail: segfault and "out of memory" from the step; blocks 3 and 4 pass), and each of the four test_that() blocks alone after pkgload::load_all() on both.
  • devtools::test() with NOT_CRAN=true on both: the same four errors on each, the three in test-httpvfs.R and test-dbConnect.R's busy-handler test (its callr child has no installed RSQLite here).
  • The issue's experiment under valgrind 3.22.0 with both check_utf8 settings: main with FALSE gives "Invalid read of size 1" and a segfault, with TRUE "out of memory" from the step; the pull request gives "Cannot read column 2: out of memory" for both, with 0 valgrind errors and no definite leaks. The new test file under valgrind: 0 errors, no definite leaks.
  • Own reproducers: re-fetching the same row after the error with the limit lifted (retry.R, also under valgrind), restoring the limits after failing and erroring tests (restore.R), an OOM in a backup while a result is open (stale-backup.R), and a sweep of the headroom (window.R).
  • cpp11::cpp_register() on the pull request leaves src/cpp11.cpp and R/cpp11.R unchanged; no src/*.dd file is touched.

What holds

  • sqlite3_step() sets the connection's error code to SQLITE_ROW on success, and RSQLite reads columns only after a step, so a NOMEM from an earlier row, an earlier statement or a finalized result cannot reach check_out_of_memory(). An OOM in a backup with the connection as source while a result is open did not leave a stale code either: the empty blob still read as "".
  • Empty text, X'' and zeroblob(0) read as "" in a UTF-16 database with both settings, as on main.
  • After the error, dbClearResult() succeeds and the connection answers further queries, under valgrind as well; the error is raised through cpp11::stop(), as other errors on this path already are.
  • local_sqlite_heap_limit() restores both limits (a nonzero soft limit included) after an expectation failure and an R error, inside local() and at test level. The tests do not run in parallel (Config/testthat/parallel is not set), so the process-wide limit affects only the few lines that set it.
  • The window is SQLite's own arithmetic (an 8 MB value plus a 16 MB transcoding buffer), not the allocator's: "out of memory" from the step up to 8 MB, the new error from 9 to 24 MB, the value in full from 25 MB. 16 MB sits well inside it, and passes under valgrind's allocator too. Skipping these two blocks on CRAN is cautious; the blocks that run on CRAN do not touch the limits.
  • The description matches the code and the scope matches the title.

High

None.

Medium

None.

Low

  1. After an out-of-memory error, re-fetching the same row with check_utf8 = TRUE blames an empty blob in an earlier column.
    src/SqliteColumnDataSource.cpp#L107-L120
    Row 2 holds X'' in column 2 and the 4 MB text in column 3. Under the limit, dbFetch(res, n = 1) raises "Cannot read column 3: out of memory". With the limit lifted, a second dbFetch() on the same result reads the row again without a step, so the connection still holds SQLITE_NOMEM from the failed conversion. sqlite3_column_blob() returns NULL for the empty blob, and the fetch raises "Cannot read column 2: out of memory" (Confirmed, retry.R). With check_utf8 = FALSE the same retry raises "out of memory" from the step, which is correct. The statement is already broken (SQLite fails the next step), so only the column named is wrong. The base behaves differently but no better: with TRUE the second fetch silently returns a row of NAs, and with FALSE it crashes on the first fetch (Confirmed on the base with the hooks). The pull request introduces the wrong attribution.
    Suggested fix: for the pointer from sqlite3_column_blob(), treat NULL as an empty blob when sqlite3_column_bytes() is 0, which allocates nothing for a blob, and apply the sqlite3_errcode() check only when the size is nonzero or the pointer comes from sqlite3_column_text(). Alternatively, accept this and note it in the comment.

  2. Already on the base, outside this pull request: sqliteCopyDatabase() segfaults when the destination has an open result.
    src/DbConnection.cpp#L81-L88
    sqlite3_backup_init() returns NULL ("destination database is in use"), and sqlite3_backup_step(NULL, -1) crashes with "address 0x28". This happens on main without any heap limit (Confirmed, backup-crash.R; found while probing for stale error codes). It is the same kind of unchecked-NULL crash as dbFetch() crashes R, or returns "", when SQLite runs out of memory converting a text value #889.
    Suggested fix: a separate issue. Check the result of sqlite3_backup_init() and raise sqlite3_errmsg(pDest->conn()).


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

One clean review round (report) found nothing above Low. Its one introduced finding, a fetch after an out-of-memory error blaming an empty blob in an earlier column with check_utf8 = TRUE, is fixed in f9419bc: a NULL blob with zero bytes is an empty blob and a NULL value is never an error, and a new test pins it. No introduced limitation remains.


Generated by Claude Code

@krlmlr krlmlr mentioned this pull request Nov 14, 2026
16 of 22 tasks
@krlmlr
krlmlr merged commit 37dc8fa into main Nov 14, 2026
8 checks passed
@krlmlr
krlmlr deleted the claude/fix-889-null-text-oom branch November 14, 2026 08:51
krlmlr pushed a commit that referenced this pull request Nov 14, 2026
Cite only the final SQLite upgrade,
and say that the UTF-8 check is opt-in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd6znpbaJUu6TJLjgQC
@krlmlr krlmlr mentioned this pull request Nov 14, 2026
6 of 11 tasks
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
…mory

The test for an empty blob read again after out of memory, from #890,
ran out of memory in a fetch and fetched the same row again.
A fetch whose conversion fails now completes the result,
so that row is never read again, and the test lost its point.

A fetch of zero rows looks at the next row without reading it,
and running out of memory there leaves the result going on,
so the test now runs out of memory there
and reads the row again in the next fetch, as before.

A new test pins what a fetch that runs out of memory does now:
it raises the error once, completes the result,
and further fetches return zero rows without stepping the statement again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd8MVXyvU7qoMeruD1R
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.

dbFetch() crashes R, or returns "", when SQLite runs out of memory converting a text value

2 participants