Skip to content

fix: A fetch returns its rows when the step past its last row fails - #850

Draft
krlmlr wants to merge 11 commits into
mainfrom
claude/fetch-row-ahead
Draft

krlmlr wants to merge 11 commits into
mainfrom
claude/fetch-row-ahead

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Asked on #830: "Accuracy is important. Do we still need to fetch one row ahead? If yes, perhaps implement a transparent one-row cache in a fresh PR against main and stack this PR on top?" This is that pull request; #830 is stacked on it.

Why the fetch loop reads ahead. Sending or binding a query steps once, which runs the statement; after that, fetch_rows() reads the current row and then steps, so the statement always stands on the next row to return, and the last step of a fetch of n rows goes one row past the rows it returns. DBI and DBItest do not require this: has_completed_query_spec_partial leaves dbHasCompleted() unspecified after fetching exactly all rows, and a version that steps lazily passes DBItest (658 tests) and RSQLite's own suite unchanged. The read-ahead still buys two things. dbHasCompleted() is TRUE right after the fetch that returns the last row, so the vignette's while (!dbHasCompleted(rs)) dbFetch(rs, n = 10) over 30 rows fetches 10, 10, 10 rather than 10, 10, 10, 0. More importantly, the step that reaches the end finishes the statement, which releases its read lock: without it, a reader that fetched exactly all its rows keeps the lock until the next fetch or dbClearResult(), and a write from another connection fails with "database is locked". So the read-ahead stays.

What changes. When the step past the last row of a fetch fails, that fetch now returns all its rows, and the error is kept and raised by the next fetch; until then, dbHasCompleted() is FALSE. On main, the fetch that held row k - 1 raised the error of row k and those rows were lost, or, with several parameter sets, the error of a later set that fails to bind or to run was raised by the fetch that held the last row of the set before. dbFetch(n = 0) and dbColumnInfo() leave a kept error alone, and a new dbBind() drops it. The same holds for a value in a later parameter set that SQLite refuses to bind, which completes the result since #868: when the read-ahead keeps that refusal, dbHasCompleted() stays FALSE until the next fetch raises it, and only then is the result complete (kept_error_completes_), with the row count of the rows returned. An error among the rows a fetch asks for is still raised by that fetch: dbGetQuery() sends, fetches with n = -1 and clears, so holding that error back would silently return a result cut short. A failed step or an unbindable parameter now throws a C++ exception, step_error, that carries SQLite's message and result code, instead of calling cpp11::stop(), which signals the R error at once and so could not be held back; a kept error keeps both. The exception reaches R through cpp11's entry points, which turn it into the same R error as before, with the same message and condition call. An SQLite error message that contains %, such as the name of a CHECK constraint, is no longer read as a printf format, also when a statement fails to prepare; two warnings that quote the query still are, as on main. dbGetQuery(n = 4) over a result whose fifth row fails returns four rows, as LIMIT 4 would, and the kept error goes with the cleared result. What happens after the kept error is raised is #830's business.

Tests. tests/testthat/test-read-ahead.R, with its fixture in tests/testthat/helper-read-ahead.R so that every block runs on its own after load_all(): an SQLite message with % in it, through a fetch and through a kept error; dbGetQuery(n = ); a kept message that survives later failing statements on the connection; fetches of 1, 2 and 4 rows with row 5 failing; several parameter sets, including a third set that fails to bind; a value SQLite refuses to bind after a fetch, kept for the next fetch; the column structure staying available while an error is kept; a new bind dropping it; the statement finishing, and releasing its lock, after the last row; and an error among the asked-for rows. Eight of the ten blocks error on main (53f2693); the other two pin behavior main already has. devtools::test() and R CMD check --no-manual pass apart from the HTTP VFS errors that #832 is about, and the read-ahead and query tests run clean under AddressSanitizer and UBSan.

Merging into #795. #795 already throws from raise_sqlite_exception() so that the fetch loop can run inside an Arrow stream callback, which this pull request now matches. The resolution of a trial merge of this stack into #795 is in #830's description.

A clean review found one Medium finding, the error path running the opposite way to #795's, and three Low ones; all are fixed in 8be7cd8 except the retry on SQLITE_BUSY, which #848 tracks. A review of the fixes, with #830 on top, found nothing above Low for this pull request. A clean review of the merge of main with #868 found one Medium issue that main already has, now in #838, and three Low ones: the comment on step_error's result code is fixed in c029a2c, this description now covers the merge, and dbGetQuery(n = ) dropping a refused parameter set is up for a question. What remains is under Accepted limitations.

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


