Skip to content

feat: Add internal lazy Arrow fetching, gated by a nanoarrow capability check - #783

Draft
krlmlr wants to merge 5 commits into
mainfrom
claude/lazy-arrow-fetch
Draft

krlmlr wants to merge 5 commits into
mainfrom
claude/lazy-arrow-fetch

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

This PR carries #769 by eitsupi (branch eitsupi/DBI:feat/lazy-arrow-fetch, head 0874a09) with its three commits and authorship unchanged, followed by a merge of current main and a rework that follows Kirill's decisions on this PR.

Origin

What the PR does now

  • DBI's default dbFetchArrow(), dbGetQueryArrow(), and dbReadTableArrow() behave exactly as on main: eager, and dbGetQueryArrow() clears its result on exit. Their documentation is unchanged from main.
  • The lazy machinery from feat: fetch Arrow results lazily in the default dbFetchArrow() and dbGetQueryArrow() methods #769 is kept as internal code: fetch_arrow_stream(res, owned, lazy = FALSE) and get_query_arrow(conn, statement, ..., lazy = FALSE). The remaining chunks are fetched on demand through nanoarrow::function_array_stream(), and an owned result is cleared at the end of the stream, on error, or on release. No public method reaches it yet.
  • has_lazy_arrow() checks the capability itself, not the version: nanoarrow must export function_array_stream(), and a one-batch probe stream must read back correctly. The result is cached per session. It is FALSE on CRAN nanoarrow 0.9.0 and TRUE on the development version. Without the capability, lazy requests fetch eagerly.
  • DESCRIPTION equals main's: no Remotes, nanoarrow (>= 0.3.0.1) in Suggests.
  • Tests: lazy tests skip unless has_lazy_arrow() holds, so they run in the rcc dev workflow, which installs development versions of dependencies. New tests pin the eager defaults: dbHasCompleted() after dbFetchArrow(), overwriting a table from its own dbReadTableArrow() stream, and clearing a result before consuming its stream.

Status

🤖 Generated with Claude Code

https://claude.ai/code/session_01Hr1rd4HRcA4823NuBCC8TS

eitsupi and others added 4 commits October 22, 2026 15:12
…GetQueryArrow()

The default dbFetchArrow() method used to fetch all chunks of a result before
returning a stream. It now fetches the first chunk to determine the schema and,
if more rows remain, returns a stream that fetches the remaining chunks only
when it is consumed. This uses nanoarrow::function_array_stream() and falls back
to the previous eager behavior if the installed nanoarrow does not provide it.

The default dbGetQueryArrow() method transfers the ownership of the result to
the returned stream when the default dbFetchArrow() method is used. The result
is cleared when the stream reaches the end, when fetching fails, or when the
stream is released. Results that fit into one chunk are still cleared right
away, and backends with their own dbFetchArrow() method keep the previous
behavior.

The development version of nanoarrow is required for the new behavior, so it is
temporarily added to Remotes.
The default dbFetchArrow() and dbGetQueryArrow() methods fetch the remaining
chunks lazily by default. Setting options(DBI.lazy_arrow = FALSE) restores the
previous behavior: all chunks are fetched before the stream is returned, and
dbGetQueryArrow() frees the result right away.

The option must be TRUE or FALSE; other values are an error. It is read once
when the stream is created, so changing it later does not affect existing
streams. Backends with their own dbFetchArrow() method are not affected.
Resolve the conflict in DESCRIPTION by keeping both the rmarkdown
vignette builder from main and the nanoarrow Remotes entry from #769.

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

krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: Global option, per-query argument, or per-connection control for lazy Arrow fetching?

