Skip to content

refactor: Own results through a shared pointer, as connections are - #856

Draft
krlmlr wants to merge 11 commits into
claude/arrow-param-sourcefrom
claude/arrow-result-ptr
Draft

krlmlr wants to merge 11 commits into
claude/arrow-param-sourcefrom
claude/arrow-result-ptr

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

This is the second pull request of the reworked Arrow stack, as planned in #829 (comment). The external pointer of a result now owns a DbResultPtr, a boost::shared_ptr<DbResult>, the way the external pointer of a connection owns a DbConnectionPtr. This lets a later pull request give an Arrow stream a share of the result, so that the stream can outlive dbClearResult(). Nothing changes in behavior or messages.

What changes

  • DbResult.h declares DbResultPtr next to DbConnectionPtr, and makes ~DbResult() virtual. The shared pointer is built from the DbResult* that create_and_send_query() returns, so it deletes the SqliteResult through a pointer to its base, as cpp11's deleter did before. That was undefined behavior on the base too, harmless only because SqliteResult has no members of its own. A virtual destructor is the smallest fix (one line), and it covers any later owner of a DbResultPtr, such as the Arrow stream, not just result_create(). Its cost is one vtable pointer per result.
  • result_create() wraps the new result in a DbResultPtr and returns an external pointer to it, as connection_connect() does with a DbConnectionPtr. result_release(), behind dbClearResult(), and cpp11's finalizer delete that DbResultPtr, which drops R's share of the result.
  • The as_cpp() specialisations for DbResult* and SqliteResult* in RSQLite_types.h read the DbResultPtr and return the result it points to. So the entry points that take a DbResult* or a SqliteResult* are unchanged. result_valid() and result_release(), including fix: Never restart a statement after an error in dbFetch() or dbBind() #830's busy guard, look through the shared pointer.
  • src/cpp11.cpp is regenerated for the new types of the three entry points.

What a reviewer may want to check

  • When a result is freed. R's share is the only one, so the result, with its statement and its share of the connection, is freed at the same moments as before: by dbClearResult(), or by the finalizer of a result that was never cleared. The finalizer of a cleared result finds the external pointer cleared and does nothing, as before. The "results in use" warning of dbDisconnect() counts the shares of the connection, and each result still holds one.
  • Empty shared pointers. as_cpp(), result_valid() and result_release() also check that the shared pointer is not empty, as feat: Implement the DBI Arrow interface natively #795 does. It never is, because create_and_send_query() throws instead of returning NULL, so these checks change nothing today.
  • The reference. This takes only the ownership change from feat: Implement the DBI Arrow interface natively #795 (43db19f): its RSQLite_types.h, and its result_create(), result_release() and result_valid() without the Arrow calls around them. feat: Implement the DBI Arrow interface natively #795 keeps the non-virtual destructor.

Left out

The second owner of a result, an Arrow stream that keeps it after dbClearResult() and dbDisconnect(), comes in pull request 10 of the plan. The thread-aware busy mark and the deferred release of results let go on other threads, which #795 adds for streams read by arrow's scanner, come in pull request 15. Everything else Arrow comes later too.

Tests

Six new tests in test-dbClearResult.R cover dbIsValid() before and after dbClearResult() and a second dbClearResult() with its warning. They pin the exact error of every use of a cleared result, through both as_cpp() specialisations. They also cover a result cleared when the next query is sent, a result collected by gc() without being cleared (the connection still runs queries and disconnects without the "results in use" warning), and the exact warning of dbDisconnect() with results in use, after which the result still fetches and clears. In that test, the last result holds a read lock on a database file after the disconnect, and a write from a second connection fails until gc() collects the result, so the test fails if the finalizer doesn't free a result after dbDisconnect(). The last test has a handler that catches the busy guard's error, after which the result is cleared normally. The tests pass on #855 (7387832 and c352631) and on this branch, and each test_that() block passes on its own after pkgload::load_all(). devtools::test() passes except for the three errors in test-httpvfs.R that main has as well (#832, #837).

A script of the finalizer cases lets the finalizer run after dbClearResult() and after dbDisconnect(), collects a connection before its uncleared result, and collects both together. Under valgrind's memcheck, the script, test-dbClearResult.R and test-dbSendQuery.R found no errors and no definite or indirect leaks. They ran before the destructor became virtual. With the virtual destructor, the script, test-dbClearResult.R, test-dbSendQuery.R, test-dbBind.R and test-read-ahead.R run without an AddressSanitizer report on an installed build, with the callr interrupt test included.

