Skip to content

feat: Read a result as a lazy Arrow array stream - #864

Draft
krlmlr wants to merge 12 commits into
claude/arrow-byte-limitsfrom
claude/arrow-lazy-stream
Draft

krlmlr wants to merge 12 commits into
claude/arrow-byte-limitsfrom
claude/arrow-lazy-stream

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Pull request 9 of the Arrow rework plan. It stacks on #863 (Arrow chunks end before string and binary offsets overflow), which stacks on #862, #861, #860, #859, #857, #856, #855, #830 and #850.

What changes

A new internal entry point, read_arrow_stream(res, n = 65536L), returns a nanoarrow_array_stream over an open result. Each get_next() fetches the next chunk of at most n rows (all of them for -1) with the chunk machinery of #859 to #863: the same column types, the coercion warning once per chunk, and the byte limit that ends a chunk before its string or binary offsets overflow. Nothing is fetched when the stream is created. get_schema() reads the first chunk, which decides the column types as for result_fetch_arrow_chunk(), and keeps it for the first get_next(), so no row is handed out before the schema and the schema always matches the chunks. The schema is cached in the stream once read. A result without rows ends the stream without a chunk, with the types of the declared columns. No DBI method calls the stream yet, and the default dbFetch() path is unchanged except for the check below.

Lifetime. The stream holds a share of the result (the DbResultPtr from #856), so the result lives through every callback, also if R's garbage collector frees the R result object meanwhile. dbClearResult() now calls DbResult::clear(), which frees the statement and drops the connection even while a stream holds a share. The next get_schema() or get_next() then fails with "Can't read an Arrow stream after its result has been cleared." It likewise fails after dbDisconnect() ("…after its connection has been closed.") and after dbBind() starts a new execution, whose types may differ from the stream's schema ("…after its result has been bound to new parameters."). The stream never touches the freed statement: it checks these conditions before each fetch, and its release() only drops its share. A stream that reaches its end drops its share at once.

Errors. C++ errors, among them SQLite's, become the stream's EIO with the message in get_last_error(). The fetch loop is the same as for result_fetch_arrow_chunk(), so #830's semantics hold: an error at the step that reads ahead after a full chunk is kept for the next get_next(), any error completes the result, and the busy guard stops a warning handler from clearing the result during a fetch. An interrupt, or a coercion warning made an error by options(warn = 2), arrives as a cpp11::unwind_exception. Its jump continues once the callback's C++ objects are destroyed, as at cpp11's entry points, and the chunk kept by #862 comes with the next get_next(). Any other failure of a callback is final: later get_next() calls, and get_schema() calls until a schema is cached, fail again with its message, rather than end the stream as if its rows were complete, so a consumer that goes on after an error or an interrupt can't take a truncated result for a complete one. The flag is never cleared once set.

Release during a callback. A handler of a warning raised inside the stream's own get_schema() or get_next() may call the stream's release(). The stream counts its running callbacks: such a release only marks the state released and detaches it from the C struct, and the callback deletes the state, with its share of the result, once its body returns and before it continues an R jump. Without this, the callback would write into the freed state, or into a freed result when R had dropped its object. A consumer that doesn't check release between chunks, such as nanoarrow's convert_array_stream(), may call the released stream again: its get_schema() and get_next() then return EINVAL without touching any state, and get_last_error() returns "The Arrow stream has been released." Each callback body runs under R_ExecWithCleanup(), so the count of running callbacks stays right even if an R error leaves the body by a jump that bypasses cpp11.

Mixed fetches. This applies the recommended answer of the mixed-fetch question, which nobody has decided yet. Once a stream has been created for a result, dbFetch() on it fails with an error of class RSQLite_error_fetch_kind. Once dbFetch() has been called on a result, with any n, creating a stream fails likewise. The claim holds for the result's lifetime, also across dbBind(). The rule lives in one place, claim_fetch_kind() in R/arrow-stream.R: dropping its error allows mixing, which the internal fetches already support. result_fetch_arrow_chunk() is not part of the rule, so the tests of #859 that alternate the two kinds of fetch keep working.

Deliberately left out

  • Reading a stream after dbClearResult() or dbDisconnect(): pull request 10.
  • Reading a stream on a worker thread, as arrow's scanner and Acero do: pull request 15. The callbacks call R and must run on R's main thread, and a release() that drops the last share destroys the result where it runs.
  • dbSendQueryArrow(), dbFetchArrow() and dbFetchArrowChunk() through the stream: pull request 16.
  • The old stack's buffered stream and its rethrow of R jumps for C++ consumers in this package belong to those later pull requests.

Error message

The error uses rlang::abort() rather than cli::cli_abort(). cli is only in Suggests, and dbFetch() can raise this error.

Tests

tests/testthat/test-arrow-stream.R, run through nanoarrow ($get_schema(), $get_next(), convert_array_stream()):

  • chunk lengths and dbGetRowCount() as the stream advances, and agreement with dbGetQuery()
  • the schema before any row is handed out, decided by the first chunk
  • a result without rows
  • the coercion warning once per chunk, and a warning made an error under options(warn = 2), after which the stream goes on with the kept chunk
  • the errors after dbClearResult(), dbDisconnect() and dbBind()
  • a stream that keeps reading after R frees its result object
  • an SQLite error at the read-ahead step and inside a chunk, after which get_next() keeps failing, and an SQLite error while the schema is read, after which three convert_array_stream() calls all fail
  • a release() from a handler of the stream's own warning, with the R result object kept and with it freed, and from a handler during convert_array_stream() (also run under valgrind, with the reviews' reproducers)
  • the mixed-fetch rule in both directions, with snapshots of the messages
  • the checks of n

