Skip to content

feat: Let Arrow streams outlive dbClearResult() and dbDisconnect() - #865

Draft
krlmlr wants to merge 11 commits into
claude/arrow-lazy-streamfrom
claude/arrow-stream-lifetime
Draft

krlmlr wants to merge 11 commits into
claude/arrow-lazy-streamfrom
claude/arrow-stream-lifetime

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Pull request 10 of the Arrow rework plan. It stacks on #864 (a result read as a lazy Arrow array stream), which stacks on #863, #862, #861, #860, #859, #857, #856, #855, #830 and #850.

What changes

A stream of the internal read_arrow_stream() now keeps working after dbClearResult() and dbDisconnect(), where #864 failed its next callback. These are the semantics that DBI's dbGetQueryArrow() needs, since it clears the result before the stream is consumed.

After dbClearResult(). The stream already holds a share of the result (#856, #864). dbClearResult() now only drops R's share, rather than freeing the statement under the stream: the statement lives as long as a stream shares the result, and is finalized when the last stream that reads it ends or is released, by release() or by R's garbage collector. A result without a stream is destroyed at once, as before. The stream keeps reading lazily, one chunk per get_next(), also while other statements run on the connection.

After dbDisconnect(). The connection counts the streams that read from it. While one does, dbDisconnect() marks the connection closed for R (dbIsValid() is FALSE, every later use fails as before) but leaves the SQLite handle open, with its busy handler; the last stream to end or be released then closes it with sqlite3_close_v2(), which completes once the statements are finalized. Without a stream, dbDisconnect() closes the handle at once, as before. Deferring the close, rather than reading through the zombie handle that sqlite3_close_v2() leaves, keeps the connection fully usable for the stream: its errors keep SQLite's message (the old stack had to fall back to sqlite3_errstr()), its virtual tables stay connected, and its R busy handler stays registered and is called as before. A result whose connection is already closed can't start a stream ("Can't read a result as an Arrow stream after its connection has been closed."), so a stream never reads through a zombie handle. read_arrow_stream() checks this before it claims the result for Arrow, so a failed call leaves dbFetch() usable.

The busy handler of a closed connection. Before every close, immediate or deferred, an R busy handler is now unregistered from SQLite (sqlite3_busy_handler(conn, NULL, NULL)) and only then released. An uncleared result can still step its statement through the zombie handle, with dbFetch() or dbBind(); until now SQLite could then call the released R closure ("attempt to apply non-function", or a crash), on #864 and on main after a plain dbDisconnect() with an open result as well. Such a step now fails at once with "database is locked". A busy timeout, set by sqliteSetBusyHandler() with an integer or by PRAGMA busy_timeout, calls no R code and stays, so such a step still waits for it, as on main.

Errors through a closed handle. sqlite3_errmsg() of a zombie handle only reports API misuse, so an error of a statement stepped after its connection was closed read "bad parameter or other API misuse" (also on main). Once the handle is closed, the error now carries SQLite's message for the step's result code (sqlite3_errstr()), such as "database is locked". While a stream keeps the handle open after dbDisconnect(), errors keep SQLite's full message.

Unchanged. dbIsValid() of the result and the connection, the warnings and errors of dbClearResult(), dbFetch() and dbDisconnect() on the default path, and #830's busy guard, which still makes dbClearResult() refuse while a fetch runs, also from a handler of a stream's own warning. The warning of dbDisconnect() about results in use counts them as before: a result cleared while a stream still reads it doesn't count (#864 got this by dropping the connection in clear(); now the connection counts such results). A result that R's garbage collector frees while a stream reads it doesn't count either, unlike on #864: the finalizer of the result's external pointer now marks it as dbClearResult() does. A stream still fails after dbBind(), whose types may differ from its schema. The release during a callback, the final failures and the mixed-fetch claim of #864 are untouched.

Lazy, not buffered. A stream reads its rows lazily after the clear, because buffering would hold the whole rest of the result in memory, which defeats a stream, and would have to read it eagerly inside dbClearResult(), where errors and coercion warnings would surface at the wrong call. The price: until the stream has ended or is released, it keeps its statement open, and with it a read transaction and the database file, also after dbDisconnect(). Meanwhile, on the same connection, DROP TABLE on a table it reads fails with "database table is locked", and on a file database another connection's writes fail with "database is locked"; a transaction left open at dbDisconnect() is rolled back only when the connection finally closes. This is what a pending statement means in SQLite, and the old stack documented the same.

Deliberately left out

  • Reading streams on worker threads: pull request 15. The last release() still destroys the result, and now possibly closes the connection, on the thread where it runs, which must be R's main thread.
  • dbSendQueryArrow(), dbFetchArrow(), dbFetchArrowChunk() and dbGetQueryArrow() through the stream, and user documentation of the lifetime: pull request 16.

Tests

tests/testthat/test-arrow-stream-lifetime.R, through nanoarrow:

  • clear then read, chunk by chunk, with another query on the connection between chunks; clear before any fetch
  • disconnect then read, with an open result (the warning as before) and with a cleared one (no warning)
  • a result of a closed connection can't start a stream, and stays usable with dbFetch()
  • rm() and gc() of the result and the connection while a stream lives, also of a connection never disconnected
  • a result freed by gc() while a stream reads it doesn't count as in use
  • a busy handler kept across dbDisconnect() while a stream lives and called through the deferred handle, then not called once the stream's release closed it; and not called after a plain dbDisconnect() with an open result, where the result fails with "database is locked" (on feat: Let Arrow streams outlive dbClearResult() and dbDisconnect() #865's first commit this test aborts R)
  • an integer busy timeout still applies to a result of a closed connection
  • options(warn = 2) and a release from a handler of the stream's own warning, after clear and disconnect
  • on a file database with a write transaction open at dbDisconnect(): three streams of one connection, one released before its end, one read to its end and then released, one freed by gc(); another connection stays locked out until the last of them, and then sees the transaction rolled back, so the connection was closed exactly then
  • a stream that ends lets the connection close before it is released
  • two streams of one connection, read interleaved, one released early

