Skip to content

feat: Read Arrow streams on worker threads - #978

Draft
krlmlr wants to merge 12 commits into
claude/rb-stack-review-readfrom
claude/rb-arrow-stream-thread
Draft

krlmlr wants to merge 12 commits into
claude/rb-stack-review-readfrom
claude/rb-arrow-stream-thread

Conversation

@krlmlr

@krlmlr krlmlr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

For users: a condition that leaves the busy handler of sqliteSetBusyHandler() by a jump (such as a message() caught by a tryCatch() further out), and the error of a handler value that isn't a single number, now reach R once SQLite's call has returned, instead of jumping through SQLite's C code (#941, NEWS). Otherwise no change of behavior yet: the Arrow stream of read_arrow_stream() is internal, and no DBI method returns it.

Another thread may now read an Arrow stream of a result, as arrow's scanner and Acero do while R goes on (plan item 15). Before, the stream's callbacks called R (warnings, interrupt checks, cpp11::unwind_protect(), the R busy handler, R parameter vectors) and would have crashed R on a worker thread. R_init_RSQLite() records R's main thread through a [[cpp11::init]] function. On any other thread, the read calls no R:

  • The fetch runs without cpp11::unwind_protect(), interrupts aren't checked, an R busy handler gives up at once (the step fails with SQLITE_BUSY), and check_ready() and the inactive-result check throw C++ exceptions instead of cpp11::stop().
  • Parameters bound from an Arrow stream: creating the Arrow stream over the result reads the rest of the parameter stream to its end on R's main thread and holds its arrays in memory. A worker then binds every set without R, and a failure of the parameter stream comes when its array would have been read.
  • Limitation: multi-set dbBind() parameters are R vectors, so a worker doesn't bind the next set. The chunk ends with the rows read before, and the worker's next call fails with EBUSY ("Can't bind the next parameter set on a thread other than R's main thread. R's main thread can read on."). This is not final: the next fetch on R's main thread binds the set and reads on. A consumer such as arrow or Acero treats any non-zero code as fatal, so such results must be read on R's main thread. Single-set binds aren't affected.
  • The R busy handler runs under R_UnwindProtect() with its own continuation, so nothing leaves SQLite's busy callback by a jump. On a jump, the callback returns 0 to SQLite, and continue_busy_unwind() continues the jump once sqlite3_step(), sqlite3_prepare_v2(), the backup step or the CSV import has returned and the connection's mutex is free. Before, a jump left SQLite's recursive mutex held by R's main thread, and a worker read on that connection then waited for good. The same path covers a handler value that isn't a single number or logical. The pending jump can't leak: the CSV import returns at once instead of raising an R error when a jump waits (src/import-file.c), and its caller continues it. sqlite3_load_extension() continues one too. Every SQLite call that can run the busy handler first fails with an internal error if a jump was left pending, so a pending jump is never continued in an unrelated call. dbWriteTable() from a file now rolls back with ROLLBACK when its savepoint started the transaction: ROLLBACK TO + RELEASE need a lock that another connection may hold, and left the transaction open, even without a jump.
  • Warnings rule: the warnings about values that the column types changed (feat: Warn when an Arrow fetch converts or drops a value #961) are kept with the result and raised later on R's main thread, as plain warnings. They come with the stream's next chunk read on the main thread, or before R's next call on the result (dbFetch(), dbBind(), dbHasCompleted(), dbGetRowCount(), dbGetRowsAffected(), dbColumnInfo(), dbClearResult(), read_arrow_stream(), fetch_arrow_chunk_warn()). They are raised by flush_thread_warnings() in R before the call takes the result's pointer, so a handler may clear the result and the call then finds it cleared. A warning made an error doesn't raise them again. They are lost if neither comes, as when R no longer holds the result.
  • When a stream drops its share of the result on a worker (when it ends, fails or is released), the share goes to a mutex-protected list. The last share frees the statement and its R parameters, and may close the connection, which releases the R busy handler. R's main thread drops these shares at its next stream call or stream creation, at R's next call on any result, in dbSendQuery()/dbExecute(), dbClearResult(), dbDisconnect() and the finalizer of a result, and on unload (R_unload_RSQLite()). None is dropped while an R busy handler runs inside SQLite. Until then, a share dropped mid-read keeps its statement's read lock. The rest of the stream state is freed on the worker. release() throws nothing there: if the share can't be queued, the stream is leaked rather than dropped on the worker.

Following the decision in #880 (comment), the busy guard of a result (run_guarded(), a plain flag) becomes an atomic owner (DbResult::Hold), so that two threads are never in a result at once. While another thread reads a stream, R's calls on the result fail at once with "Can't use a result while another thread reads an Arrow stream of it. Try again once the read has returned." There is no mutex wait. Every entry point that uses the statement holds the result for its whole run. The ones where R allocates or may run R code (the placeholder names, the creation of a stream) mark the result as a fetch does, so a finalizer can't clear it meanwhile. A read on a worker that finds the result in use by R's main thread fails with EBUSY, as does a call of a stream while another of its calls runs, from a handler or on another thread. Both are not final. The stream's own running and released flags are atomic, so a release() during a call on another thread leaves the deletion to that call.

SQLite threading mode: the bundled SQLite is built with the default SQLITE_THREADSAFE=1 (serialized), confirmed at run time with sqlite_compileoption_used('THREADSAFE=1'). That mode is needed because R's main thread may use the same connection meanwhile through other statements or sqliteCopyDatabase(). A read on a worker checks sqlite3_threadsafe() == 1 and sqlite3_db_mutex(conn) != NULL, so it also catches a connection opened with SQLITE_OPEN_NOMUTEX, and otherwise fails with EINVAL (not final). Steps, prepares and parameter binds hold the connection's mutex until their error message is read, so a call on the other thread can't replace it. The Arrow spec forbids concurrent calls of one stream, so a release() that races the start of a call on another thread isn't guarded; the code says so in a comment. src/Makevars adds -pthread to PKG_CPPFLAGS and PKG_LIBS, as "Using pthreads" in Writing R Extensions recommends. Without it, std::thread may not link on older glibc, and there is no Makevars.win that would need its own flag.

Tests: internal hooks start a std::thread that calls get_schema(), get_next(), release(), or reads the stream to its end (result_arrow_stream_thread_start() / _join()), and result_set_pause_after_rows() pauses a worker in the middle of a chunk (_wait() / _resume()). test-arrow-stream-thread.R covers the following:

  • A worker reads 2500 rows of integer, real, text, blob and null values in three chunks, and they arrive intact.
  • The stream passes from one thread to the other and back.
  • While a worker is paused mid-read, dbFetch(), fetch_arrow_chunk(), dbHasCompleted(), dbGetRowCount(), dbColumnInfo(), dbBind(), read_arrow_stream(), dbClearResult(), dbSendQuery(), the same stream and another stream of the result all fail at once, and none of them fails for good.
  • A worker read fails with EBUSY from a warning handler of a main-thread call.
  • Warnings from a worker read reach R by the rule above.
  • The next dbBind() set is left to R's main thread with a non-final EBUSY, and the read then goes on. Arrow parameters over several arrays, one of them empty, are read entirely on a worker with code 0.
  • A message() that leaves a busy handler reaches an outer tryCatch(), and a worker read on that connection then finishes. test-dbConnect.R checks this, and the error of a non-number handler value, without threads.
  • Each of seven main-thread calls drops a share that a worker released, observed through an internal counter, and so does the query of a write itself.
  • A connection opened with SQLITE_OPEN_NOMUTEX refuses worker reads, but not for good.
  • For each R call on the result, a warning handler that clears the result leaves a clean "Invalid result set" error, under valgrind (this was a use-after-free in review).
  • A release on a worker keeps the read lock until each of four main-thread calls drops the share.

The unload test now includes a stream released on a worker.

Evidence: with on_main_thread() forced to true, the new file stops at 10 failures. With the change, 165 expectations pass. The new import tests in test-dbWriteTable.R fail 4 expectations on the previous head (0ef4e86) and pass now. A test thread left running is joined at unload. Valgrind memcheck on the new file and on the review probes: 0 errors, 0 bytes lost. Helgrind on it: no data races; its only 2 reports are p11-kit mutexes at exit. Full suite with NOT_CRAN=true: FAIL 0, WARN 3 (the locale warnings of test-encoding.R), SKIP 64, PASS 13690.

This pull request first refused reads on other threads (commit add20c2). The second commit replaces that with support, per the plan. Layer 15 of the rebuilt chain, planned in #880; based on #977. The record of the main thread, the deferred drop of results and the R-free busy handler follow the old draft #796, and the atomic owner follows the old stack's #795, without their other parts.

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


https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4


Generated by Claude Code

… thread

The callbacks of the Arrow stream call R and SQLite on the connection that R uses.
A consumer that reads on a worker thread, as arrow's scanner or Acero do,
now gets EINVAL and a message that names the thread from get_schema() and get_next(),
before the stream touches its state, and the stream reads on from R's main thread.
A release() on another thread leaves the stream to R's main thread,
which deletes it on the next call of a stream, creation of a stream,
dbClearResult(), dbDisconnect() or unloading of the package.
R_init_RSQLite() records R's main thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
krlmlr and others added 3 commits December 1, 2026 12:52
Another thread may now read an Arrow stream of a result,
as arrow's scanner and Acero do while R goes on.
On a thread other than R's main thread, the stream calls no R:
interrupts aren't checked, an R busy handler gives up at once,
the second parameter set of dbBind() fails the read,
and the fetch runs without cpp11::unwind_protect().
The warnings about the values of chunks read there are kept with the result,
and R's main thread raises them with the stream's next chunk there
or before R's next call on the result.
A share of a result that a stream drops there goes to R's main thread,
which drops it later.

The busy guard of a result becomes an atomic owner, see DbResult::Hold,
so that two threads are never in a result at once.
While another thread reads a stream, R's calls on the result fail at once
with an error that names the read,
and a read that finds the result in use by R fails with EBUSY.
A call of a stream during another of its calls fails with EBUSY too.

The tests read streams on a std::thread through internal hooks,
and pause the read to try R's calls meanwhile.
src/Makevars adds -pthread, as Writing R Extensions recommends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
…nto claude/rb-arrow-stream-thread

# Conflicts:
#	src/SqliteArrowStream.cpp
@krlmlr krlmlr changed the title fix: Refuse to read an Arrow stream from a thread other than R's main thread feat: Read Arrow streams on worker threads Dec 1, 2026
krlmlr and others added 8 commits December 1, 2026 13:25
The warnings of a read of an Arrow stream on another thread
are raised by flush_thread_warnings() in R before R's calls on the result,
not in the conversion of the result's pointer:
a handler that cleared the result left the call with a freed pointer.

Every call that uses the result's statement now holds it for its whole run,
also result_keep_arrow_chunk(), the setters and the placeholder names.
A parameter set that needs R, from dbBind() or from the next array
of an Arrow stream of parameters, is left to R's main thread:
the read on another thread fails with EBUSY, not for good,
and R's main thread binds the set and reads on.
A read on another thread also needs a connection with SQLite's mutex,
and steps hold that mutex until their error is read.
release() can't throw on another thread,
R_unload_RSQLite() joins a test thread left running,
and the finalizer of a result drops the shares that streams dropped there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
The R busy handler runs under R_UnwindProtect():
a condition that leaves it by a jump, such as a message() caught further out,
ends in the C callback, which returns 0 to SQLite,
and continue_busy_unwind() goes on with the jump
once sqlite3_step() or sqlite3_prepare_v2() has returned
and the connection's mutex is free (#941).
A handler value that isn't a single number fails the call the same way.
Before, the jump left SQLite's mutex held,
and a read of an Arrow stream on another thread waited for it for good.

The creation of an Arrow stream reads the rest of an Arrow stream
of parameters on R's main thread,
so that a read on another thread binds all of its sets.
dbSendQuery() drops the shares that streams dropped on another thread,
no drop happens while an R busy handler runs,
the placeholder names and the stream's creation guard the result
while R may run,
and the errors of preparing and binding are read under the connection's mutex.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd7QnTD4acgzTUihnF4
The CSV import returns at once when a jump out of the busy handler waits,
instead of raising an R error,
and connection_import_file() goes on with the jump.
Every call of SQLite that may run the busy handler
fails with an internal error if a jump was left pending,
rather than go on with it in an unrelated call,
and sqlite3_load_extension() goes on with a jump too.
dbWriteTable() from a file rolls back the savepoint that started a transaction
with ROLLBACK, which needs no lock,
so that a jump out of the import leaves no transaction open.
The documentation of sqliteSetBusyHandler() says what a failing handler does.

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

krlmlr commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

Question: one more review round for the busy-handler fix in this pull request?

The third and last review round of this pull request found a High in the busy-handler change from round 2: when the R busy handler jumped out during a CSV import, the import raised its own error first, so the jump stayed pending and hijacked a later SQLite call. Through dbWriteTable(con, name, file) that left a savepoint open and the database locked. The fix is implemented: the import now returns instead of raising while a jump waits (import-file.c), every SQLite call that can run the busy handler refuses to inherit a pending jump, and file dbWriteTable() now rolls back with a plain ROLLBACK when its savepoint opened the transaction, which also releases the lock in the case the reviewer found. Tests for both reproductions fail on the previous head and pass now, the full suite passes, and the thread tests are clean under valgrind. Your rules allow three review rounds per change and send a High that survives the third to you, so the fix itself has not been reviewed.

  • Run one more clean review round, limited to the fix (recommended: the busy handler runs on every connection, and the fix touches the import and transaction handling)
  • Accept the fix without another review

Kirill decides. Until then no further round runs, and the pull request stays a draft.


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