Skip to content

fix: Count rows in 64 bits, so that dbGetRowCount() and dbGetRowsAffected() stay right beyond INT_MAX - #858

Merged
krlmlr merged 2 commits into
mainfrom
claude/row-count-64bit
Nov 13, 2026
Merged

krlmlr merged 2 commits into
mainfrom
claude/row-count-64bit

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

dbGetRowCount() counted the rows fetched from a result in an int, incremented once per row. A result read in chunks, such as dbFetch(res, n = 1e6) in a loop, can pass INT_MAX rows in total, for example a recursive CTE that generates its rows without storing them. The signed increment then overflowed, which is undefined behavior; in practice dbGetRowCount() returned NA at 2^31 rows and negative counts after that.

dbGetRowsAffected(), and with it dbExecute(), had the same problem: it subtracted two values of sqlite3_total_changes(), which SQLite truncates to an int, so that the count turned negative once the changes since one dbBind() or dbExecute(), summed over all its parameter rows, passed INT_MAX. Where a connection's total of changes passes INT_MAX, the subtraction itself also overflowed, even for a statement that changes a few rows, although in practice the wrapped result came out right there.

Both counts are now int64_t, and the changes come from sqlite3_total_changes64(), which the bundled SQLite 3.54.1 has. dbGetRowCount() and dbGetRowsAffected() return an integer while the count fits, as before, and a double beyond INT_MAX, the only R type without bit64 that holds the count exactly up to 2^53. dbGetRowsAffected() still returns an integer NA before dbBind().