The two tests of test-arrow-stream.R that expected the failures are gone. Every new block fails on #864 and passes on its own after load_all(). devtools::test() with NOT_CRAN=true passes except the three known errors in test-httpvfs.R (#832, #837). A script of default-path behavior (fetch after disconnect, clearing twice, disconnecting twice, results freed) prints the same on #864 and here; the only intended changes on the default path are the busy handler and the error message through a closed handle above.

valgrind (--leak-check=full): no errors and nothing definitely lost for test-arrow-stream-lifetime.R, test-arrow-stream.R and test-dbClearResult.R, nor for the review's reproducers (busy handlers, lifetimes in every order of rm() and gc(), the claim, the default path), nor for reproducers that release a stream of a cleared result of a disconnected connection, with a custom busy handler, from a handler of its own warning during get_next() and convert_array_stream(), that leave a stream by options(warn = 2) and free it by gc(), and that release ten streams of one connection in random order, before and after their end.

https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn


Generated by Claude Code

A stream of `read_arrow_stream()` now reads on, lazily and chunk by chunk,
after its result is cleared or its connection is closed,
as `dbGetQueryArrow()` needs, since it clears the result
before the stream is consumed.
`dbClearResult()` drops only R's share of the result:
the statement lives as long as a stream shares it,
and is finalized when the last stream ends or is released.
`dbDisconnect()` defers closing the connection while a stream reads from it,
so the stream keeps a fully open handle with its busy handler,
and the connection is closed once the last stream has ended or is released.
A result whose connection is already closed can't start a stream.

`dbIsValid()`, the errors and warnings of `dbClearResult()`,
and the busy guard are unchanged.
The warning of `dbDisconnect()` about results in use counts them as before:
a cleared result that a stream still reads doesn't count.
A stream still fails after `dbBind()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn
@krlmlr
krlmlr added this pull request to stack #851 November 12, 2026 22:18
krlmlr and others added 2 commits November 12, 2026 22:24
The CI's auto-update regenerated `src/cpp11.dd` and `src/result.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 at 79efd5d
and keeps the auto-update's formatting of `src/result.cpp`.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 79efd5d, by a Claude Code reviewer with clean context that read the descriptions of #865 and #864, the diff against 075d214 with the code around it (DbConnection, DbResult, SqliteResultImpl, SqliteArrowStream.cpp, the R wrappers) and the tests, built the pull request and its base into separate libraries, plus an AddressSanitizer build of the head, and ran the tests and its own reproducers under ASan and valgrind. I posted nothing myself.