In #769, Kirill asked whether the control should be per connection or even per query. The PR currently reads only the global option DBI.lazy_arrow once when the stream is created (use_lazy_arrow(), called from dbGetQueryArrow()). A single query can already be switched with withr::with_options(). The contributor proposed in #769 to keep the option as the global default and add a named lazy argument after ... to the default dbFetchArrow(), dbGetQueryArrow(), and dbReadTableArrow() methods, without changing the generics, and to leave per-connection defaults to backends (for example a dbConnect() argument). Backends with their own dbFetchArrow() (adbi, duckdb) would ignore lazy either way.

  • Option as global default plus a lazy argument on the default methods only, no generic change (recommended): per-query control at little cost, no interface change for backends.
  • Keep the global option only: smallest change; per-query control via withr::with_options().
  • Add per-connection control in DBI (e.g. a common connection-level setting): most flexible, but a new interface every backend would have to understand.
  • Superseded by Kirill's later decision, relayed from the session chat: "The default should be FALSE, no option, only dbConnect() arguments." No global option and no per-query argument; lazy fetching is enabled per connection only. How DBI's default methods learn that setting is asked separately.

Kirill decides. If nobody decides, the PR stays as is (global option only) and is not merged.


Generated by Claude Code

krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: Should lazy fetching be on by default (DBI.lazy_arrow = TRUE)?