The fix of the fetched rows is the one the old Arrow stack carries in 1914d20 (#795), without the Arrow parts around it, and it moves out of item 8 of the plan to rework the Arrow stack, which keeps the end of Arrow chunks before string offsets overflow. The fix of the changed rows is new: the old stack keeps the int there.

Tests

tests/testthat/test-row-count.R, with every test_that() block self-contained:

  • Two tests set the counts just below INT_MAX through two unexported entry points for the tests, result_set_rows_fetched() and result_set_rows_affected(), then fetch real rows across the limit and check the exact values on both sides: an integer up to INT_MAX, a double beyond. The changed rows go across the limit for real through an INSERT ... RETURNING, whose changes SQLite counts once its last row is fetched. The hook moves the start of the count, not SQLite's total of changes, so that only the gated test below catches a return to the 32-bit sqlite3_total_changes(). Both hooks stop with an error unless the count is a whole number from 0 to 2^53. On main, both fail, as the entry points do not exist there.
  • Two tests reach the limit for real and are skipped unless RSQLITE_TEST_INT_MAX_ROWS=true, with the variable's name in the skip message. One fetches 2^31 + 1 rows of a recursive CTE in chunks of 10^6 rows, which took 608 s here on a machine busy with other jobs (a run of 10^7 rows suggests about six minutes when idle); on main, dbGetRowCount() returns NA at 2^31 rows and -2147483647 one row later. The other runs UPDATE on a table of 2^20 rows with 2^11 + 1 parameter rows, 2^31 + 2^20 changes in one dbExecute(), which took 107 s here; on main, dbExecute() returns -2146435072.

devtools::test() with NOT_CRAN=true passes, apart from the three errors in test-httpvfs.R that main has as well (#832, #837) and "interrupt in busy handler" in test-dbConnect.R, whose callr session found no installed RSQLite after pkgload::load_all(); #830 skips it in that case, and it passes against the installed build.

Speed of the default path

A fetch of 5 million rows of an integer and a real column, as a whole and in chunks of 10^5 rows, median user CPU time of seven runs, three alternating runs per build: 1.16 s as a whole and 1.14 to 1.24 s in chunks on main, 1.15 to 1.16 s and 1.10 to 1.17 s with this pull request. The difference is within the noise.

Where this sits

This is a separate pull request from main. The new Arrow stack, on #830 and #850, picks it up by merging main once this lands. git merge-tree --write-tree origin/claude/fix-error-mid-result HEAD reports conflicts in four files, in five small hunks: in each, #830 adds a line next to a declaration or a sqlite3_total_changes() call that this pull request changes (busy() next to n_rows_fetched() in DbResult.cpp and DbResult.h, bind_started_ next to the counts in SqliteResultImpl.h, in n_rows_affected() and in bind()). Keeping both sides resolves all of them. The fetch loop that #850 and #830 rewrite merges without a conflict, as this pull request leaves the line that counts the rows alone: #830 adds an int count of the rows of one fetch to nrows_, which is now an int64_t. #850 alone merges without any conflict. A trial merge into #830 with these resolutions builds, and test-row-count.R, test-dbSendQuery.R, test-read-ahead.R and test-dbClearResult.R pass on it.

For the reviewer

  • The R type: dbGetRowCount(), dbGetRowsAffected() and dbExecute() return a double instead of an integer beyond INT_MAX, where they returned NA or a negative integer before. DBI's specification allows either type: "a scalar number (integer or numeric)". Code that checks for an integer with is.integer() sees the change only beyond INT_MAX.
  • Windows, where long is 32 bits: the counts use int64_t and SQLite's sqlite3_int64, never long, and reach R through a cast to int or double, never through a format string.
  • The speed of the default path, measured above: the per-row increment is now on an int64_t.

Reviewed in a clean review, which found nothing above Low; its points are fixed in 7ca358d or listed in the accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

…ffected()` stay right beyond `INT_MAX`

The number of rows fetched from a result was an `int`, incremented once per row.
A result read in chunks can pass `INT_MAX` rows in total, for example a recursive CTE that generates rows without storing them,
and then the signed increment overflowed: in practice `dbGetRowCount()` returned `NA`, then negative counts.
The number of rows changed was the difference of two `sqlite3_total_changes()` values, which SQLite truncates to an `int`,
so that `dbGetRowsAffected()` and `dbExecute()` turned negative once one execution changed more than `INT_MAX` rows.
Both counts are now `int64_t`, the changes come from `sqlite3_total_changes64()`,
and both functions return an integer while the count fits, as before,
and a double beyond `INT_MAX`, the only R type without bit64 that holds it exactly up to 2^53.

Two unexported entry points for the tests set the counts close to the limit.
Two tests that fetch and change 2^31 rows for real take minutes
and run only with `RSQLITE_TEST_INT_MAX_ROWS=true`.

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 this pull request at 76e4ebe, by a Claude Code reviewer with clean context that read the description, the diff against main at 3b7bea3, the code around it (the fetch loop, the bind path, the R wrappers, the cpp11 conversions of the result pointers) and DBItest's specification of dbGetRowCount(), dbGetRowsAffected() and dbExecute(); built the pull request, its base, a trial merge into #830 and a mutant into separate libraries; and ran the tests and the reproducers listed below. I posted nothing on GitHub myself.

What was run

  • R CMD INSTALL of the pull request and of main into separate libraries; cpp11::cpp_register() on a copy, which reproduces R/cpp11.R and src/cpp11.cpp byte for byte.
  • devtools::test() with NOT_CRAN=true on the pull request: only the three test-httpvfs.R errors and "interrupt in busy handler", whose callr session finds no installed RSQLite; test-dbConnect.R passes with the installed build on R_LIBS.
  • Each of the four new test_that() blocks alone in a fresh R process after pkgload::load_all(): the two hook tests pass, the two gated tests skip with the variable's name in the message; against main, both hook tests fail with "could not find function".
  • The gated rows-affected test for real: passes in 2 min 21 s; the same UPDATE on main returns -2146435072L. The gated fetch test for real: passes in 9 min 34 s on a busy machine. The same fetch on main: 2147483647L, then NA at 2^31 rows and -2147483647L one row later, as the description says.
  • git merge-tree --write-tree against fix: Never restart a statement after an error in dbFetch() or dbBind() #830 (aa07034) and fix: A fetch returns its rows when the step past its last row fails #850 (8be7cd8); a trial merge into fix: Never restart a statement after an error in dbFetch() or dbBind() #830 with the conflicts resolved by keeping both sides, then devtools::test() on it and the hook tests alone.
  • Reproducers of the R types before and after a bind, after dbClearResult(), for statements that change no rows, with a trigger, with RETURNING and with a second statement sent on the same connection, on both builds; the hooks with odd inputs; UBSan on the hooks' cast; -Wconversion on the changed files; a mutant that calls sqlite3_total_changes() again. No AddressSanitizer build: the change touches no memory beyond the two counters, and the one crash I found is deterministic.
  • CPU time of fetches and of many small dbExecute() calls, alternating builds, medians of user CPU on a machine at load 6 to 8: a fetch of 5 million rows of an integer and a real column, 1.21 s on main and 1.22 s here as a whole, 1.12 s and 1.19 s in chunks of 10^5 (three runs each, spread up to 0.18 s); 20,000 one-row dbExecute() inserts, 3.20 s on both (eight runs each); 20,000 one-row fetches each followed by both counts, 1.02 s and 0.98 s. No difference beyond the noise.

What holds

  • Both counts are int64_t from the member to the entry point, with no long, no format string and no implicit narrowing (-Wconversion is silent on the changed files), so Windows' 32-bit long does not matter; sqlite3_int64 converts to int64_t at the same width.
  • row_count_as_sexp() returns 2147483647L at INT_MAX and 2147483648 one above (Confirmed); doubles stay exact up to 2^53, and the hook shows 2^53 + 1 rounding to 2^53, a limit no real result reaches.
  • The R types are unchanged below INT_MAX on every path I tried: 0L for queries and for CREATE TABLE or an UPDATE that matches nothing, 5L for a five-row DELETE, NA_integer_ before dbBind() (DBItest checks that with expect_identical()), an error after dbClearResult(). DBItest only uses expect_equal() and is.numeric() on these counts otherwise, and its suite passes.
  • Trigger changes, RETURNING (counted once the last row is fetched) and the counts after a rebind come out the same on both builds. A second statement on the same connection cannot slip in between bind and count through the public API: dbSendQuery() clears the open result first, and the old result then errors.
  • The description is accurate on the conflicts: five hunks in four files against fix: Never restart a statement after an error in dbFetch() or dbBind() #830, all resolved by keeping both sides, and none against fix: A fetch returns its rows when the step past its last row fails #850. The merge builds and passes devtools::test() apart from the three test-httpvfs.R errors; fix: Never restart a statement after an error in dbFetch() or dbBind() #830's nrows_ += n_fetched adds an int to the now 64-bit count.
  • No src/*.dd file changes; the dependencies of SqliteResult.cpp already list SqliteResultImpl.h. The scope matches the title.

High

None.

Medium

None.

Low

  1. The test hooks cast any double to int64_t unchecked, and a connection pointer crashes them.

    RSQLite/src/result.cpp

    Lines 70 to 80 in 76e4ebe

    // For the tests: sets the number of rows fetched from the statement
    [[cpp11::register]]
    void result_set_rows_fetched(SqliteResult* res, double n) {
    res->set_rows_fetched(static_cast<int64_t>(n));
    }
    // For the tests: sets the number of rows the statement has changed so far
    [[cpp11::register]]
    void result_set_rows_affected(SqliteResult* res, double n) {
    res->set_rows_affected(static_cast<int64_t>(n));
    }
    RSQLite:::result_set_rows_fetched(rs@ptr, x) with NA_real_, NaN, Inf or 1e30 is undefined behaviour (UBSan: "nan is outside the range of representable values of type 'long int'"); in practice the count reads 0L, as it also does for NA_integer_, which cpp11 turns into NaN, and for -2^40, which row_count_as_sexp() narrows to int (Confirmed). result_set_rows_fetched(con@ptr, 1) segfaults (Confirmed), as result_get_placeholder_names(con@ptr) does on main, so this is the existing pattern of the internal entry points rather than a new kind of risk. Both hooks are unexported and no user path reaches them. Suggested fix: stop on a non-finite or out-of-range n in both hooks, for example if (!(n >= 0 && n <= 9007199254740992.0)) cpp11::stop("..."), which keeps them harmless when misused with a valid result.

  2. Only the gated test would catch a return to the 32-bit sqlite3_total_changes().

    test_that("dbGetRowsAffected() goes on beyond INT_MAX as a double", {
    con <- dbConnect(SQLite(), ":memory:")
    on.exit(dbDisconnect(con), add = TRUE)
    dbExecute(con, "CREATE TABLE t (a INTEGER)")
    # SQLite counts the changes of a statement with RETURNING
    # once the statement is done, after its last row
    rs <- dbSendQuery(con, "INSERT INTO t VALUES (1), (2), (3) RETURNING a")
    on.exit(dbClearResult(rs), add = TRUE, after = FALSE)
    expect_identical(dbGetRowsAffected(rs), 0L)
    # As if the statement had changed 2^31 - 1 rows
    result_set_rows_affected(rs@ptr, 2^31 - 1)
    expect_identical(dbGetRowsAffected(rs), .Machine$integer.max)
    expect_equal(nrow(dbFetch(rs)), 3L)
    expect_identical(dbGetRowsAffected(rs), 2^31 + 2)
    })
    With all four calls in SqliteResultImpl.cpp switched back to sqlite3_total_changes(), the hook test for dbGetRowsAffected() still passes, since the hook moves the start rather than SQLite's total (Confirmed); the gated test does fail on that mutant, with -2146435072L (Confirmed). SQLite has no way to raise a connection's total cheaply, so the hook test cannot do better. Suggested fix: say in the hook test's comment that it covers the R type and the 64-bit arithmetic only, and run the gated tests in a scheduled CI job so that they do not rot.

  3. dbGetRowsAffected() counts what the connection changed since the bind, not what the statement changed (pre-existing, unchanged here).

    // Before a bind, NA_INTEGER, which result_rows_affected() returns as NA
    int64_t SqliteResultImpl::n_rows_affected() {
    if (!ready_) {
    return NA_INTEGER;
    }
    return sqlite3_total_changes64(conn) - total_changes_start_;
    }
    An INSERT of one row into a table with a trigger that inserts one more row returns 2L from dbExecute() on both builds (Confirmed), as sqlite3_total_changes64() includes trigger and foreign-key changes, while DBI describes "the number of rows affected by the statement". This pull request only widens the type and should not change it. Suggested fix: a separate issue; summing sqlite3_changes64() after each SQLITE_DONE in step_done() would count the statement's own rows, also in 64 bits.

  4. The description's first account of the rows-affected overflow is narrower than the defect.

    group_ = 0;
    total_changes_start_ = sqlite3_total_changes64(conn);
    It says the count turned negative "once one execution of a statement changed more than INT_MAX rows", but the start is taken at dbBind(), so the sum over all parameter rows of one bind is what matters, as the gated test itself shows with 2^11 + 1 executions of 2^20 changes each (by reading, and Confirmed on main with -2146435072L). Suggested fix: write "once the changes since one dbBind() or dbExecute() passed INT_MAX".


Generated by Claude Code

…m 0 to 2^53

`result_set_rows_fetched()` and `result_set_rows_affected()` cast any double to `int64_t`,
which is undefined behavior for `NA`, `NaN`, infinite and out-of-range values.
Both now stop with "`n` must be a whole number from 0 to 2^53." unless the count fits.
The hook test of `dbGetRowsAffected()` now says that it covers the R type and the 64-bit arithmetic only:
the hook moves the start of the count, not SQLite's total of changes,
so that only the gated test catches a return to the 32-bit `sqlite3_total_changes()`.

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

Accepted limitations

The clean review found nothing above Low; it ran both gated tests (the rows-affected one in 2 min 21 s, the 2^31-row fetch in 9 min 34 s), which pass here and fail on main, and confirmed that the merge with #830 resolves by keeping both sides. Three of its Lows are fixed in 7ca358d: the test hooks reject anything but a whole number from 0 to 2^53, the hook test says that only the gated test catches a return to the 32-bit sqlite3_total_changes(), and the description says the count overflows when the changes since one bind, summed over its parameter rows, pass INT_MAX. These remain:

  • src/SqliteResultImpl.cpp#L120-L125: dbGetRowsAffected() counts every change on the connection since the bind, so the changes a trigger makes count too: a one-row INSERT whose trigger writes another row returns 2L, as on main. Relevance: low; reviewer's confidence: high.
  • tests/testthat/test-row-count.R: the two tests that cross INT_MAX for real take minutes and run only with RSQLITE_TEST_INT_MAX_ROWS=true, which no CI job sets; the hook tests cover the R type and the 64-bit arithmetic. Relevance: low; reviewer's confidence: high.
  • src/result.cpp#L83-L91: the internal test hooks crash when given a connection's pointer instead of a result's, like every other internal entry point that takes a result. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

@krlmlr
krlmlr merged commit bf95e2c into main Nov 13, 2026
8 checks passed
@krlmlr
krlmlr deleted the claude/row-count-64bit branch November 13, 2026 13:48
krlmlr pushed a commit that referenced this pull request Nov 13, 2026
The local counter of `fetch_rows()` was an `int`,
which a single fetch with `n = -1` could overflow
before `nrows_`, an `int64_t` since #858, takes its value.

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