Repository navigation
Conversation
… 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
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
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
…nto claude/rb-arrow-stream-thread
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
…nto claude/rb-arrow-stream-thread
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
Kirill decides. Until then no further round runs, and the pull request stays a draft. Generated by Claude Code |
For users: a condition that leaves the busy handler of
sqliteSetBusyHandler()by a jump (such as amessage()caught by atryCatch()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 ofread_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:cpp11::unwind_protect(), interrupts aren't checked, an R busy handler gives up at once (the step fails withSQLITE_BUSY), andcheck_ready()and the inactive-result check throw C++ exceptions instead ofcpp11::stop().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 withEBUSY("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.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, andcontinue_busy_unwind()continues the jump oncesqlite3_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 withROLLBACKwhen its savepoint started the transaction:ROLLBACK TO+RELEASEneed a lock that another connection may hold, and left the transaction open, even without a jump.dbFetch(),dbBind(),dbHasCompleted(),dbGetRowCount(),dbGetRowsAffected(),dbColumnInfo(),dbClearResult(),read_arrow_stream(),fetch_arrow_chunk_warn()). They are raised byflush_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.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 withEBUSY, 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 arelease()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 withsqlite_compileoption_used('THREADSAFE=1'). That mode is needed because R's main thread may use the same connection meanwhile through other statements orsqliteCopyDatabase(). A read on a worker checkssqlite3_threadsafe() == 1andsqlite3_db_mutex(conn) != NULL, so it also catches a connection opened withSQLITE_OPEN_NOMUTEX, and otherwise fails withEINVAL(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 arelease()that races the start of a call on another thread isn't guarded; the code says so in a comment.src/Makevarsadds-pthreadtoPKG_CPPFLAGSandPKG_LIBS, as "Using pthreads" in Writing R Extensions recommends. Without it,std::threadmay not link on older glibc, and there is noMakevars.winthat would need its own flag.Tests: internal hooks start a
std::threadthat callsget_schema(),get_next(),release(), or reads the stream to its end (result_arrow_stream_thread_start()/_join()), andresult_set_pause_after_rows()pauses a worker in the middle of a chunk (_wait()/_resume()).test-arrow-stream-thread.Rcovers the following: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.EBUSYfrom a warning handler of a main-thread call.dbBind()set is left to R's main thread with a non-finalEBUSY, and the read then goes on. Arrow parameters over several arrays, one of them empty, are read entirely on a worker with code 0.message()that leaves a busy handler reaches an outertryCatch(), and a worker read on that connection then finishes.test-dbConnect.Rchecks this, and the error of a non-number handler value, without threads.SQLITE_OPEN_NOMUTEXrefuses worker reads, but not for good.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 intest-dbWriteTable.Rfail 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 withNOT_CRAN=true: FAIL 0, WARN 3 (the locale warnings oftest-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