use_lazy_arrow() defaults to TRUE. For results larger than one chunk, the result then stays open on the connection until the stream is consumed or released. On single-result backends (RSQLite, and any backend relying on DBI's default Arrow methods), a second query on the same connection invalidates the stream, e.g. dbWriteTableArrow(con, ..., dbGetQueryArrow(con, ...)). This changes behavior for every caller of the default methods across DBI's reverse dependencies. In #769, Dewey Dunnington suggested starting opt-in and moving to opt-out later, or going straight to opt-out; the contributor chose opt-out so that the lazy path gets exercised.

  • Default FALSE (opt-in) for now, flip to TRUE in a later release after downstream checks (recommended): no behavior change for existing code; lazy path available to those who ask for it.
  • Default TRUE (opt-out), as in feat: fetch Arrow results lazily in the default dbFetchArrow() and dbGetQueryArrow() methods #769: users get the memory and latency benefit at once, at the risk of breaking the same-connection pattern above.
  • Default TRUE, but only after a reverse-dependency check shows no breakage.
  • Default FALSE, with no option: decided by Kirill, relayed from the session chat ("The default should be FALSE, no option, only dbConnect() arguments.").

Kirill decides. If nobody decides, the PR stays as is (TRUE) and is not merged. The clean review's findings on this follow in a separate comment.


Generated by Claude Code

krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: How to handle the dependency on development nanoarrow (Remotes, nanoarrow (>= 0.9.0.9000))?

DESCRIPTION requires nanoarrow (>= 0.9.0.9000) in Suggests and adds a Remotes: nanoarrow=apache/arrow-nanoarrow/r entry, because nanoarrow::function_array_stream() (apache/arrow-nanoarrow#975) is not on CRAN yet. CRAN does not accept a Remotes field or a Suggests requirement no CRAN version satisfies, so main cannot be released while these are in. The code itself falls back to eager fetching when function_array_stream() is not exported (has_function_array_stream()), so the version bump is needed only for the tests and CI. Whether this goes into the next CRAN release is asked in #781.

  • Keep both entries, and hold this PR until a nanoarrow release with function_array_stream() is on CRAN; then drop Remotes and require that version (recommended): main stays releasable.
  • Merge with Remotes and the dev requirement now, and drop them before the next CRAN release, as done before in a091ecc: earlier exposure, but main is blocked for CRAN until nanoarrow releases.
  • Drop Remotes and the version requirement now, keep the runtime fallback, and skip the lazy tests when function_array_stream() is missing: releasable at once, but CI on CRAN nanoarrow does not exercise the lazy path.

Decided by Kirill, relayed from the session chat: "Can we implement a runtime check for the nanoarrow package that checks precisely if the capabilities are available (fail on 0.9.0, succeed in the dev version)? [...] Remove from the remote, skip tests if not yet available (gated by our "dev" checks)." The lazy tests then run in the rcc dev workflow, which installs the development version of each dependency.


Generated by Claude Code

@krlmlr krlmlr mentioned this pull request Nov 28, 2026
3 of 7 tasks

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Clean review, round 1 (at 981a130)

Reviewed by an agent without context from the work, briefed with the risks of the default change, single-result backends, resource lifetime, downstream impact, and the dev-nanoarrow dependency. Reproduced on RSQLite with 1000 rows (chunk size 256), dev nanoarrow 0.9.0.9000 vs CRAN nanoarrow 0.9.0.

High (all on the lazy path only; with CRAN nanoarrow or options(DBI.lazy_arrow = FALSE) every case behaves as on main)

  1. dbWriteTableArrow(con, "big", dbReadTableArrow(con, "big"), overwrite = TRUE) warns Closing open result set, pending rows, then fails with Invalid result set; the original table is already dropped and the new one holds 256 of 1000 rows. Data loss.
  2. dbWriteTableArrow(con, "copy", dbGetQueryArrow(con, "SELECT * FROM big")) fails the same way and leaves "copy" with 256 rows. Cause: DBI's own default dbExistsTable(), dbCreateTableArrow() and dbAppendTable() query the connection before the stream is consumed. Any interleaved query or dbExecute() has the same effect.
  3. Clearing the result before consuming now fails: s <- dbFetchArrow(res); dbClearResult(res); as.data.frame(s), or a function with on.exit(dbClearResult(res)) that returns dbFetchArrow(res) — the idiom dbGetQueryArrow() itself used on main. dbFetchArrow() is lazy even without ownership.
  4. Streams consumed off the R main thread fail: duckdb::duckdb_register_arrow() on a dbGetQueryArrow() stream gives Can't evaluate R callback on a non-R thread, because function_array_stream() calls back into R. arrow::as_arrow_table() still works.
  5. dbBind() on a result whose stream is unconsumed silently returns mixed data (266 rows: first chunk of binding 1 plus binding 2), no error.

Medium

  1. dbHasCompleted(res) after dbFetchArrow(res) is now FALSE when more than one chunk remains.
  2. Fetch errors move from call time to consumption time and lose their condition class (nanoarrow turns them into an IOError string), so tryCatch() around dbGetQueryArrow() no longer catches them.
  3. dbDisconnect() with an unconsumed stream warns about a result in use; each new lazy query silently kills the previous stream with a warning.
  4. DESCRIPTION cannot go to CRAN (see the nanoarrow question above). The version bump is not needed by the code, which checks for the function, not the version.

Low

  1. Tests skip by nanoarrow version while the code checks function existence.
  2. dbGetQueryArrow() no longer forwards ... to the fetch (the default method ignores it anyway).

Correct as written: zero-row, single-chunk and option-FALSE fallbacks; the option is validated and read once; release, GC and end of stream each clear the result exactly once.

Tests: test-arrow.R passes with dev and with CRAN nanoarrow (lazy tests skip on CRAN). Full devtools::test() with dev nanoarrow: 711 results, 0 failures, 59 skips. DBItest on RSQLite does not catch High 1–5. No test covers a second query on the same connection, the write/read round trip, clearing before consuming, dbBind() before consuming, disconnecting first, or non-R-thread consumers.

Not checked: backends other than RSQLite and duckdb, interrupts during a lazy fetch, finalizers at session exit, an actual reverse-dependency run.

How to address High 1–5 is asked in the next comment.


Generated by Claude Code

krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Resolved: How to address the five High findings of the clean review?

All five High findings above (data loss in dbWriteTableArrow(con, x, dbReadTableArrow(con, x), overwrite = TRUE), truncated copies, clearing before consuming, non-R-thread consumers such as duckdb, silent wrong data after dbBind()) occur only on the lazy path, which use_lazy_arrow() turns on by default. They are inherent to a stream that keeps the result open, so no local patch removes them while lazy stays the default. This changes the contributor's design, so it is left to Kirill and not fixed here.

  • Make lazy opt-in: default DBI.lazy_arrow = FALSE, plus the per-query lazy argument if chosen above, and document the five pitfalls for those who opt in (recommended): main behavior is unchanged for all ~900 reverse dependencies, the feature remains available.
  • Opt-in as above, and additionally make dbFetchArrow() eager unless called from dbGetQueryArrow()/dbReadTableArrow() with ownership, which removes High 3 and 5 even for those who opt in.
  • Keep lazy as the default and mitigate in DBI, e.g. materialize the input stream in the default dbWriteTableArrow()/dbAppendTableArrow() before touching the connection: fixes High 1–2 for DBI's own writer only; High 3–5 and third-party writers stay broken.
  • Return the review to the contributor on feat: fetch Arrow results lazily in the default dbFetchArrow() and dbGetQueryArrow() methods #769 and wait.
  • Settled by Kirill's decision, relayed from the session chat ("The default should be FALSE, no option, only dbConnect() arguments."): since 19c4bb2 the default methods are eager as on main, and tests pin High 1 and 3 on the default path. The findings come back only for connections that opt in, and how that opt-in reaches DBI is open; the recommended hook keeps dbFetchArrow() eager, which rules out High 3 and 5 there too.

Kirill decides, and what is said on #769 is his call. If nobody decides, the PR stays a draft with these findings open and is not merged.


Generated by Claude Code

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Question: How do DBI's default methods learn the per-connection dbConnect() setting?

Kirill decided (relayed from the session chat): lazy fetching is off by default, with no option and no per-query argument, and is enabled only through dbConnect() arguments. DBI does not implement dbConnect() for any backend, and the default dbFetchArrow() method only sees the result, not the connection, so DBI needs some hook to learn what the backend's dbConnect() was told. Until this is decided, the branch keeps the lazy machinery reachable only internally (and in tests), so the default methods behave exactly as on main.

  • A new generic, e.g. dbArrowLazy(conn), with a default method returning FALSE; a backend stores its dbConnect(..., lazy_arrow = FALSE) argument and overrides this one method. Only the default dbGetQueryArrow() and dbReadTableArrow(), which own their result, consult it; the default dbFetchArrow() stays eager (recommended): one small method per backend, and High 3 (clearing before consuming) and High 5 (dbBind() before consuming) of the clean review cannot occur, since no user holds the result.
  • No generic: DBI exports the lazy machinery as a documented helper (e.g. dbGetQueryArrowLazy()), and a backend calls it from its own dbGetQueryArrow() method when its dbConnect() argument says so: no new generic, but each backend writes and maintains its own method.
  • Leave it entirely to backends: DBI ships nothing lazy, and the code from feat: fetch Arrow results lazily in the default dbFetchArrow() and dbGetQueryArrow() methods #769 becomes a recipe for backends without native Arrow support: smallest DBI change; the work in feat: fetch Arrow results lazily in the default dbFetchArrow() and dbGetQueryArrow() methods #769 is not used by DBI itself.

Kirill decides. If nobody decides, the default methods stay eager and the lazy path stays unreachable outside tests.


Generated by Claude Code

…pability check

This follows Kirill's decision on PR #783.
The default `dbFetchArrow()`, `dbGetQueryArrow()`, and `dbReadTableArrow()` methods fetch eagerly again,
exactly as on main, and their documentation matches main.
The `DBI.lazy_arrow` option is gone, and no per-query argument replaces it.

The lazy machinery stays as internal code, reachable through a `lazy` argument
of the internal `fetch_arrow_stream()` and `get_query_arrow()` functions.
Lazy fetching needs `nanoarrow::function_array_stream()`.
The internal `has_lazy_arrow()` checks that it is exported and that a one-batch stream built with it can be read back,
and caches the result per session.
Requesting lazy fetching without that capability falls back to eager fetching.

DESCRIPTION drops the `Remotes:` field and requires nanoarrow (>= 0.3.0.1) again.
The lazy tests call the internal functions and are skipped when the capability is missing.
New tests check that the default methods are eager,
and that the capability check is FALSE when `function_array_stream()` is not exported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4HRcA4823NuBCC8TS
@krlmlr krlmlr changed the title feat: Fetch Arrow results lazily in the default dbFetchArrow() and dbGetQueryArrow() methods feat: Add internal lazy Arrow fetching, gated by a nanoarrow capability check Nov 28, 2026

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Clean review, round 2 (19c4bb2 only)

Scope: the rework commit 19c4bb2; the rest of the PR was context. No High or Medium findings, so the review stops here.

Checked and correct

  • git diff origin/main 19c4bb2 -- DESCRIPTION man is empty; public signatures and the eager default paths match main.
  • The internal lazy cannot be reached through ... of any public method, and it sits after ... in get_query_arrow(), so no partial matching.
  • has_lazy_arrow() is TRUE on nanoarrow 0.9.0.9000 and FALSE on 0.9.0; with nanoarrow missing it returns FALSE without a warning.
  • An owned lazy result is cleared exactly once on end, error, interrupt, release and GC; GC after dbDisconnect() with a half-read stream is silent.
  • Tests are standalone, mocks are undone, the capability cache is restored.

Results

  • test-arrow.R: dev nanoarrow 0 failures, 0 skips; CRAN 0.9.0 0 failures, 4 lazy tests skipped.
  • R CMD check --no-manual --ignore-vignettes with CRAN 0.9.0: no warnings, one NOTE about a hidden .git that comes from building inside a worktree; no undefined-global notes.

Low (each with its own question below)

  1. The capability result is cached for the session.
  2. The check catches errors but not warnings from loading nanoarrow's namespace.
  3. In get_query_arrow(), ownership is recorded only after the fetch returns, so a failure right after the internal clear would clear twice.

Not checked: R CMD check with dev nanoarrow, a real install without nanoarrow, backends other than RSQLite.


Generated by Claude Code

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Question: Keep caching the nanoarrow capability check for the whole session?

has_lazy_arrow() caches its first answer. If lazy fetching is requested before nanoarrow is installed or upgraded in the same session, the answer stays FALSE until DBI is reloaded. Only the internal lazy path is affected, and upgrading a loaded package needs a restart anyway.

  • Keep the session cache and accept this (recommended): one probe per session, no cost per query.
  • Cache only a TRUE answer, and re-probe while the answer is FALSE: picks up an install made in the session, at the cost of a failed probe on every lazy request with old nanoarrow.

Kirill decides. If nobody decides, the cache stays as is.


Generated by Claude Code

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Question: Suppress warnings from loading nanoarrow during the capability check?

The capability check catches errors but not warnings. The first getNamespaceExports("nanoarrow") loads the namespace, so a load-time warning (such as "package built under R version x.y") can reach the caller once per session.

  • Leave it (recommended): the same warning would appear on any other use of nanoarrow, and hiding it hides a real hint about the installation.
  • Wrap the check in suppressWarnings(): silent, but it also hides warnings from the probe stream.

Kirill decides. If nobody decides, the check stays as is.


Generated by Claude Code

krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Question: Record ownership before the fetch in get_query_arrow()?

In get_query_arrow(), owned <- TRUE is set only after fetch_arrow_stream() returns. If basic_array_stream() failed after the internal dbClearResult(), on.exit() would clear the result a second time. With validate = FALSE this failure is very unlikely, and the code is reachable only internally.

  • Accept it for now and revisit it when the lazy path is wired to dbConnect() (recommended): no change to code that no public method reaches yet.
  • Guard the on.exit() clear with dbIsValid(rs) now: a one-line fix, at the cost of another review round.

Kirill decides. If nobody decides, the code stays as is.


Generated by Claude Code

krlmlr commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.


Generated by Claude Code

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Question: Accept the codecov failure, or measure coverage with development nanoarrow?

codecov/patch (23.94% of the diff hit, target 64.83%) and codecov/project (62.00%, −2.83%) fail on 19c4bb2. All other checks pass. The cause is the decision to gate the lazy tests on has_lazy_arrow(): the coverage run installs CRAN nanoarrow 0.9.0, so the lazy tests skip and the internal lazy machinery counts as uncovered. Locally, with development nanoarrow, all lazy tests run and pass. The lazy tests are meant to run in the rcc dev workflow, which does not report coverage.

  • Accept the red codecov checks until a nanoarrow release with function_array_stream() reaches CRAN (recommended): no CI change; coverage recovers by itself once CRAN nanoarrow has the capability.
  • Install development nanoarrow in the coverage job only (e.g. through the coverage workflow's extra packages): green codecov now, but coverage then measures a dependency setup that CRAN users don't have.
  • Exclude the lazy machinery from coverage (# nocov markers) until nanoarrow releases: green now, at the cost of markers to remove later.

Kirill decides. If nobody decides, codecov stays red on this draft and nothing changes.


Generated by Claude Code

krlmlr commented Nov 28, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations


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.

3 participants