Generated by Claude Code

`dbFetch()` steps one row past the last row it returns, to tell whether the result is complete and to finish the statement as soon as it is.
When that step failed, the fetch raised the error and lost its rows, so the error of row k cost row k - 1 and every other row of that fetch.
Now that fetch returns its rows, and the next `dbFetch()` raises the error, with SQLite's message saved when the step failed.
This also holds when the step moves on to a later parameter set of `dbBind()` that fails to bind or to run.
Until the error is raised, `dbHasCompleted()` returns `FALSE`, and `dbFetch(n = 0)` and `dbColumnInfo()` leave it for the next fetch that reads rows.
A new `dbBind()` drops it.
An error among the rows a fetch asks for is still raised by that fetch, so that `dbGetQuery()` never returns a result cut short.
What happens after the error is raised is unchanged.

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: 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); the same holds for #830 on top of it. That is the runners' network, not this change, and there is no fix to port. The job will be re-run once the mirrors resolve again.


Generated by Claude Code

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 12b103a, by a Claude Code reviewer with clean context that read the description, the diff against main (3b7bea3), src/SqliteResultImpl.cpp and its header in full, the callers in src/DbResult.cpp and src/result.cpp, cpp11 0.5.5's stop(), warning() and END_CPP11, DBItest 1.8.3's has_completed_query_spec_partial, issue #848, and #795's head 43db19f where it touches the same code; built main, this pull request and the stack above it, plus an AddressSanitizer and UBSan build of this pull request; ran the new tests against this pull request and main, the full suite, R CMD check and scripted reproducers; tried a trial merge into #795; and posted nothing itself. Line numbers refer to 12b103a. "Confirmed" means reproduced by running code.

What was run

What holds

  • A fetch of n rows whose step n + 1 fails returns its rows, and the next fetch raises the error once, with SQLite's original message, even after another statement on the same connection has overwritten sqlite3_errmsg() (Confirmed).
  • In the grid, up to the first error, all 126 cases return the expected rows in order and raise once, from the fetch the design says; the only difference is that dbGetRowCount() still counts the rows of the failing fetch, as on main, which fix: Never restart a statement after an error in dbFetch() or dbBind() #830 fixes.
  • The error is kept across parameter sets, also across empty sets and when a later set fails to bind. While an error is kept, dbFetch(n = 0) and dbColumnInfo() leave it in place, dbHasCompleted() is FALSE, and dbGetRowCount() counts the rows returned. A new dbBind() drops it, also when the new bind fails at its first set, and dbClearResult() drops it without a message. n = -1 and dbGetQuery() still raise the error.
  • A fetch that reaches the end releases the read lock, for an exact n and with several parameter sets, and a kept error does not hold the lock either (Confirmed).
  • The default path behaves as on main, with timings within run-to-run noise (about ±10%).
  • step_error is thrown only in step_run() and bind_parameter_pos(), and is caught in step() or read_ahead() or leaves bind() as a std::runtime_error, which END_CPP11 turns into the same R error; messages and condition calls are identical to main. No C++ exception crosses R frames, and no raw longjmp is added.
  • AddressSanitizer and UBSan are clean on test-read-ahead.R, test-dbSendQuery.R, the grid and the probes.
  • Four of the six blocks error on main and the other two pass there, as the description says; every block passes on its own after load_all().

High

None.

Medium

1. The error path runs the opposite way to #795's, and the description gives no guidance for the merge. src/SqliteResultImpl.cpp#L363-L373, #L438-L440. #795 at 43db19f makes raise_sqlite_exception() throw std::runtime_error "so that the fetch loop can also run inside an Arrow stream callback" (#L689-L707); its fetch_arrow_rows() calls step() (#L524) on arrow's worker threads, and it reads the result code to report errors after dbDisconnect(). This pull request catches the step error in step() and turns it into an R error with cpp11::stop(). A trial merge into 43db19f conflicts in nine hunks of src/SqliteResultImpl.cpp and one of the header, including step(), step_run(), raise_sqlite_exception() and bind_parameter_pos(), which #795 moved into SqliteListParamSource, where it still calls cpp11::stop() (src/SqliteParamSource.cpp#L99-L105). Keeping this side of step() or of raise_sqlite_exception(const char*) calls R from a worker thread; keeping #795's parameter source as it is turns a later list set that fails to bind into an R error that read_ahead() does not catch, so the fetch loses its rows again and the third-set test in test-read-ahead.R fails; and #795's step_done() sets complete_ = true before it rethrows (#L434-L452), so dbHasCompleted() would be TRUE while an error is kept. Also, "Only the message is kept ... since nothing reads the code today" stops being true once #795 lands. By reading, with git merge-tree. Suggested fix: let step() and raise_kept_error() throw instead of calling cpp11::stop(); step_error already derives from std::runtime_error, and END_CPP11 turns it into the same R error, as it already does here for a first parameter set that fails to bind. That matches #795, removes two of the conflicts and fixes Low 2. Also give step_error the result code, and add a "Merging into #795" paragraph that covers the parameter source and step_done().