Every test_that() block runs on its own after load_all(). devtools::test() with NOT_CRAN=true passes except the three known errors in test-httpvfs.R (#832, #837), and R CMD check --no-manual passes.

https://claude.ai/code/session_01Hr1rd432Aef98ibnZSSsYn


Generated by Claude Code

The internal `read_arrow_stream()` returns a `nanoarrow_array_stream`
whose `get_next()` fetches the next chunk of at most `n` rows of the result,
built as `result_fetch_arrow_chunk()` builds it:
the same column types, coercion warnings and byte limits.
`get_schema()` reads the first chunk, which decides the types,
and keeps it for the first `get_next()`,
so that no row is handed out before the schema.

The stream shares the result with its R object,
so the result outlives a callback even if R frees the object meanwhile.
Once `dbClearResult()` clears the result, which now frees its statement
also while a stream holds a share,
once the connection is closed,
or once the result is bound to new parameters,
the next `get_schema()` or `get_next()` fails with an error that says so.
Errors of SQLite reach the consumer through `get_last_error()`,
with the semantics of the fetch loop;
an interrupt or a warning made an error continues its jump
once the callback's C++ objects are destroyed.

A result is fetched either as data frames or as an Arrow stream,
whichever comes first:
`claim_fetch_kind()` holds this rule in one place,
so that it is easy to relax.

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 21:16

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at 89e2751, by a Claude Code reviewer with clean context that read the description, the diff against the merged base head 975e379 (#863), the surrounding DbResult, fetch loop, read-ahead and bind code, the connection release and the new tests; built the pull request and its base into separate libraries; and ran the test suites, R CMD check, reproducers of its own, valgrind and a small benchmark. I posted nothing on GitHub myself.

What was run

  • devtools::test() with NOT_CRAN=true on the pull request and on the base; test-arrow-stream.R against both, and each of its 12 test_that() blocks on its own after pkgload::load_all().
  • R CMD check --no-manual on the pull request.
  • Reproducers in the scratchpad (r864/): default-path.R (clearing, disconnecting with open results, garbage collection, kept errors, busy guard, dbBind(), dbGetQuery(), dbGetQueryArrow(), run on both libraries and diffed), lifetime.R, release-in-handler.R, data.R, interrupt.R (real SIGINT during get_next() and convert_array_stream()), bench.R.
  • valgrind on lifetime.R, release-in-handler.R, and on test-arrow-stream.R, test-dbClearResult.R, test-read-ahead.R, test-exception.R, test-dbBind.R, test-dbSendQuery.R (the last five also on the base).

What holds

  • Test suites: only the three known test-httpvfs.R errors, on both; the DBItest progress line is byte-identical between base and pull request (9618 passes, same skips). Every block of the new file passes on its own; on the base every block fails for want of read_arrow_stream(). R CMD check: one NOTE, about the worktree's .git, an artifact of my checkout.
  • The default path behaves exactly as on the base: the output of default-path.R is identical, including messages and calls of errors and warnings (clearing twice, fetching a cleared result, dbSendQuery() closing an open result, dbDisconnect() with an open result and fetching afterwards, results and connections freed by gc(), the kept read-ahead error of fix: Never restart a statement after an error in dbFetch() or dbBind() #830 and the completed result after it, re-execution with dbBind(), dbFetch(res, 0)). The destructor order is unchanged: impl is declared after pConn_, so it was already destroyed first; clear() keeps that order, and ~DbResult() and every other use of pConn_ or impl after clear() are either guarded or unreachable because the R pointer is reset.
  • Lifetime under valgrind, no errors and no definite leaks from this pull request: streams used after dbClearResult(), after dbDisconnect() (then cleared), after rm() + gc() of both the result and the connection (the stream still reads all rows), after dbBind(), released before and after exhaustion, released twice, never released, and get_next() without get_schema(). The single 40-byte definite leak in peek_first_row() appears identically on the base.
  • Jumps: a warning made an error by options(warn = 2) and a handler that leaves by a restart, inside get_next() and inside convert_array_stream(), are valgrind-clean, and the kept chunk comes with the next get_next(). A real SIGINT during a 30-million-row get_next() and during convert_array_stream() reaches R's interrupt handler; nothing crashes afterwards. The busy guard refuses dbClearResult() and a re-entrant get_next() from a handler of the stream's own warning.
  • Data: chunk lengths, coercion warnings and the schema of the stream equal those of repeated result_fetch_arrow_chunk() calls for n of 1, 7, -1, byte limits of feat: End Arrow chunks before string and binary offsets overflow #863 (7,3,2,2,1,...), an all-NULL first chunk, types decided by the first chunk with text in later ones, and empty results (declared types, no chunk); a value over the byte limit fails the stream with feat: End Arrow chunks before string and binary offsets overflow #863's message; convert_array_stream() equals dbGetQuery().
  • The claim costs about 1 µs per dbFetch() (an R closure and a .Call), within noise against about 25 µs for dbFetch(res, 1). dbGetQueryArrow() still works.
  • The description matches the code; the scope matches the title; src/SqliteArrowStream.dd holds no absolute paths.

High

None.

Medium

  1. Calling the stream's release() from a handler of a warning raised inside its own get_schema() or get_next() frees the stream state while the callback still uses it: invalid write, segfault.
    int run_callback(StreamState* state, F body) {
    SEXP token = R_NilValue;
    try {
    body();
    return NANOARROW_OK;
    } catch (const cpp11::unwind_exception& e) {
    token = e.token;
    } catch (const std::exception& e) {
    state->last_error = e.what();
    return EIO;
    } catch (...) {
    state->last_error = "Unknown C++ error";
    return EIO;
    }
    R_ContinueUnwind(token);
    return EIO;
    }
    int stream_get_schema(
    struct ArrowArrayStream* stream,
    struct ArrowSchema* out
    ) {
    StreamState* state = get_state(stream);
    return run_callback(state, [&] { get_schema_impl(state, out); });
    }
    int stream_get_next(struct ArrowArrayStream* stream, struct ArrowArray* out) {
    StreamState* state = get_state(stream);
    return run_callback(state, [&] { get_next_impl(state, out); });
    }
    const char* stream_get_last_error(struct ArrowArrayStream* stream) {
    return get_state(stream)->last_error.c_str();
    }
    // Destroys the result if R has dropped it,
    // as R's garbage collector does when it frees the stream
    void stream_release(struct ArrowArrayStream* stream) {
    delete get_state(stream);
    stream->private_data = NULL;
    stream->release = NULL;
    }
    (Confirmed) release-in-handler.R reads a result whose first chunk raises the coercion warning; the handler calls s$release(). With the R result object dropped and collected, R segfaults ("memory not mapped"), because the release drops the last share of the result whose busy_ flag run_guarded() then resets, and ensure_schema() writes into the deleted state->schema. With the result kept, valgrind reports an invalid write in ArrowSchemaDeepCopy() called from SqliteResultImpl::arrow_schema(), into the block freed by stream_release(). This is exactly the hazard that the busy guard of fix: Never restart a statement after an error in dbFetch() or dbBind() #830 closes for dbClearResult(), and nanoarrow's $release() does not check for a running callback. The function is internal for now, so users reach it only with :::, but pull request 16 will expose it. Suggested fix: count a running callback in StreamState; in stream_release(), if a callback runs, only mark the state released (and detach stream->private_data), and let run_callback() delete the state once the body returns, before R_ContinueUnwind(); add a test that releases from a handler.

Low

  1. After a failed get_next() (an SQLite error inside a chunk, or an interrupt), the next get_next() reports a clean end of the stream, so a consumer that goes on sees a truncated result as complete.
    void get_next_impl(StreamState* state, struct ArrowArray* out) {
    out->release = NULL;
    if (state->done) {
    return;
    }
    DbResult* result = checked_result(state);
    ensure_schema(state, result);
    nanoarrow::UniqueArray array;
    if (!result->complete()) {
    nanoarrow::UniqueSchema schema;
    result->fetch_arrow_chunk(array.get(), schema.get(), state->n_max);
    }
    // A result without rows ends the stream with no chunk:
    // only the chunk that get_schema() keeps for it can be empty
    if (array->release == NULL || (array->length == 0 && result->complete())) {
    state->done = true;
    // Frees the statement unless R still holds the result
    state->result.reset();
    return;
    }
    ArrowArrayMove(array.get(), out);
    }
    (Confirmed) After a SIGINT during get_next(), dbGetRowCount() is 0 and get_next() returns NULL; the test "an error of SQLite fails the stream and completes the result" asserts the same NULL. This mirrors dbFetch() after fix: Never restart a statement after an error in dbFetch() or dbBind() #830, and the Arrow C stream interface leaves calls after an error undefined, but this stream deliberately invites a further get_next() after a jump (the kept chunk of feat: Report values converted to an Arrow column's type once per chunk, with their rows #862), which makes the silent end easy to mistake for completion. Suggested fix: remember in StreamState that a fetch failed, other than by the kept-chunk path, and fail later get_next() calls with that error instead of ending; or state the current behavior in the comment and the description.

Generated by Claude Code

…r, and make its failures final

A `release()` called from a handler of a warning that the stream's own
`get_schema()` or `get_next()` raises
freed the state, and possibly the result, while the callback still used them.
The state now counts its running callbacks:
`release()` during one only marks the state released,
and the callback deletes it once its body returns,
before it continues an R jump.

After a failed `get_next()`, by an error of SQLite, an interrupt
or another error, later calls fail again with its message
instead of ending the stream as if the rows were complete.
A chunk kept when its warning exited still comes with the next call.

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

CI: the full matrix is blocked by #836, not by this pull request

The full matrix dispatched by hand for 89e2751 (run 43310606297) stopped after the smoke test, whose step "Write diff and fail for workflow_dispatch" found three files to regenerate: src/cpp11.dd and src/result.dd, which gained hundreds of absolute paths through gcc's continuation lines that the filter in src/Makevars.deps does not drop (#836, fixed by #853), and the formatting of src/result.cpp that #863 already carries (75c9515) and that 89e2751 predates. A dispatched run fails where a push-triggered run commits, so the matrix jobs were skipped. R CMD check in that job ended with "Status: OK", and the only test failures are the three test-httpvfs.R errors that also happen on main (#832, #837).

Any branch whose change regenerates src/cpp11.dd, as every new C++ entry point does, hits this until #853 is merged. Once it is, merging main up the stack and dispatching the matrix again gives a clean run; until then the push-triggered smoke test is the CI of record here.


Generated by Claude Code

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Second review round of this pull request, of a0f7fee, which addresses the two findings of the first round (the use-after-free on a release() from a handler, and the clean end after a failure). Review of this pull request at a0f7fee, by a Claude Code reviewer with clean context that read git diff 89e27517 a0f7fee4, the stream code around it, the guarded fetch and kept-chunk code in DbResult.cpp and SqliteResultImpl.cpp, the changed tests and the description; built the commit and its parent into separate libraries; and ran the tests, reproducers of its own and valgrind. I posted nothing on GitHub myself.

What was run

  • devtools::test() with NOT_CRAN=true on a0f7fee; test-arrow-stream.R against a0f7fee and 89e2751; each of its 13 test_that() blocks on its own after pkgload::load_all().
  • New reproducers in the scratchpad (r864-r2/): nested.R (a handler that calls get_next() and get_schema() of the same stream, then release() twice, with the R result kept and garbage-collected; a handler that releases and then jumps; a release during get_schema(); with convert also a release during convert_array_stream()), sticky.R (options(warn = 2) on the first and a later chunk and inside convert_array_stream(), a restart, a refused nested call followed by a muffle or a jump, clearing, rebinding, disconnecting, an SQLite error), schemafail.R (failures inside get_schema() and retries), interrupt.R (a real SIGINT during get_next() and convert_array_stream()), disc.R.
  • valgrind (--leak-check=full) on nested.R, sticky.R, the first round's release-in-handler.R in both modes, and test-arrow-stream.R; valgrind on nested.R convert for the stack of the crash.

What holds

  • Tests: only the three known test-httpvfs.R errors; every block of test-arrow-stream.R passes on its own. On 89e2751 the file segfaults in the new release test, so the test catches the first-round bug.
  • The deferred release, for $get_next() and $get_schema() called from R: no valgrind errors and no definite leaks in any case of nested.R, sticky.R, release-in-handler.R or the test file, so the state and its share of the result are freed exactly once on normal return, C++ error and R jump, with the result kept or collected, and with a nested call refused by the busy guard or answered from the cached schema before the release. A second release() is refused by nanoarrow. The state is deleted only after run_guarded() has reset busy_, so a collected result is destroyed after its guard.
  • The sticky failure: after an SQLite error in get_next(), a clear, a rebind, a disconnect or a SIGINT, every later get_next() fails with the stored message (89e2751 returned NULL). Under options(warn = 2) and after a handler's restart or jump, the kept chunk still comes with the next call, on the first and on a later chunk, also through convert_array_stream(). A nested call refused by the busy guard leaves the outer fetch and the stream intact.
  • DbResult::arrow_chunk_kept() is reached only after result->cleared() is false, so impl is never null there; moving the declaration to public changes nothing on the default path.
  • The diff touches no src/*.dd file; the scope matches the title.

High

None.

Medium

  1. A release() from a handler during convert_array_stream() still crashes R: nanoarrow calls get_next() again on the released stream, and stream_get_next() dereferences the null state.
    int stream_get_next(struct ArrowArrayStream* stream, struct ArrowArray* out) {
    StreamState* state = get_state(stream);
    return run_callback(state, [&] { get_next_impl(state, out); });
    }
    const char* stream_get_last_error(struct ArrowArrayStream* stream) {
    return get_state(stream)->last_error.c_str();
    }
    // Destroys the result if R has dropped it,
    // as R's garbage collector does when it frees the stream.
    // During a callback, the callback deletes the state once it returns:
    // it goes on with the state and the result.
    void stream_release(struct ArrowArrayStream* stream) {
    StreamState* state = get_state(stream);
    if (state->running > 0) {
    state->released = true;
    } else {
    delete state;
    }
    stream->private_data = NULL;
    stream->release = NULL;
    }
    (Confirmed) nested.R convert reads six rows in chunks of 2 with a coercion in the second chunk, and the handler calls s$release(). The deferred release keeps the running callback safe, but stream_release() leaves get_next, get_schema and get_last_error in the struct and sets private_data to NULL; nanoarrow_c_collect_array_stream() does not check release between chunks, so its next call reaches ++state->running with a null state (valgrind: invalid read at SqliteArrowStream.cpp:138, called from nanoarrow_c_collect_array_stream; R: segfault at address 0x88, the offset of running). The new test and the description cover only $get_next(), which nanoarrow's R wrapper guards. The same null dereference awaits get_last_error() after a released stream's callback returns an error. 89e2751 crashes here too, so this is what remains of the first-round finding rather than a regression. Suggested fix: make the callbacks safe on a released stream: in stream_get_schema() and stream_get_next(), return EINVAL when get_state(stream) is NULL (setting out->release = NULL), and let stream_get_last_error() return a static "The Arrow stream has been released." for a null state; add convert_array_stream() to the new test.

Low

  1. The failure is not final after a retry: a later failing callback recomputes failed from arrow_chunk_kept() and can clear it, so a third attempt reports a clean, empty end.

    --state->running;
    // A call from a handler during another callback, which the busy guard
    // refuses, leaves the stream to that callback
    if (code != NANOARROW_OK && state->running == 0) {
    const DbResult* result = state->result.get();
    state->failed =
    result == NULL || result->cleared() || !result->arrow_chunk_kept();
    }
    (Confirmed) With SELECT 1 AS x UNION ALL SELECT abs(-9223372036854775808) and n = 5, get_schema() fails with "integer overflow" and sets failed; a second get_schema() has no cached schema, so get_schema_impl() builds a new, empty chunk of the completed result and keeps it; the next get_next() fails with the stored message, but its run_callback() sees a kept chunk and resets failed to false; the following get_next() returns that empty chunk's end, NULL. Calling convert_array_stream(s) three times gives an error, an error, then a data frame of 0 rows. The same holds when the first get_next() fails before the schema is cached. This contradicts the description's "a consumer that goes on after an error or an interrupt can't take a truncated result for a complete one". Suggested fix: only ever set the flag, if (code != NANOARROW_OK && state->running == 0 && !state->failed), and make get_schema_impl() throw the stored error when state->failed and no schema is cached; add the triple retry to the SQLite-error test.

  2. An R longjmp that bypasses cpp11 inside a callback leaves running incremented for good: a later release() then never deletes the state, and failures no longer stick.

    template <typename F>
    int run_callback(StreamState* state, F body) {
    SEXP token = R_NilValue;
    int code = NANOARROW_OK;
    ++state->running;
    try {
    body();
    } catch (const cpp11::unwind_exception& e) {
    token = e.token;
    state->last_error =
    "Can't read an Arrow stream after an R condition interrupted a fetch.";
    code = EIO;
    } catch (const std::exception& e) {
    state->last_error = e.what();
    code = EIO;
    } catch (...) {
    state->last_error = "Unknown C++ error";
    code = EIO;
    }
    --state->running;
    // A call from a handler during another callback, which the busy guard
    // refuses, leaves the stream to that callback
    if (code != NANOARROW_OK && state->running == 0) {
    const DbResult* result = state->result.get();
    state->failed =
    result == NULL || result->cleared() || !result->arrow_chunk_kept();
    }
    if (state->released && state->running == 0) {
    delete state;
    }
    if (token != R_NilValue) {
    R_ContinueUnwind(token);
    }
    return code;
    }
    (by reading) run_guarded() documents that such a longjmp (a failed allocation in R's API outside cpp11::safe) skips the C++ frames; it now also skips --state->running, so stream_release() only marks the state released (leaking the state and the statement it shares) and failed is never computed again because running is never 0. The trigger is rare, as cpp11 wraps the R calls in the fetch. Suggested fix: accept it and say so in the comment above run_callback(), or decrement the counter from an R_ExecWithCleanup() cleanup as run_guarded() does for busy_.


Generated by Claude Code

…ilures final

A consumer that doesn't check `release` between chunks,
such as nanoarrow's `convert_array_stream()`,
calls `get_next()` again on a stream released from a handler;
the callbacks now return `EINVAL` for a released stream without touching it,
and `get_last_error()` returns a fixed message.

A failure is never cleared once recorded,
and `get_schema()` raises it as well until a schema is cached,
so that a retry can't report an empty, complete stream.

The count of running callbacks is kept by `R_ExecWithCleanup()`,
also when an R error leaves a callback by a jump that bypasses cpp11.

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

Third review round of this pull request, of db5b47a, which addresses the findings of the second round (a crash when a handler releases the stream during convert_array_stream(), a failure that a retry could clear, and a callback count that a raw R jump could leave wrong). Review of this pull request at db5b47a, by a Claude Code reviewer with clean context that read git diff a0f7fee4 db5b47aa, the whole of src/SqliteArrowStream.cpp, run_guarded() in DbResult.cpp, the destructors that delete state can reach, cpp11 0.5.5's unwind_protect(), the changed tests and the description; built db5b47a, a0f7fee and a patched copy of db5b47a into separate libraries; and ran the tests, reproducers of its own and valgrind. I posted nothing on GitHub myself.

What was run

  • devtools::test() with NOT_CRAN=true on db5b47a; test-arrow-stream.R against db5b47a and a0f7fee; each of its 14 test_that() blocks on its own after pkgload::load_all(); the test file under valgrind.
  • New reproducers in the scratchpad (r864-r3/): released.R (a release from a handler of a warning in the first and in a later chunk, during convert_array_stream(), collect_array_stream() and basic_array_stream(collect_array_stream()), with a muffle or a stop(), with the R result kept or collected; then the R wrappers, and all four C callbacks called directly through a small C helper, c/released_cb.c), raw.R (a build patched to call Rf_error() at the top of get_next_impl() or get_schema_impl(): a raw longjmp in a plain call, in convert_array_stream(), in get_schema(), in a nested call of the same stream from a handler, and in another stream's callback from a handler of a stream that the handler released), sticky3.R (a read-ahead error during get_schema(), options(warn = 2) on the first chunk through convert_array_stream() and get_schema(), a cached schema after a failure).
  • valgrind (--leak-check=full) on released.R and raw.R; the second round's sticky.R and schemafail.R on both builds; a real SIGINT during a long get_next() and during convert_array_stream() (r864-r2/interrupt.R).

What holds

  • Tests: no failures except the known test-httpvfs.R errors; every block of test-arrow-stream.R passes on its own. On a0f7fee the file aborts R in the new convert_array_stream() test, and the triple retry gives a data frame of 0 rows the third time, so both new tests catch the second-round findings.
  • Released streams: after a release from a handler, stream_get_schema() and stream_get_next() return EINVAL without touching any state (get_next() sets out->release to NULL), and stream_get_last_error() returns "The Arrow stream has been released.". nanoarrow's C loop in convert_array_stream() reaches that path and reports it; its R methods and collect_array_stream() refuse the released stream themselves. valgrind: 0 errors and nothing definitely lost across the 24 combinations and the direct C calls.
  • R_ExecWithCleanup(): the cleanup runs exactly once on normal return, a C++ error, a cpp11 unwind and a raw longjmp, also for a nested callback whose raw jump leaves through the handler into the outer callback's cpp11 frame. R_ContinueUnwind() runs only after R_ExecWithCleanup() has returned. After a raw jump the counter is right: later calls fail with "…after an R error interrupted a fetch.", a later release() frees the state, and valgrind reports nothing lost. The cleanup calls no R API that can raise an error: delete state reaches only sqlite3_finalize(), sqlite3_close_v2() and R_ReleaseObject(), all inside destructors that do not throw. The busy guard's cleanup runs before the stream's, so a collected result is destroyed after its guard is reset.
  • Sticky failure: failed is only ever set; get_schema() raises the stored error until a schema is cached and returns a cached one after a failure; three convert_array_stream() calls after a schema-time SQLite error all fail. Under options(warn = 2), on the first chunk (through get_schema() and convert_array_stream()) and on a later one, the kept chunk still comes next, and a read-ahead error during get_schema() still delivers the chunk first.
  • Interrupts: a SIGINT inside get_next() makes the stream fail for good; one that lands in nanoarrow's conversion between callbacks leaves the stream readable. The diff does not touch DbResult.cpp or the dbFetch() path.
  • The description matches the code, the scope matches the title, and no src/*.dd file changes.

High

None.

Medium

None.

Low

  1. The new convert_array_stream() test depends on nanoarrow not checking release between chunks: a nanoarrow that did would fail it with "has already been released", which the regex does not match.
    test_that("a stream can be released from a handler while nanoarrow converts it", {
    skip_if_not_installed("nanoarrow")
    con <- local_con()
    # The warning comes with the second chunk,
    # and nanoarrow asks the released stream for a third one
    res <- local_result(
    con,
    "SELECT 1 AS x UNION ALL SELECT 2 UNION ALL SELECT 'a' UNION ALL SELECT 4"
    )
    stream <- read_arrow_stream(res, 2)
    expect_error(
    withCallingHandlers(
    nanoarrow::convert_array_stream(stream),
    RSQLite_warning_coercion = function(w) {
    stream$release()
    invokeRestart("muffleWarning")
    }
    ),
    "has been released"
    )
    })
    (Confirmed) The expected message "has been released" matches only RSQLite's own released_error; nanoarrow 0.9.0's R-level refusal is "nanoarrow_array_stream() has already been released" (seen in released.R), and grepl("has been released", that) is FALSE. A future nanoarrow that refuses a released stream in its C loop would therefore break the test while RSQLite behaves correctly. Suggested fix: expect "been released", or keep the C path covered by the regex and add a comment that the test pins nanoarrow 0.9.0's behaviour.

Generated by Claude Code

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the new copy.

Three clean review rounds: the first of the whole pull request at 89e2751, the second of a0f7fee and the third of db5b47a. The first two found a crash when a handler releases the stream during its own callback (fixed by deferring the release and by failing every callback of a released stream with EINVAL) and a stream reporting a clean end after a failure (failures are now final). The third found only a test pattern tied to nanoarrow 0.9.0's wording, fixed after it. The default path is unchanged: DBItest output is byte-identical to the base, and dbFetch() costs about 1 µs more per call for the mixed-fetch check (about 25 µs for dbFetch(res, 1)). valgrind found nothing on any reproducer of the three rounds. These remain:

  • R/arrow-stream.R#L26-L36: one result can't mix data-frame and Arrow fetches; the first kind claims it for its lifetime, also across dbBind(). This applies the recommended answer of the open mixed-fetch question; dropping the error in claim_fetch_kind() allows mixing. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L13-L20: the stream fails after dbClearResult(), dbDisconnect() and dbBind() (pull request 10 lets it outlive the first two), but keeps reading when R garbage-collects the result object without dbClearResult(), since it holds a share of the result. Relevance: low; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L20: the callbacks call R and must run on R's main thread; a release() that drops the last share destroys the result where it runs. Worker threads are pull request 15. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L186-L205: an R error that leaves a callback by a jump bypassing cpp11 still skips the C++ destructors of that callback's body; the cleanup keeps the stream's state consistent, as run_guarded() does for the busy flag. No path in the package raises one. Relevance: low; reviewer's confidence: high (recorded).
  • The full CI matrix could not run: a dispatched run fails on the src/*.dd files that gcc regenerates with absolute paths (Incremental builds miss changes to bundled extensions under src/vendor/extensions/ #836, fixed by build: Keep system headers out of the generated .dd files on gcc's continuation lines #853), see this comment. The push-triggered smoke test passes; R CMD check --no-manual passes locally. Relevance: medium; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the stream fail once R frees its result object without dbClearResult()?

The stream holds a share of the result, so it keeps reading when R's garbage collector frees the R result object, while it fails after dbClearResult(), dbDisconnect() and dbBind() (src/SqliteArrowStream.cpp#L13-L21); pull request 10 lets it outlive the first two. A connection with such a stream open stays in use until the stream is released. Against this pull request's head, built from source:

library(DBI)
con <- dbConnect(RSQLite::SQLite())
dbExecute(con, "CREATE TABLE t (x INTEGER)")
#> [1] 0
dbExecute(con, "INSERT INTO t VALUES (1), (2), (3), (4), (5)")
#> [1] 5
res <- dbSendQuery(con, "SELECT x FROM t")
stream <- RSQLite:::read_arrow_stream(res, 2L)

# The R result object goes away without dbClearResult()
rm(res)
invisible(gc())

# The stream holds a share of the result and still reads every row
nanoarrow::convert_array_stream(stream)
#>   x
#> 1 1
#> 2 2
#> 3 3
#> 4 4
#> 5 5
dbDisconnect(con)
#> Warning in connection_release(conn@ptr): There are 1 result in use. The
#> connection will be released when they are closed

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

  • Keep reading, since a consumer that holds only the stream expects all its rows (recommended)
  • Fail the stream once the R result object is gone, as after dbClearResult()

Kirill decides. If nobody decides, the stream keeps reading.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the stream be safe to read on a thread other than R's main thread in this pull request?

The stream's callbacks call R, through the fetch and the coercion warning, so they must run on R's main thread, and a release() that drops the last share of the result destroys it where it runs (src/SqliteArrowStream.cpp#L13-L21). Consumers such as arrow's scanner and Acero read streams on worker threads. Nothing reaches the stream from outside yet: no DBI method calls it until pull request 16. The older question about waiting for a stream read on another thread concerns the same problem in the old stack. This needs a thread and a consumer that a script here can't host, so there is no reproducer.

  • Leave worker threads to pull request 15, as planned, and keep the comment that says the callbacks run on the main thread (recommended)
  • Make the callbacks safe off the main thread here, which needs the warning's text without calling R and a release that hands the result back to the main thread

Kirill decides. If nobody decides, worker threads come with pull request 15.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the stream's callbacks also destroy their C++ objects when an R error leaves them by a jump that bypasses cpp11?

Each callback body runs under R_ExecWithCleanup(), so the count of running callbacks and the stream's state stay right on any jump, as run_guarded() keeps the busy flag of the result. A jump that bypasses cpp11, such as one from an R API call outside cpp11::safe, still skips the C++ destructors of the body (src/SqliteArrowStream.cpp#L180-L208), which can leak what they own. No path in the package raises one; the third review reached it only with a build patched to call Rf_error() at the top of a callback, so there is no reproducer against this pull request as it is.

Kirill decides. If nobody decides, it stays as it is, recorded in the comment above run_callback().


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.

Three clean review rounds: the first of the whole pull request at 89e2751, the second of a0f7fee and the third of db5b47a. The first two found a crash when a handler releases the stream during its own callback (fixed by deferring the release and by failing every callback of a released stream with EINVAL) and a stream reporting a clean end after a failure (failures are now final). The third found only a test pattern tied to nanoarrow 0.9.0's wording, fixed after it. The default path is unchanged: DBItest output is byte-identical to the base, and dbFetch() costs about 1 µs more per call for the mixed-fetch check (about 25 µs for dbFetch(res, 1)). valgrind found nothing on any reproducer of the three rounds. This copy replaces the previous one: each limitation links its question, and the note on the CI matrix is dropped, since #853, which blocked it, is merged and this branch includes it. These remain:

  • R/arrow-stream.R#L20-L40: one result can't mix data-frame and Arrow fetches; the first kind claims it for its lifetime, also across dbBind(). This follows the mixed-fetch question, resolved as "no". Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L13-L19: the stream keeps reading when R garbage-collects the result object without dbClearResult(), since it holds a share of the result; question. Relevance: low; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L20-L21: the callbacks call R and must run on R's main thread, and a release() that drops the last share destroys the result where it runs; question. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L186-L189: an R error that leaves a callback by a jump bypassing cpp11 still skips the C++ destructors of that callback's body, while the stream's state stays consistent; question. Relevance: low; reviewer's confidence: high (recorded).

Found here, but on main too:


Generated by Claude Code

A stream raises a parameter that its read-ahead could not bind
with its next chunk, and completes the result.
A row held back for the byte limit of a chunk starts the next chunk.
Running out of memory while reading a value fails the stream
with an error of the stream, completes the result, and stays final.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: refuse a second Arrow stream on a result that already has one?

The clean review of 2026-11-29 rated this Low. read_arrow_stream() checks only that a result is not also fetched as data frames (R/arrow-stream.R#L16), so two streams can be opened on one result. They then take turns fetching its chunks, and each silently gets only part of the rows. The reviewer's reprex: five rows, n = 2; s reads its schema, which fetches the first chunk, then s2 <- read_arrow_stream(r, 2L); s2$get_next() returns rows 1 and 2, the chunk s had kept for itself, and s$get_next() starts at row 3. No error or warning is raised. This session did not run it.

Refusing a second stream while one is open, with an error like "This result is already read by an Arrow stream.", costs a flag or a count on the result next to claim_fetch_kind() and a test; a stream that has ended or been released frees the result for a new one. Leaving it allows a pattern that always loses rows.

  • Refuse a second stream while one is open on the result (recommended: no row is lost unseen, and the case has no use)
  • Allow it, and document that the streams share the result's rows
  • Accept it as a limitation of this pull request

The fix 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.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Three clean review rounds: the first of the whole pull request at 89e2751, the second of a0f7fee and the third of db5b47a. The first two found a crash when a handler releases the stream during its own callback (fixed by deferring the release and by failing every callback of a released stream with EINVAL) and a stream reporting a clean end after a failure (failures are now final). The third found only a test pattern tied to nanoarrow 0.9.0's wording, fixed after it. The default path is unchanged: DBItest output is byte-identical to the base, and dbFetch() costs about 1 µs more per call for the mixed-fetch check (about 25 µs for dbFetch(res, 1)). valgrind found nothing on any reproducer of the three rounds. This copy replaces the previous one: each limitation links its question, and the note on the CI matrix is dropped, since #853, which blocked it, is merged and this branch includes it.

The clean review of 2026-11-29, after main (3.54.1) was merged up the stack, read this pull request at 7e1db95 and found nothing above Low that is new here. Its Medium, that an R error or interrupt in a callback leaves through the consumer's frames, is the case of the third and fourth items below, which defer it to pull requests 15 and 16. Two new Lows are 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:

  • R/arrow-stream.R#L20-L40: one result can't mix data-frame and Arrow fetches; the first kind claims it for its lifetime, also across dbBind(). This follows the mixed-fetch question, resolved as "no". Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L13-L19: the stream keeps reading when R garbage-collects the result object without dbClearResult(), since it holds a share of the result; question. Relevance: low; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L20-L21: the callbacks call R and must run on R's main thread, and a release() that drops the last share destroys the result where it runs; question. Relevance: medium; reviewer's confidence: high (recorded).
  • src/SqliteArrowStream.cpp#L186-L189: an R error that leaves a callback by a jump bypassing cpp11 still skips the C++ destructors of that callback's body, while the stream's state stays consistent; question. Relevance: low; reviewer's confidence: high (recorded).
  • R/arrow-stream.R#L16: two streams can be opened on one result and silently share its rows (question). Relevance: low; reviewer's confidence: high.
  • src/SqliteArrowStream.cpp#L275: a stream still alive when RSQLite is unloaded crashes R at the next garbage collection, as an Arrow chunk does (question on #859); a connection or result of RSQLite 3.54.1 survives the same unload. Relevance: low; reviewer's confidence: high.

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Finding: A stream created before the first dbBind() can never be read, and its error blames a rebind

StreamState records result->executions() when the stream is created (src/SqliteArrowStream.cpp:46 at 8e6fe0de), and checked_result() refuses to read once that number changes (:77). A stream created on a parameterized result that hasn't been bound yet starts at 0 executions. The first dbBind() then makes it unreadable, although the stream has read nothing and there were no earlier parameters. The message says "bound to new parameters", which is misleading. Reading the same stream without binding gives "Query needs to be bound before fetching". Binding first and creating the stream afterwards works.

This happens on #864 (7e1db95) and at the top of the stack (#867, 8e6fe0d). Severity: low, because the entry point is still internal. It will matter once dbSendQueryArrow() plus dbBind() exposes it.

con <- dbConnect(RSQLite::SQLite())
rs <- dbSendQuery(con, "SELECT ? AS x")
s <- RSQLite:::read_arrow_stream(rs)   # created before the first bind, nothing read
dbBind(rs, list(1))
tryCatch(nanoarrow::convert_array_stream(s), error = conditionMessage)
#> [1] "array_stream->get_schema(): [5] Can't read an Arrow stream after its result has been bound to new parameters."
# Expected: a data frame with x = 1, or a refusal at creation ("Query needs to be bound")

Possible fixes:

  • Refuse to create a stream on a result that still needs binding, with the "Query needs to be bound" message (recommended)
  • Let a stream that has not read anything follow the first bind

Found while mapping this stack onto RMariaDB (r-dbi/RMariaDB#596); checked by building this PR's head and the stack's top.


Generated by Claude Code

The claim of a result for one kind of fetch now lives in `DbResult::claim_fetch_kind()` below.
The stream claims the result for Arrow arrays when it is created, as the Arrow chunks do,
and the R function `claim_fetch_kind()` with `result_claim_fetch_kind()` is gone.
The errors read "Can't fetch a result as a data frame after fetching it as Arrow arrays." and the converse.

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