What was run

  • devtools::test() with NOT_CRAN=true on the head: only the three known test-httpvfs.R errors (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); DBItest passes.
  • Each of the eight blocks of test-arrow-stream-lifetime.R on its own after pkgload::load_all(): all pass on the head, all fail on 075d214.
  • A default-path script (fetch, dbIsValid(), dbGetRowCount(), dbColumnInfo() after disconnect, clearing and disconnecting twice, two open results, cleared results, GC of results and of the connection, a transaction open at disconnect with and without an open result, a busy handler): output identical on base and head.
  • A lifetime reproducer on a file database with a write transaction open: rm() + gc() of result, connection and stream in all six orders, with and without clear and disconnect (also never disconnected); ten streams of one connection, half cleared, some read to the end, released or GC'd in random order, 20 rounds; release from a handler of the stream's own coercion warning during get_next() and convert_array_stream() after clear, disconnect and rm(con), with a busy handler that calls gc(); options(warn = 2); an SQLite error after disconnect. Under ASan (vendored SQLite instrumented) and valgrind --leak-check=full: no errors, nothing definitely lost.
  • A busy-handler reproducer: the R handler, after rm(con) and gc(), is called four times on the deferred handle while a stream lives (via dbBind() on the uncleared result against another connection's exclusive lock), clean under ASan.
  • No src/*.dd, DESCRIPTION, NAMESPACE or man/ change, so no R CMD check.

What holds

  • Without a stream, dbClearResult() and dbDisconnect() behave as on the base, warnings included; n_cleared_results_ is balanced by ~DbResult().
  • The statement is finalized and the handle closed exactly once, when the last stream ends, is released or is GC'd: the other connection stays locked until exactly then and sees the transaction rolled back. A connection GC'd without dbDisconnect() closes through ~DbConnection() after remove_stream() has brought the count to zero.
  • drop_result() closes the handle while its own statement is still unfinalized, so the close always goes through the zombie path; the finalize that follows completes it. Neither the rollback nor the WAL close checkpoint calls the busy handler (sqlite3WalClose() passes no xBusy), and the return codes were ignored on the base too, so no error is lost that was reported before.
  • The stream reads after dbSendQuery() auto-clears its result ("Closing open result set"), keeps SQLite's error message after disconnect, and its locks behave as described (DROP TABLE and dbWriteTable(overwrite = TRUE) on the same connection fail with "database table is locked"; COMMIT with a pending cleared stream works).
  • The description matches the code and the scope matches the title.

High

None.

Medium

  1. The R busy handler is still released while SQLite can call it, when R keeps the result: the claim "its R busy handler isn't released while SQLite can still call it" holds only for cleared results.
    void DbConnection::disconnect() {
    if (n_streams_ > 0) {
    // The busy handler stays until the handle is closed
    pDeferred_ = pConn_;
    } else {
    // A zombie until the statements of open results are finalized
    sqlite3_close_v2(pConn_);
    release_callback_data();
    }
    pConn_ = NULL;
    }
    void DbConnection::add_stream() {
    ++n_streams_;
    }
    void DbConnection::remove_stream() {
    if (--n_streams_ == 0 && pDeferred_ != NULL) {
    sqlite3_close_v2(pDeferred_);
    pDeferred_ = NULL;
    release_callback_data();
    }
    }
    . When the last stream ends, remove_stream() calls sqlite3_close_v2(), which leaves a zombie while the uncleared R result holds its statement, and then release_callback_data(). dbBind() on that result still steps the statement through the zombie, and SQLite calls the released closure: with a handler made inline, dbBind() under another connection's exclusive lock fails with "attempt to apply non-function", i.e. R called a freed and reused object (Confirmed, busy2.R stream). The same happens on the base and on the default path after dbDisconnect() with an open result (Confirmed, busy2.R plain on 075d214), so this is pre-existing, but this pull request rewrites exactly this code and states the opposite. Suggested fix: release the callback only in ~DbConnection(), which runs after every result, and with it every statement, is gone, so the zombie has been freed; or unregister it with sqlite3_busy_handler(h, NULL, NULL) before sqlite3_close_v2(). Either fixes the default path too; narrow the sentence in the description otherwise.

Low

  1. The mixed-fetch claim is taken before the connection check, so a failed read_arrow_stream() blocks dbFetch() with a misleading message.

    RSQLite/R/arrow-stream.R

    Lines 18 to 19 in 79efd5d

    claim_fetch_kind(res, "an Arrow stream")
    result_create_arrow_stream(res@ptr, as.integer(n))
    and
    // The stream keeps a connection open, not one closed already
    if (!(*result)->connection_valid()) {
    cpp11::stop(
    "Can't read a result as an Arrow stream after its connection "
    "has been closed."
    );
    }
    . After dbDisconnect(), read_arrow_stream(res) fails at once, and dbFetch(res) then fails with "Can't fetch a result as a data frame after fetching it as an Arrow stream", although no stream exists; on feat: Read a result as a lazy Arrow array stream #864 the stream was created, so the claim was earned (Confirmed). Suggested fix: check connection_valid() (and n) before claim_fetch_kind(), e.g. a small C++ check called from R first, or claim inside result_create_arrow_stream() after its checks.

  2. A result freed by R's GC while a stream reads it still counts as "in use" for dbDisconnect(), unlike a cleared one.

    DbConnectionPtr* con = con_.get();
    // Each result holds a share of the connection,
    // also one cleared while an Arrow stream reads it
    long n = con_->use_count() - (*con)->n_cleared_results();
    if (n > 1) {
    Rf_warning(
    "There are %ld result in use. The connection will be released when they "
    "are closed",
    n - 1
    );
    . The finalizer drops R's share without clear(), so dbDisconnect() warns "There are 1 result in use" when the user holds no result (Confirmed, same on feat: Read a result as a lazy Arrow array stream #864). Suggested fix: have the result finalizer call clear() (which now only marks), or count results with a stream rather than cleared ones; or state the exception.

  3. Test gaps for paths the description relies on.

    # An Arrow stream of read_arrow_stream() reads on
    # after dbClearResult() and dbDisconnect(),
    # and keeps the statement and the connection until it no longer needs them.
    test_that("a stream reads on lazily after its result is cleared", {
    skip_if_not_installed("nanoarrow")
    con <- local_con()
    dbWriteTable(con, "t", data.frame(a = 1:5))
    res <- dbSendQuery(con, "SELECT a FROM t")
    stream <- read_arrow_stream(res, 2)
    expect_equal(stream$get_next()$length, 2)
    dbClearResult(res)
    expect_false(dbIsValid(res))
    expect_warning(dbClearResult(res), "already closed")
    expect_error(dbFetch(res), "Invalid result set")
    # Chunk by chunk, also while other statements run on the connection
    expect_equal(nanoarrow::convert_array(stream$get_next())$a, 3:4)
    expect_equal(dbGetQuery(con, "SELECT count(*) AS n FROM t")$n, 5)
    expect_equal(nanoarrow::convert_array(stream$get_next())$a, 5L)
    expect_null(stream$get_next())
    expect_equal(stream$get_schema()$children$a$format, "l")
    })
    test_that("a stream of a result cleared before any fetch reads all rows", {
    skip_if_not_installed("nanoarrow")
    con <- local_con()
    res <- dbSendQuery(con, "SELECT 1 AS x UNION ALL SELECT 2.5")
    stream <- read_arrow_stream(res)
    dbClearResult(res)
    expect_equal(nanoarrow::convert_array_stream(stream)$x, c(1, 2.5))
    })
    test_that("a stream reads on after its connection is closed", {
    skip_if_not_installed("nanoarrow")
    # The result is still open, and dbDisconnect() warns as before
    con <- dbConnect(SQLite(), ":memory:")
    res <- dbSendQuery(con, "SELECT 1 AS x UNION ALL SELECT 2")
    stream <- read_arrow_stream(res, 1)
    expect_equal(stream$get_next()$length, 1)
    expect_warning(dbDisconnect(con), "1 result in use")
    expect_false(dbIsValid(con))
    expect_equal(nanoarrow::convert_array(stream$get_next())$x, 2)
    expect_null(stream$get_next())
    dbClearResult(res)
    # A cleared result doesn't count as in use
    con <- dbConnect(SQLite(), ":memory:")
    res <- dbSendQuery(con, "SELECT 1 AS x UNION ALL SELECT 2")
    stream <- read_arrow_stream(res, 1)
    dbClearResult(res)
    expect_no_warning(dbDisconnect(con))
    expect_warning(dbDisconnect(con), "Already disconnected")
    expect_equal(nanoarrow::convert_array_stream(stream)$x, c(1, 2))
    })
    test_that("a result of a closed connection can't start a stream", {
    skip_if_not_installed("nanoarrow")
    con <- dbConnect(SQLite(), ":memory:")
    res <- dbSendQuery(con, "SELECT 1 AS x")
    suppressWarnings(dbDisconnect(con))
    expect_error(
    read_arrow_stream(res),
    "after its connection has been closed"
    )
    dbClearResult(res)
    })
    test_that("a stream reads on after R frees its result and connection", {
    skip_if_not_installed("nanoarrow")
    con <- dbConnect(SQLite(), ":memory:")
    dbWriteTable(con, "t", data.frame(a = 1:3))
    res <- dbSendQuery(con, "SELECT a FROM t")
    stream <- read_arrow_stream(res, 2)
    expect_equal(stream$get_next()$length, 2)
    # Not cleared, and the R object of the connection goes too
    expect_warning(dbDisconnect(con), "1 result in use")
    rm(res, con)
    gc()
    expect_equal(nanoarrow::convert_array(stream$get_next())$a, 3L)
    expect_null(stream$get_next())
    })
    test_that("the last stream to end or be released closes the statements and the connection", {
    skip_if_not_installed("nanoarrow")
    path <- withr::local_tempfile(fileext = ".sqlite")
    con <- dbConnect(SQLite(), path)
    dbWriteTable(con, "t", data.frame(a = 1:3))
    other <- dbConnect(SQLite(), path)
    withr::defer(dbDisconnect(other))
    insert <- function() {
    tryCatch(
    dbExecute(other, "INSERT INTO t VALUES (4)"),
    error = function(e) conditionMessage(e)
    )
    }
    # The connection holds a write transaction until it is closed
    dbBegin(con)
    dbExecute(con, "INSERT INTO t VALUES (10)")
    res <- dbSendQuery(con, "SELECT a FROM t")
    first <- read_arrow_stream(res, 1)
    expect_equal(first$get_next()$length, 1)
    dbClearResult(res)
    res <- dbSendQuery(con, "SELECT a FROM t")
    second <- read_arrow_stream(res, 1)
    dbClearResult(res)
    res <- dbSendQuery(con, "SELECT a FROM t")
    third <- read_arrow_stream(res, 1)
    dbClearResult(res)
    expect_no_warning(dbDisconnect(con))
    expect_equal(insert(), "database is locked")
    # Released before it has ended
    first$release()
    expect_equal(insert(), "database is locked")
    # Ended, then released
    expect_equal(nanoarrow::convert_array_stream(second)$a, c(1:3, 10L))
    expect_equal(insert(), "database is locked")
    second$release()
    expect_equal(insert(), "database is locked")
    # Freed by R's garbage collector
    expect_equal(third$get_next()$length, 1)
    rm(third)
    gc()
    # The close has rolled back the transaction
    expect_equal(insert(), 1)
    expect_equal(dbGetQuery(other, "SELECT a FROM t")$a, 1:4)
    })
    test_that("a stream that has ended lets the connection close", {
    skip_if_not_installed("nanoarrow")
    path <- withr::local_tempfile(fileext = ".sqlite")
    con <- dbConnect(SQLite(), path)
    dbWriteTable(con, "t", data.frame(a = 1:3))
    other <- dbConnect(SQLite(), path)
    withr::defer(dbDisconnect(other))
    dbBegin(con)
    dbExecute(con, "INSERT INTO t VALUES (10)")
    res <- dbSendQuery(con, "SELECT a FROM t")
    stream <- read_arrow_stream(res, 2)
    dbClearResult(res)
    dbDisconnect(con)
    expect_error(dbExecute(other, "INSERT INTO t VALUES (4)"), "locked")
    expect_equal(nanoarrow::convert_array_stream(stream)$a, c(1:3, 10L))
    # Before the stream is released
    expect_equal(dbExecute(other, "INSERT INTO t VALUES (4)"), 1)
    stream$release()
    expect_equal(dbGetQuery(other, "SELECT a FROM t")$a, 1:4)
    })
    test_that("streams of several results of one connection read independently", {
    skip_if_not_installed("nanoarrow")
    con <- dbConnect(SQLite(), ":memory:")
    dbWriteTable(con, "t", data.frame(a = 1:4))
    res <- dbSendQuery(con, "SELECT a FROM t")
    ones <- read_arrow_stream(res, 1)
    dbClearResult(res)
    res <- dbSendQuery(con, "SELECT a * 10 AS b FROM t")
    twos <- read_arrow_stream(res, 2)
    dbClearResult(res)
    dbDisconnect(con)
    expect_equal(nanoarrow::convert_array(ones$get_next())$a, 1L)
    expect_equal(nanoarrow::convert_array(twos$get_next())$b, c(10L, 20L))
    ones$release()
    expect_equal(nanoarrow::convert_array(twos$get_next())$b, c(30L, 40L))
    expect_null(twos$get_next())
    })
    . No test keeps a busy handler across disconnect and calls it, reads after GC of a connection that was never disconnected, or uses options(warn = 2) / a handler release after clear and disconnect; all pass in my reproducers (Confirmed), so they would be cheap regressions to add. Suggested fix: add the busy-handler case (dbBind() on the uncleared result against an exclusive lock) and the never-disconnected GC case.


Generated by Claude Code

…im no stream on a closed one

A connection closed by `dbDisconnect()`, or by the last Arrow stream
that reads it, can stay a zombie while an open result holds a statement.
SQLite could then call the R busy handler after it had been released,
as when `dbBind()` on such a result met a lock:
the handler is now unregistered from SQLite before the handle is closed,
and the result fails at once instead.
This also holds without streams.

`read_arrow_stream()` checks the connection before it claims the result,
so that a failed call leaves `dbFetch()` usable.

A result that R's garbage collector frees while a stream reads it
no longer counts as in use for `dbDisconnect()`, as a cleared one:
its finalizer now marks it as `dbClearResult()` does.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Second review round of this pull request, of e8d0917, by a Claude Code reviewer with clean context that read the description, the diff against bb119a5 with the code around it (DbConnection, DbResult, SqliteResultImpl, connection.cpp, cpp11's external_pointer, the R wrappers) and the new tests, built e8d0917, bb119a5 and main into separate libraries plus an AddressSanitizer build of e8d0917 (vendored SQLite instrumented), and ran the tests and its own reproducers. I read the first round's findings only to know what the commit fixes. I posted nothing myself.

What was run

  • devtools::test() with NOT_CRAN=true on e8d0917: 0 failures, only the three known test-httpvfs.R errors (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); DBItest passes.
  • Each of the 13 blocks of test-arrow-stream-lifetime.R on its own after pkgload::load_all(): all pass on e8d0917. On bb119a5, the four blocks that target this commit's fixes fail (closed-connection claim, GC'd result in use, both busy-handler blocks); the two coverage blocks asked for by the first round pass there too, as expected.
  • Under ASan: test-arrow-stream-lifetime.R, test-arrow-stream.R, test-dbClearResult.R, test-dbConnect.R, test-DBItest.R, the first round's reproducers (life.R, misc.R, busy2.R) and two new ones: final.R (GC of an uncleared or cleared result, with and without a stream, connection disconnected before, after or never, freed first, second or last, 36 cases; clearing twice; clearing after GC of the connection; GC of a result from a handler of its own stream's warning; results, streams and connections left alive at R exit) and default.R (an open result stepped after dbDisconnect() under another connection's lock, with no handler, an integer timeout, PRAGMA busy_timeout and an R handler, on main, bb119a5 and e8d0917). No ASan report.
  • valgrind --leak-check=full on the three test files, final.R and default.R: no memory errors, nothing definitely lost; final.R shows 3 "possibly lost" SQLite blocks from the streams deliberately left alive at exit, whose nanoarrow finalizers don't run at exit.
  • No change to src/*.dd, DESCRIPTION, NAMESPACE or man/, so no R CMD check.

What holds

  • close_handle() runs on every close path in the right order: unregister, release, sqlite3_close_v2(). ~DbConnection() only reaches it through disconnect() once every result, and with it every stream, is gone, so pDeferred_ is always NULL there. busy2.R (an inline handler reclaimed after dbDisconnect() with an open result) gives "attempt to apply non-function" on bb119a5 and a plain SQLite error on e8d0917, with and without a stream.
  • The result finalizer and dbClearResult() don't free twice: cpp11's reset() clears the address of the R-visible external pointer before it deletes, so the finalizer later sees NULL; clear() is balanced by ~DbResult(). Results hold the connection's shared_ptr, so finalizer order at gc() and at exit doesn't matter (ASan-clean in all 36 orders and at exit). A failed create_and_send_query() leaves a NULL address, which the finalizer skips.
  • A result freed by GC while a stream reads it no longer counts as in use; one freed before dbDisconnect() without a stream is gone, so no warning either, as before.
  • connection_valid() before claim_fetch_kind() leaves dbFetch() usable after a failed read_arrow_stream() (Confirmed); the C++ check in result_create_arrow_stream() stays as a backstop.
  • The SQLite message on a closed connection: with no busy handler, main already gives "bad parameter or other API misuse" when a step on such a result meets a lock, and a fetch without contention still works on all three. DBItest has no expectation on results of closed connections beyond the warning of dbDisconnect(). So the message isn't a regression, see Low 2.
  • The test that builds a connection with new() is sound: the slots match setClass("SQLiteConnection") and connection_connect()'s signature, and it avoids dbConnect()'s warning_once() finalizer, which would make the block depend on test order.

High

None.

Medium

None.

Low

  1. Closing now also drops a busy timeout, not only the R handler, so a result of a closed connection no longer waits for a lock.

    void DbConnection::close_handle(sqlite3* conn) {
    // The statements of open results can still step the handle,
    // which stays a zombie until they are finalized:
    // they get SQLITE_BUSY at once rather than call the released R handler
    sqlite3_busy_handler(conn, NULL, NULL);
    release_callback_data();
    sqlite3_close_v2(conn);
    }
    . sqlite3_busy_handler(conn, NULL, NULL) also removes the timeout set by sqliteSetBusyHandler(con, 1000L) or PRAGMA busy_timeout, which call no R code. With an open result after dbDisconnect() and another connection holding a lock, dbBind() waits 1 s on main and bb119a5 and fails at once on e8d0917 (Confirmed, default.R). This is an edge case of the default path that the description doesn't mention ("the only intended change on the default path is the busy handler"). Suggested fix: unregister only when an R function is installed (busy_callback_ && !Rf_isInteger(busy_callback_)), or state in the description that timeouts are dropped as well.

  2. A step that hits a lock through the zombie handle reports "bad parameter or other API misuse", which hides the cause.

    throw step_error(sqlite3_errmsg(conn), rc);
    . sqlite3_errmsg() on a zombie handle always returns the misuse text, while rc is SQLITE_BUSY (Confirmed, default.R; identical on main without a handler, so pre-existing). Now that every handler's user ends up there, the message matters a bit more. Suggested fix: when the connection is no longer valid, build the message from sqlite3_errstr(rc) ("database is locked"), perhaps with "after its connection has been closed". A blanket RSQLite error for any use of such a result would break fetching without contention, which works on main, so I'd keep that path.

  3. The default-path busy-handler test can pass on the bug it guards against.

    expect_error(dbBind(res, list(1)), info = with_stream)
    expect_equal(calls, 0L, info = with_stream)
    . expect_error() has no pattern, and when the released wrapper closure has been reclaimed, the old code fails with "attempt to apply non-function" without incrementing calls, so both expectations hold (by reading; busy2.R shows that error on bb119a5). The test failed on bb119a5 in my run only because the closure was still alive. Suggested fix: pin the message, e.g. expect_error(..., "misuse|locked"), as the stream block above it does with "locked".


Generated by Claude Code

…ult code of its errors

Closing a connection unregisters the busy handler only when it is an R function,
so a busy timeout set by `sqliteSetBusyHandler()` with an integer
or by `PRAGMA busy_timeout` keeps working for the statements of open results,
as before.
An error of such a statement, whose handle has been closed,
reports SQLite's message for its result code, such as "database is locked",
since `sqlite3_errmsg()` of a closed handle only reports API misuse.

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

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by this newer copy.

Two clean review rounds: the first of the whole pull request at 79efd5d, the second of e8d0917. The first found that the R busy handler could be released while SQLite could still call it (also on main, after dbDisconnect() with an open result), and three Lows; e8d0917 fixes all four, also on the default path. The second found nothing above Low; its three Lows are fixed in 049716e: an integer busy timeout or PRAGMA busy_timeout stays in force on a closed connection's handle as on main, a lock met through a closed handle reports "database is locked", and the busy-handler tests pin their messages. Without a stream, behavior matches the base and DBItest passes; AddressSanitizer and valgrind found nothing in either round. These remain:

  • src/DbConnection.cpp#L99-L121: while a stream reads after dbDisconnect(), the connection keeps its SQLite handle, its read transaction and the database file: DROP TABLE on the same connection reports "table is locked", other connections' writes report "database is locked", and a transaction left open at disconnect is rolled back only when the last stream ends, is released or is garbage-collected. The description documents it. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L22: the final close and the release of the R busy handler can now run inside a stream's release(), also from a GC finalizer or a callback's cleanup; they must stay on R's main thread, which pull request 15 has to keep. Relevance: medium; reviewer's confidence: high (recorded).
  • A fetch or bind on an uncleared result of a closed connection still works without lock contention, as on main, and fails with SQLite's message on a lock; no RSQLite-specific "connection closed" error comes first, since that would break the working case. Relevance: low; reviewer's confidence: high.
  • The last round of fixes (049716e) was not run under valgrind or AddressSanitizer; it adds a condition and picks another message string, and the lifetime tests and devtools::test() pass. Relevance: low; reviewer's confidence: medium.

Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: buffer the rest of a result when its Arrow stream outlives dbClearResult() or dbDisconnect(), so that the stream no longer holds the database?

A stream of read_arrow_stream() reads its result lazily after dbClearResult() and dbDisconnect(), and the connection defers closing its SQLite handle until the last stream has ended or is released (src/DbConnection.cpp#L90-L95). Until then the stream keeps its statement open, and with it a read transaction on the database: on the same connection, DROP TABLE of a table it reads fails with "database table is locked", other connections' writes to a file database fail with "database is locked", and a transaction left open at dbDisconnect() is rolled back only when the last stream ends. This is what a pending statement means in SQLite, and the description of this pull request documents it. Run on a build of #867's head (d63d63d), the top of the stack, which leaves this path as it is here:

library(DBI)
library(nanoarrow)
path <- tempfile(fileext = ".sqlite")
con <- dbConnect(RSQLite::SQLite(), path)
dbWriteTable(con, "t", data.frame(a = 1:3))

res <- dbSendQuery(con, "SELECT * FROM t")
stream <- RSQLite:::read_arrow_stream(res, n = 1)
stream$get_next()$length
#> [1] 1
dbClearResult(res)

# Fails while the stream reads: database table is locked
dbExecute(con, "DROP TABLE t")
#> Error:
#> ! database table is locked
dbDisconnect(con)

# Fails while the stream reads: database is locked
other <- dbConnect(RSQLite::SQLite(), path)
dbExecute(other, "INSERT INTO t VALUES (4)")
#> Error:
#> ! database is locked

# Works once the stream is released
stream$release()
dbExecute(other, "INSERT INTO t VALUES (4)")
#> [1] 1
dbDisconnect(other)

Created on 2026-11-13 with reprex v2.1.1

  • Keep reading lazily and accept the locks (recommended): buffering would hold the whole rest of the result in memory, which defeats a stream, and would read it inside dbClearResult() or dbDisconnect(), where errors and coercion warnings would surface at the wrong call
  • Buffer the remaining rows at dbClearResult() and dbDisconnect(), so that the statement is finalized and the connection closed at once

If nobody decides, streams keep reading lazily, and the limitation stays accepted in this pull request's "Accepted limitations" comment.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: make the final close of a statement and a connection safe off R's main thread now, rather than in pull request 15?

With this pull request, the last release() of a stream finalizes the result's statement and, after dbDisconnect(), closes the SQLite handle and releases the connection's R busy handler (src/SqliteArrowStream.cpp#L18-L19). That release can also come from R's garbage collector or from a callback's cleanup, and releasing an R object must happen on R's main thread. Today it does, since every callback of the stream runs there (src/SqliteArrowStream.cpp#L22-L23). Pull request 15 of the Arrow rework plan reads streams on worker threads, as arrow's scanner and Acero do, and must then keep the final release on R's main thread or hand it over (see the stream-read question). No reproducer: nothing reads a stream on another thread before pull request 15.

  • Leave it to pull request 15, which keeps or hands the final release to R's main thread (recommended): no caller can release a stream off the main thread before it
  • Defer the final close to R's main thread here already, for example through a queue that the next call into RSQLite drains

If nobody decides, the final close runs where release() is called, and pull request 15 has to handle it.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the copy of 2026-11-29.

Two clean review rounds: the first of the whole pull request at 79efd5d, the second of e8d0917. The first found that the R busy handler could be released while SQLite could still call it (also on main, after dbDisconnect() with an open result), and three Lows; e8d0917 fixes all four, also on the default path. The second found nothing above Low; its three Lows are fixed in 049716e: an integer busy timeout or PRAGMA busy_timeout stays in force on a closed connection's handle as on main, a lock met through a closed handle reports "database is locked", and the busy-handler tests pin their messages. Without a stream, behavior matches the base and DBItest passes; AddressSanitizer and valgrind found nothing in either round. Since then, the branch has only merged its base (3d13999). These remain:

  • src/DbConnection.cpp#L90-L95: while a stream reads after dbClearResult() or dbDisconnect(), it holds its statement, a read transaction and the connection's handle, so the database stays locked for writes until the stream ends or is released (question). Relevance: medium; reviewer's confidence: high.
  • src/SqliteArrowStream.cpp#L18-L23: the last release() of a stream finalizes the statement and may close the connection, which must stay on R's main thread when pull request 15 reads streams on worker threads (question). Relevance: medium; reviewer's confidence: high (recorded).

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: keep a PRAGMA busy_timeout when the connection closes after an R busy handler?

The clean review of 2026-11-29 rated this Low, from the code; this session did not run it. When a connection's busy handler is an R function, close_handle() removes it with sqlite3_busy_handler(conn, NULL, NULL) so that statements of results left open after dbDisconnect() never call into released R code (src/DbConnection.cpp#L109-L119). The comment says "A busy timeout calls no R code and stays." But if a PRAGMA busy_timeout was set after the R handler, SQLite's sqlite3_busy_handler() also sets the connection's timeout to 0, so such a result gets "database is locked" at once instead of waiting, which on main it does.

Reading the timeout before removing the handler (sqlite3_busy_timeout() has no getter, but PRAGMA busy_timeout returns it) and setting it again afterwards keeps it, about five lines and a test with two connections and a lock. Whether a timeout set after an R handler should outlive it at all is the narrower part: SQLite itself treats the two as one setting, where the last call wins.

  • Restore a timeout set after the R handler once the handler is removed, and fix the comment (recommended: the result waits as it did on main)
  • Keep the behavior and correct the comment: closing removes an R busy handler together with any timeout set after it
  • Accept it as a limitation of this pull request

The change was not written in this session, whose harness refused to start an agent for fixes. Kirill decides. If nobody decides, it is accepted as a limitation and the comment stays as it is.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Two clean review rounds: the first of the whole pull request at 79efd5d, the second of e8d0917. The first found that the R busy handler could be released while SQLite could still call it (also on main, after dbDisconnect() with an open result), and three Lows; e8d0917 fixes all four, also on the default path. The second found nothing above Low; its three Lows are fixed in 049716e: an integer busy timeout or PRAGMA busy_timeout stays in force on a closed connection's handle as on main, a lock met through a closed handle reports "database is locked", and the busy-handler tests pin their messages. Without a stream, behavior matches the base and DBItest passes; AddressSanitizer and valgrind found nothing in either round. Since then, the branch has only merged its base (3d13999).

The clean review of 2026-11-29, after main (3.54.1) was merged up the stack, read this pull request at e3c4e08 and found nothing above Low here; one new Low is listed below. From #830 up, five expectations in test-dbBind.R from #868 fail until the question on the state after a failed dbBind() is answered. This copy replaces the copy of 2026-11-13. These remain:

  • src/DbConnection.cpp#L90-L95: while a stream reads after dbClearResult() or dbDisconnect(), it holds its statement, a read transaction and the connection's handle, so the database stays locked for writes until the stream ends or is released (question). Relevance: medium; reviewer's confidence: high.
  • src/SqliteArrowStream.cpp#L18-L23: the last release() of a stream finalizes the statement and may close the connection, which must stay on R's main thread when pull request 15 reads streams on worker threads (question). Relevance: medium; reviewer's confidence: high (recorded).
  • src/DbConnection.cpp#L109-L119: closing a connection whose busy handler was an R function also drops a PRAGMA busy_timeout set after it, so a result left open gets "database is locked" at once (question). Relevance: low; reviewer's confidence: medium, from the code.

Generated by Claude Code

…time

The stream claims its result in C++ after the check of the connection,
so a call refused for a closed connection claims nothing without a check in R.

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

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