Low

1. SQLITE_BUSY at a parameter-set boundary (#848): row 2 is now returned, but a retry still reads a row that is not there, and the kept error lacks the code a retry would need. src/SqliteResultImpl.cpp#L380-L388. With #848's reprex, main returns 1, then "database is locked" twice while the writer waits, then NA, 3, 4; this pull request returns 1, then 2, then the error, then NA, 3, 4, with dbGetRowCount() at 5 for a four-row result; with #830 on top, 1, 2, the error, and then zero rows (Confirmed). Not a regression, since the retry was already wrong on main, and #848 tracks it. Suggested fix: keep SQLite's result code with the message (Medium 1 needs it too), so that #848 can leave the result incomplete on SQLITE_BUSY and repeat the read-ahead step on the next fetch instead of reading the current row; update #848 with what the stack does now.

2. A message with % is still used as a format string. src/SqliteResultImpl.cpp#L438-L440. With CREATE TABLE c (x INTEGER CONSTRAINT "positive %d%d%x" CHECK (x > 0)), inserting -1 fails with "CHECK constraint failed: positive 19188505920768a6b80" on main and "positive -2027539696083af4b80" here: cpp11::stop(message) reads arguments that were never passed, and a %s or %n could crash (Confirmed). Pre-existing and raised on #829, but this pull request rewrites the function and now also sends kept messages through it. Suggested fix: cpp11::stop("%s", message), or throw as in Medium 1.

3. dbGetQuery(n = ) now drops an error after its rows, and neither the description nor the tests say so. tests/testthat/test-read-ahead.R#L49-L72. On main, dbGetQuery(con, "SELECT id, json(v) AS j FROM t1", n = 4) over the six-row fixture raised "malformed JSON"; here it returns rows 1 to 4, and dbClearResult() drops the kept error without a word (Confirmed). That matches what LIMIT 4 would do, so it seems right, but the description's "dbGetQuery() sends, fetches with n = -1 and clears" reads as if dbGetQuery() always raised the error. Suggested fix: mention it in the description and pin it next to the dbGetQuery() expectation; in the same place, add a check that the kept message survives later failing statements on the connection, which the comment of read_ahead() promises and no test covers.


Generated by Claude Code

… intact

A failed step, a kept error and a statement that fails to prepare now throw a C++ exception, which cpp11 turns into an R error at the entry point, instead of calling `cpp11::stop()` where they happen.
The exception of a step carries SQLite's result code next to the message, and a kept error keeps both; a parameter that cannot be bound has `SQLITE_ERROR`.
An SQLite message that contains a `%`, for example from a constraint name, now reaches R as it is: before, it was used as a format string and printed garbage or could crash.
Otherwise the message, the class and the condition call (`NULL`) are the same as before.
A calling handler of such an error now runs once the C++ frames of the call have unwound, rather than while they are still running.
New tests pin that `dbGetQuery(n = )` drops an error after its rows, as `LIMIT` does, and that a kept error keeps its message after later statements on the connection fail.

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

Superseded: Accepted limitations

Superseded by the current copy.

The first clean review found one Medium and three Low issues, all fixed in 8be7cd8 apart from the retry below; the review of the fixes, run on the whole stack with #830 on top, found nothing above Low for this pull request, and its description's count of tests is corrected. These remain:


Generated by Claude Code

This was referenced Nov 12, 2026
Bring in #853 (gcc continuation lines in the generated `.dd` files)
and #869 (no query text or SQLite message as a `printf()` format, `fetch_blob()` guarded against `NULL`).

The conflict in `SqliteResultImpl::raise_sqlite_exception()` keeps this branch's
`throw std::runtime_error(sqlite3_errmsg(conn))`:
a failed prepare reaches R at cpp11's entry point like every other step error here,
and cpp11 passes the message through `"%s"`, so it is not a format string either.
The `.dd` files regenerated with the new `src/Makevars.deps` are unchanged.

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

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.

The first clean review found one Medium and three Low issues, all fixed in 8be7cd8 apart from the retry on SQLITE_BUSY below; the review of the fixes, run on the whole stack with #830 on top, found nothing above Low for this pull request, and its description's count of tests is corrected. The two warnings that still passed query text as a printf format are fixed on main by #869, which this branch has merged. No limitation introduced by this pull request remains; this one is older:


Generated by Claude Code

`raise_bind_exception()` from #868 throws a `step_error` with SQLite's result code
instead of calling `cpp11::stop()`,
so that `read_ahead()` keeps a value SQLite refuses to bind
like any other error of the step past the last row of a fetch.
The completion it sets is held back until the next fetch raises the kept error,
so that `dbHasCompleted()` stays `FALSE` until then.
A new `dbBind()` resets both the state #868 resets and the kept error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
A value SQLite refuses to bind carries SQLite's own code since the merge of #868,
such as `SQLITE_TOOBIG`;
only a parameter of a type that cannot be bound carries `SQLITE_ERROR`.

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

Question: Raise a refused parameter set from dbGetQuery(n = )?

Since the merge of main with #868, dbGetQuery(n = 1) silently drops a later parameter set that SQLite refuses to bind, where main raises the error. The fetch of n rows returns them, read_ahead() keeps the refusal for the next fetch (src/SqliteResultImpl.cpp#L415-L429), and dbGetQuery() clears the result without fetching again. This follows this pull request's rule that dbGetQuery(n = ) drops an error after its rows, as LIMIT does. But a value the user passed in params that can't be bound is an input error rather than a row past the limit, so one could argue it should still be raised.

library(DBI)
con <- dbConnect(RSQLite::SQLite())
# Lower SQLite's length limit to 30 bytes for this connection
RSQLite:::connection_limit_length(con@ptr, 30L)
x <- c("a", strrep("a", 31))
dbGetQuery(con, "SELECT :x AS x", params = list(x = x), n = 1)
#>   x
#> 1 a
# main (53f26934): Error: Can't bind parameter 1 (:x) in row 2: string or blob too big.
dbGetQuery(con, "SELECT :x AS x", params = list(x = x))
#> Error: Can't bind parameter 1 (:x) in row 2: string or blob too big.
dbDisconnect(con)
  • Accept it as the same rule as for an SQLite error after the requested rows, and pin it with a test (recommended)
  • Raise a kept bind refusal from dbGetQuery(n = ) before clearing the result, for example by checking kept_error_completes_ there, with a test
  • Bind all parameter sets up front, so that a refusal is raised before any row is returned

If nobody decides, the recommended option stands: the behavior stays as it is and is listed under Accepted limitations.


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The first clean review found one Medium and three Low issues, all fixed in 8be7cd8 apart from the retry on SQLITE_BUSY below; the review of the fixes, run on the whole stack with #830 on top, found nothing above Low for this pull request, and its description's count of tests is corrected. The two warnings that still passed query text as a printf format are fixed on main by #869, which this branch has merged. A clean review of the merge of main with #868 (9d1f216) found one Medium issue that main already has, now in #838, and three Low ones: the comment on step_error's result code is fixed in c029a2c, the description now covers the merge, and one remains:

  • dbGetQuery(n = ) drops a later parameter set that SQLite refuses to bind, where main raises it, as it drops an SQLite error after the requested rows (src/SqliteResultImpl.cpp#L415-L429, question). Relevance: Low; reviewer's confidence: confirmed by running code.

These are older:

  • SQLITE_BUSY from the step past a fetch is kept like any other error and raised by the next fetch instead of stepping again, so a retry does not recover; the result code a retry would need is now kept with the error. Tracked in A fetch that hits SQLITE_BUSY between parameter sets loses or corrupts rows on retry #848.
  • A parameter of a type RSQLite can't bind, in a later parameter set, lets a fetch after the error return a row with that parameter as NULL; it does not complete the result as a refusal by SQLite does. Tracked in #838.

Generated by Claude Code

@krlmlr krlmlr mentioned this pull request Nov 14, 2026
16 of 22 tasks

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