Stack

Based on #855 (claude/arrow-param-source), which is based on #830 and #850. The branch merges #855's latest head (c352631). Next in the new stack: vendoring nanoarrow.

Review

The clean review found nothing above Low; both points are fixed in d608525 and e5b871d. See the accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

The tests pin what a change of how results are owned must keep:
`dbIsValid()` before and after `dbClearResult()`, a second `dbClearResult()`,
the error of every use of a cleared result,
a result cleared when the next query is sent,
a result collected without being cleared,
the warning of `dbDisconnect()` with results in use,
and a handler that catches the busy guard's error and clears the result after its fetch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The external pointer of a result owns a `DbResultPtr`, a `boost::shared_ptr<DbResult>`,
as the external pointer of a connection owns a `DbConnectionPtr`.
`dbClearResult()` and the finalizer drop R's share.
It is the only share, so a result is freed exactly when it was before.
A later change lets an Arrow stream hold a share of its own,
so that the stream can outlive `dbClearResult()`.

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 2f319a7, by a Claude Code reviewer with clean context that read the description, the two commits 7387832..2f319a7, the code around them (result.cpp, DbResult.*, SqliteResult.*, RSQLite_types.h, connection.cpp, the R wrappers, cpp11's external_pointer) and #795's reference at 43db19f, then built this branch and its base #855 (7387832) into separate libraries, plain and with AddressSanitizer, and ran the tests, valgrind, mutants and its own reproducers against both. I posted nothing on GitHub myself.

What was run

  • R CMD INSTALL of both commits: no new compiler warnings, also with -Wall -Wextra on result.cpp and cpp11.cpp; cpp11::cpp_register() (cpp11 0.5.5) reproduces src/cpp11.cpp and R/cpp11.R byte for byte.
  • The new test-dbClearResult.R against both builds (8 tests, 38 expectations, no failure on either), and each of its eight test_that() blocks alone in a fresh R after pkgload::load_all() (all pass).
  • devtools::test() with NOT_CRAN=true on this branch: only the three known test-httpvfs.R errors.
  • A script of ten scenarios (clear then gc(), every entry point on a cleared result, the next query clearing a result, dbDisconnect() with two open results then fetch, connection collected before, after and together with an uncleared result, fix: Never restart a statement after an error in dbFetch() or dbBind() #830's busy guard from a warning handler, a serialized result, create/clear loops) on both builds, plain and under ASan with gctorture(TRUE).
  • valgrind memcheck of a second script (create/clear loops, 250 failing creates, the finalizer orders, objects left to the exit finalizers) on both builds.
  • Three mutants of this branch: no finalizer, dbClearResult() leaking (release() for reset()), busy guard removed, the last also built with ASan.
  • Timing of 20000 creates and clears, alternating builds.

What holds

  • No change of behavior: the scenario script prints identical output on both builds, plain and under ASan with gctorture(), with no ASan report.
  • Every entry point that takes a result fails on a cleared one exactly as before: the seven that go through the DbResult* and SqliteResult* specialisations of as_cpp() with simpleError "Invalid result set", result_valid() returns FALSE, a second result_release() is a silent no-op, dbGetInfo() and dbGetStatement() give "Expired, result set already closed", and NULL or a non-pointer give cpp11's same type errors.
  • Nothing is freed twice: result_release() goes through cpp11's r_deleter(), which clears the address before deleting the DbResultPtr, so the finalizer of a cleared result finds NULL; a serialized result with a NULL address behaves as before.
  • Finalizer order is safe either way: a result still fetches after its connection's external pointer is collected, and valgrind reports 0 errors and 0 bytes definitely or indirectly lost on both builds, including the failing creates, whose DbResultPtr storage the new expression frees.
  • fix: Never restart a statement after an error in dbFetch() or dbBind() #830's guard still works through the shared pointer: with it removed, ASan reports a heap-use-after-free in SqliteResultImpl::step_run() and the new handler test crashes.
  • The new tests are live: without the finalizer the "collected without being cleared" test fails, and with a leaking dbClearResult() that test and the disconnect test fail. The tests calling internal result_create() work under load_all() and test_check().
  • Speed is unchanged within noise: medians of 3.93 s (base) and 3.60 s (branch) for 20000 dbSendQuery() and dbClearResult(), and about 3 µs per internal create and release on both. The two extra small allocations per result do not show.
  • The description says what the code does, the scope matches the title, the code matches feat: Implement the DBI Arrow interface natively #795's RSQLite_types.h and result.cpp without the Arrow calls, and no src/*.dd file is touched or changed by a build.

High

None.

Medium

None.

Low

  1. Results are still deleted through DbResult*, whose destructor is not virtual, and the new shared pointer is where that could be fixed. src/result.cpp#L15-L16, src/SqliteResult.h#L14. SqliteResult::create_and_send_query() returns a DbResult*, so boost::shared_ptr<DbResult> binds checked_delete<DbResult>. Deleting the SqliteResult through it is undefined behavior by the standard, exactly as with the base's default_deleter<DbResult>, so this is not a regression (by reading). It is harmless today: sizeof(SqliteResult) == sizeof(DbResult) and DbResult is not polymorphic (Confirmed, by static_assert), and ASan's sized-delete check stays silent. But this owner type is the one later shared with Arrow streams, and a member added to SqliteResult would silently never be destroyed. Suggested fix: let create_and_send_query() return a SqliteResult* (or a DbResultPtr built from one), so the shared pointer captures the right deleter, or declare ~DbResult() virtual. The static_cast in as_cpp() stays valid either way.

  2. The closing expectation of the disconnect test cannot fail. tests/testthat/test-dbClearResult.R#L109-L111. With the finalizer disabled (external_pointer<DbResultPtr>(res, false)), this test still passes while the "collected without being cleared" test fails (Confirmed). con@ptr still holds the connection, so collecting ptr changes nothing that R can see, and the comment "The last result lets go of the connection when collected" claims more than is checked. Suggested fix: drop the two lines, or reword the comment to say only that collecting the last result does not warn; the earlier test already covers the finalizer.


Generated by Claude Code

A `DbResultPtr` is built from the `DbResult*` that `create_and_send_query()` returns,
so it deletes the `SqliteResult` through a pointer to its base,
as the external pointer did before.
A virtual destructor makes that deletion well-defined,
also for any later owner that holds a `DbResultPtr`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
…after `dbDisconnect()`

The disconnect test ended with a `gc()` that could not fail.
Its last result now holds a read lock on a database file,
which blocks a write from a second connection until the result is collected.

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

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.

The clean review found nothing above Low; ten lifetime scenarios gave identical results to #855's head, plain and under AddressSanitizer with gctorture(), and mutants without the finalizer, with a leaking clear, or without the busy guard each fail a test. Both Lows are fixed: ~DbResult() is virtual (d608525), so a result is deleted as the type it is, also by the later owners the stack adds, and the disconnect test now checks that collecting the last result releases its read lock after dbDisconnect() (e5b871d). #855's comment fix is merged in (f62b149). This remains:

  • tests/testthat/test-dbClearResult.R#L90-L121: the disconnect test observes the finalizer through "database is locked" from a second connection, which relies on the default rollback journal and on RSQLite setting no busy timeout by default; a change of either default needs the expectation adjusted. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: make the disconnect test independent of the journal mode and the busy timeout?

The new test "disconnecting with an open result warns, the result holds the connection" checks that the finalizer releases the last result after dbDisconnect() by writing from a second connection: the write fails with "database is locked" until gc() collects the result (tests/testthat/test-dbClearResult.R#L114-L120). That relies on SQLite's default rollback journal, since in WAL mode a reader doesn't block a writer, and on RSQLite setting no busy timeout by default, since with one the write waits instead of failing at once. If either default changes, the test fails and its expectation has to be adjusted.

  • Keep the test as it is: a change of either default makes it fail visibly, and it is adjusted then (recommended)
  • Set the journal mode and the busy timeout explicitly in the test, so that it doesn't depend on the defaults

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


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review found nothing above Low; ten lifetime scenarios gave identical results to #855's head, plain and under AddressSanitizer with gctorture(), and mutants without the finalizer, with a leaking clear, or without the busy guard each fail a test. Both Lows are fixed: ~DbResult() is virtual (d608525), so a result is deleted as the type it is, also by the later owners the stack adds, and the disconnect test now checks that collecting the last result releases its read lock after dbDisconnect() (e5b871d). #855's comment fix is merged in (f62b149). This remains:


Generated by Claude Code

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants