Skip to content

feat: Report values converted to an Arrow column's type once per chunk, with their rows - #862

Draft
krlmlr wants to merge 12 commits into
claude/arrow-date-columnsfrom
claude/arrow-coercion-reports
Draft

krlmlr wants to merge 12 commits into
claude/arrow-date-columnsfrom
claude/arrow-coercion-reports

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Seventh step of the Arrow rework (plan: #829 (comment)): the internal Arrow engine of #859, #860 and #861 now reports the values it converts to the type of their column, or makes NULL, with one warning per chunk. The entry point result_fetch_arrow_chunk() stays internal, so nothing changes for users.

What changes:

  • SqliteArrowColumn logs every value that feat: Build Arrow arrays from the integer, real and NULL columns of a result #859, feat: Build Arrow arrays from text and blob columns #860 and feat: Build Arrow date, time and timestamp arrays with extended_types #861 convert silently, in a new CoercionLog per column: grouped by storage class and what happened, with the count and the first five row numbers. Row numbers count from 1 across the whole result, as dbGetRowCount() counts rows, so a chunk after a data-frame fetch goes on from the rows of that fetch. Logging calls no R API. The groups:

    • converted, as SQLite converts: a real truncated in an int64 column fixed by the first chunk, text and blobs read as numbers, numbers rendered as text, text in a binary column, and a blob of valid UTF-8 in a utf8 column. This includes values of another storage class within the first chunk, after the first value has decided the type. Text and blobs that an open int64 column reads as beyond its range take their reading as reals when a real widens the column later in the chunk (feat: Build Arrow arrays from text and blob columns #860), and the log then counts them as converted.
    • out of range, NULL instead: a real, or the leading integer of text or a blob, beyond int64; a count of days beyond date32; seconds beyond int64 microseconds, or an infinity; a time outside the day, as a number or as text.
    • not valid UTF-8 or with a NUL byte, NULL instead: text and blobs in a utf8 column.
    • not parsable, NULL instead: text that isn't a date or time, and any blob, in a date or time column.
    • dropped by the null type: any value in a column of the null type.

    Not reported, since dbFetch() reads them the same way without a warning: integers in a double column, integers widened to double within the first chunk, and numbers within the range of a date or time column.

  • Once the chunk is complete, SqliteResultImpl::fetch_arrow_chunk() hands the logs to warn_coercion() in the new R/warn-coercion.R, which raises one warning of class RSQLite_warning_coercion with a line per column, and carries the logs in its coercions field:

    * Column `i` (int64): 2 text values converted (rows 3 and 5); 1 real value converted (row 4)
    * Column `s` (utf8): 1 blob value not valid UTF-8 or with a NUL byte, NULL instead (row 3); 2 integer values converted (rows 4 and 5)
    * Column `b` (binary): 1 text value converted (row 3); 1 integer value converted (row 5)
    * Column `n` (null): 1 integer value dropped by the null type (row 3); 1 text value dropped by the null type (row 4) ```
    
    The groups of a column come in the order of their first rows. More than five rows end in `...` after the first five; row numbers are printed in full, `100000` and not `1e+05`. The condition is built and signalled with base R's `warning()`, not `rlang::warn()`, which made each warning cost about 0.4 ms instead of 0.05 ms.
    
  • The warning is raised after fetch_loop() has returned and the struct array is assembled, never while values are read: no R code runs while a chunk is half-built, and an error made of the warning doesn't pass the handler of the fetch loop, which ends the result. It is raised while the busy guard of fix: Never restart a statement after an error in dbFetch() or dbBind() #830 still holds the result: a handler can read dbGetRowCount() and dbHasCompleted(), while fetching from, binding or clearing the result fails with the guard's error, such as "Can't clear a result while one of its fetches or binds is running, as from a handler of a warning that it raised." Raising it from R after the entry point has returned would let a handler clear the result between building the chunk and handing it out.

  • The chunk stays in the result until it is handed out. When the warning exits instead of returning, because options(warn = 2) turns it into an error ("(converted from warning) Values converted to the Arrow type of 1 column: ..."), a handler signals an error (the guard's included) or an exiting handler catches it, the error reaches the caller and the chunk is kept. The next result_fetch_arrow_chunk() hands it out without warning again, whole, whatever its n: after a fetch of 100 rows whose warning failed, a fetch of 1 row returns those 100 rows. The fetches after it go on with the next rows, so no row is lost. Until then its rows don't count: dbGetRowCount() leaves them out and dbHasCompleted() is FALSE, so a loop until dbHasCompleted() gets them. dbFetch() refuses with "Can't fetch a data frame before the Arrow chunk that was kept when the warning about its values exited.", since its rows would come out before the earlier rows of the kept chunk, and dbBind() drops the kept chunk with the rest of the execution. The same counting holds while a handler runs.

  • Each chunk starts with empty logs, so a fetch that fails after converting values (a step error, an interrupt) doesn't report them with the next fetch. A value that runs out of memory while it is read is an error that fails its chunk (feat: Build Arrow arrays from text and blob columns #860, feat: Build Arrow date, time and timestamp arrays with extended_types #861), not a conversion: the log notes a value only after reading it, and goes with the failed chunk.

  • The simpler alternative, for the maintainers to choose: raise the warning inside the try of the fetch loop, so that a warning that exits ends the execution, as an error of dbFetch() does, with its warning turned into an error by options(warn = 2). That drops KeptArrowChunk and its special cases in complete(), n_rows_fetched(), fetch() and bind(), about 50 lines with their tests, and the n of a fetch would always hold. The cost: the rows of the chunk are lost, and so are the remaining rows of the result, so that with options(warn = 2) the first chunk with a conversion ends the read. The open question of mixing data-frame and Arrow fetches on one result may settle it too.

  • SqliteResultImpl.h keeps nanoarrow out, as feat: Build Arrow arrays from the integer, real and NULL columns of a result #859 has it: the kept chunk lives behind the forward-declared KeptArrowChunk, defined in SqliteResultImpl.cpp.

The design comes from #800 (ef68461: CoercionLog, R/warn-coercion.R), with its refinements 7f6a01e (the log of a failed fetch is discarded), 1fcf5a4 (row numbers in full), 4a4e580 (values of the null type reported as dropped) and a5f157a (rlang::warn() without call), applied to the Arrow path only. Where it differs:

The data-frame path is unchanged: dbFetch() keeps its "mixed type" and date warnings exactly as they are, raised while it reads. Extending the per-fetch report to dbFetch() would be a separate, user-visible change, also for the data frames that pull requests 19 and 20 build through Arrow, for which #800 warned once per dbFetch().

Deliberately left out:

Tested:

  • New tests/testthat/test-arrow-coercion.R with a snapshot of the message (_snaps/arrow-coercion.md): several columns with several groups at once, and the coercions field; one block per kind of conversion: reals truncated and values beyond int64, text beyond int64 that a later real in the chunk turns into a converted real, the null type, text, blobs and numbers converted between utf8, binary and double with invalid UTF-8 and a NUL byte, and unparsable and out-of-range dates, times and timestamps; 30 values (the list shortened) and rows 100000 and 123456 in full, with numbers beyond 2^31 formatted directly; row numbers in later chunks and after a dbFetch() in between; options(warn = 2): the error, dbGetRowCount(), dbHasCompleted() and dbFetch() meanwhile, the kept chunk handed out by the next fetch and the rest after it; a calling handler that muffles, which gets the chunk and sees the result busy; a handler that clears the result, refused by the guard, with the chunk kept; a new bind dropping a kept chunk; a step error after a converted value, not reported by the next fetch; and no warning when nothing is converted: widening within a chunk, integers in a double column, NULL, all-NULL columns and dates as numbers and text, in one chunk and in chunks of one row.
  • tests/testthat/helper-arrow.R: fetch_arrow_chunk() and fetch_arrow_all() take converted = TRUE to expect the warning, and expect_same_chunks() lets it through where it already allows dbFetch()'s warnings (mixed = TRUE, unparsable = TRUE); warnings_of() and expect_coercions() collect and check the warnings. The fetches in test-arrow-columns.R, test-arrow-text.R and test-arrow-dates.R that convert values now expect the warning; their values are unchanged.
  • Each test_that() block of the four Arrow test files and test-extendedTypes.R passes on its own in a fresh session right after pkgload::load_all(); the two out-of-memory blocks skip there, since their callr sessions need an installed build.
  • Against an installed build, the four Arrow test files and test-extendedTypes.R pass, the out-of-memory blocks of test-arrow-text.R and test-arrow-dates.R included.
  • Mutations, each caught by the new tests: leaving values beyond int64 as out of range when a real widens the column, merging their rows out of order, or putting the merged group in the slot of the later one, keeping the log of a failed fetch for the next one, counting a kept chunk in dbHasCompleted() or dbGetRowCount(), keeping it across dbBind(), letting dbFetch() run before it, and numbering rows from the start of each chunk.
  • Before the merge of feat: Build Arrow date, time and timestamp arrays with extended_types #861's latest head: under AddressSanitizer (gcc, -O1), test-arrow-coercion.R, test-arrow-columns.R, test-arrow-text.R, test-arrow-dates.R, test-read-ahead.R, test-dbSendQuery.R, test-dbClearResult.R, test-error.R, test-dbBind.R and test-extendedTypes.R pass without a report, and so does a script with chunks of several sizes and conversions in every column; warnings turned into errors, refused by the guard and caught by exiting handlers; kept chunks handed out, dropped by dbBind(), by dbClearResult() and with the result after dbDisconnect(); and chunks converted after their connection was closed, also under gctorture(TRUE).
  • Before the merge of feat: Build Arrow date, time and timestamp arrays with extended_types #861's latest head: devtools::test() with NOT_CRAN=true: no failures beyond the three errors in test-httpvfs.R that also happen on main (test: Run the HTTP VFS tests for real, and make their errors fail the check #832, testthat hides a test's error when the test records another result after it #837).
  • Before the merge of feat: Build Arrow date, time and timestamp arrays with extended_types #861's latest head: R CMD check --no-manual on a built tarball, with tests and vignettes and NOT_CRAN=true: Status: OK. DESCRIPTION only gains warn-coercion.R in Collate, from devtools::document().

Cost of a chunk without conversions, measured before the merge of #861's latest head, one million rows from a file database in one chunk, median of nine runs, three rounds alternating between #861 and this branch, -O2: int64 0.083 to 0.087 s on #861 and 0.083 to 0.089 s here, double 0.081 to 0.085 and 0.082 to 0.086, utf8 0.110 to 0.114 and 0.111 to 0.117, timestamps as text 0.67 to 0.72 and 0.69 to 0.73, the four columns together 0.89 to 0.91 and 0.88 to 0.91, and the four columns in 10000 chunks of 100 rows 1.09 to 1.11 and 1.09 to 1.12. Four more rounds of 21 runs gave 0.082 to 0.086 s for int64 alone on both, and 0.137 to 0.140 against 0.134 to 0.139 s with a double column next to it. The differences stay within the spread between rounds: logging costs a row number and a comparison per value, and the R call happens only for a chunk with conversions.

Cost of the warning, two million rows of an int64 column with text in every hundredth row, warnings muffled, median of five runs, three rounds: in chunks of 1000 rows 0.17 to 0.18 s on #861, 1.03 to 1.20 s through rlang::warn() and 0.29 to 0.30 s now; in chunks of 10000 rows 0.14 to 0.16, 0.26 to 0.29 and 0.16 to 0.18 s; in one chunk 0.14 to 0.16 s on all three. One call of warn_coercion() takes 0.40 to 0.45 ms through rlang::warn() and 0.045 to 0.050 ms now.

Sits on #861, which is on #860, #859, #857, #856, #855, #830 and #850, and merges #845.

Size

About 395 hand-written lines of C++: 185 in the new CoercionLog.cpp and .h, 110 in SqliteArrowColumn.cpp and .h, and 100 in SqliteResultImpl.cpp and .h; 73 lines of R in R/warn-coercion.R; and 415 lines of tests: 350 in test-arrow-coercion.R, 50 in helper-arrow.R and 20 in the three other Arrow test files. That is about 880 in all, above the plan's 600. Most of it is tests, one block per case of the plan, and the logging, the warning and the kept chunk don't make sense without each other, so the pull request is kept whole. The .dd files are written by hand (#836).

Review

The clean review found nothing above Low; its points are answered in ea9f836, and the design choice it raised is the first of the accepted limitations: uncheck it to switch to the simpler alternative.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

…k, with their rows

The Arrow columns of #859, #860 and #861 convert values that don't fit their type,
or make them NULL, without a trace.
Each column now logs them in a `CoercionLog`, by storage class and what happened,
with their count and the first five row numbers in the result, counted as `dbGetRowCount()` counts.
Once the chunk is complete and the fetch loop has returned,
`result_fetch_arrow_chunk()` raises one warning of class `RSQLite_warning_coercion` for them
through `warn_coercion()` in R, which carries the logs in its `coercions` field.

The warning comes while the busy guard still holds the result,
so that a handler can't clear it between building the chunk and handing it out.
The chunk is kept in the result until it is handed out:
if the warning exits, as with `options(warn = 2)` or a handler that signals an error,
the next fetch hands it out without warning again,
and until then `dbGetRowCount()` leaves its rows out, `dbHasCompleted()` is false and `dbFetch()` refuses.
A new bind drops it.

The design follows #800 (ef68461) for the Arrow path only;
the warnings of the data frame path are unchanged.
Fetches that convert values in the existing Arrow tests now expect the warning.

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

The base now keeps nanoarrow out of `SqliteResultImpl.h`,
so the chunk kept for the next fetch is held behind the forward-declared `KeptArrowChunk`.
Text and blobs that an open `int64` column saturates take their reading as reals when a real widens the column,
so the log moves them from out of range to converted.
A value that runs out of memory fails its chunk, which discards the log with it.
The fetches of the base's new tests that convert values expect the warning.

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

An open `int64` column now keeps the reading as a real only for text and blobs where it differs,
which includes every value beyond `int64`,
so the log still moves those from out of range to converted when a real widens the column.
The log notes a value only once it has been read, after any out-of-memory error.

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

krlmlr commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at a5442bd, by a Claude Code reviewer with clean context that read the description, the diff against #861 at 6d490fb (the feature commit 855ab08 and the merges 98c0a09 and a5442bd), the code around it (DbResult.cpp's busy guard, the fetch loop, result.cpp) and the tests, built both commits and an AddressSanitizer build, and ran the tests and its own reproducers. It posted nothing itself.

What was run

  • Both commits built into separate libraries, and an ASan and UBSan build of a5442bd (gcc, -O1).
  • The four Arrow test files and test-extendedTypes.R against both builds: all pass on the PR, the new expectations fail on the base; the base's Arrow test files against the PR build: all pass, so no value changed.
  • Each test_that() block of the four Arrow files alone in a fresh session right after pkgload::load_all(): 50 pass, the two out-of-memory blocks skip there (they pass against the installed build).
  • devtools::test() with NOT_CRAN=true: only the three test-httpvfs.R errors of test: Run the HTTP VFS tests for real, and make their errors fail the check #832 and testthat hides a test's error when the test records another result after it #837.
  • R CMD check --no-manual on a tarball built with vignettes, NOT_CRAN=true: Status: OK.
  • Under ASan: ten test files (the Arrow ones, read-ahead, dbSendQuery, dbClearResult, error, dbBind, extended types), the reproducers, and a script with conversions in every column, chunks of several sizes, kept chunks handed out, dropped by dbBind(), dbClearResult(), GC and dbDisconnect(), run once plainly and once under gctorture(TRUE). No ASan report; one UBSan report in code this pull request doesn't touch (SqliteColumnDataSource.cpp:92, memcpy() from NULL for an empty blob in dbFetch()).
  • Reproducers for the kept chunk, the log, the message, memory release (RSS), and timings of 2 million rows from a file database, alternating base and PR.

What holds

  • Every conversion of feat: Build Arrow arrays from the integer, real and NULL columns of a result #859, feat: Build Arrow arrays from text and blob columns #860 and feat: Build Arrow date, time and timestamp arrays with extended_types #861 is logged with its class and reason, and nothing dbFetch() reads silently is. Text and blobs beyond int64 become "converted" when a real widens the column: with six such values interleaved with six converted ones and a blob, the warning reads "12 text values converted (rows 2, 3, 4, 5, 6, ...); 1 blob value converted (row 14)", and without the real they stay out of range.
  • Row numbers count across the result: after a dbFetch(), after a kept chunk, and in later chunks.
  • The warning comes once per chunk, after the chunk is built, while the busy guard holds. Names with {x}, %s, backticks, a newline or non-ASCII characters print verbatim; rows print in full; the list is shortened after five rows.
  • The kept chunk loses no rows and duplicates none. With options(warn = 2) and n cycling through 10, 3, 50, 1, 200 and 7, a loop until dbHasCompleted() got all 1000 rows in order after 12 errors, with dbGetRowCount() equal to the rows received after every call. Exiting handlers, restarts and erroring handlers keep the chunk too. A read-ahead error comes after the kept chunk. dbFetch() refuses, and dbBind() drops the chunk. A bind refused for its parameter count keeps the old execution and its chunk, as it keeps the execution on the base.
  • The kept chunk is freed: RSS falls back to its level from before the chunk after dbClearResult(), after dbBind(), and after dbDisconnect() and dbClearResult(). GC frees it with the result.
  • The log stays bounded: 2 million conversions in one chunk peak at the same memory as the base, and RSS stays level over 12 repeated runs.
  • A chunk without conversions costs the same: three columns in one chunk took 0.362 to 0.375 s, against 0.364 to 0.374 s on the base.
  • A failed chunk's log is dropped. The data-frame path's warnings and its warn = 2 behaviour are identical to the base.
  • The .dd files hold relative paths only, and a fresh compile leaves the worktree clean. The description matches the code.

High

None.

Medium

None.

Low

  1. A kept chunk ignores the n of the fetch that hands it out, while the comments still say "at most n rows".

    // A chunk kept when its warning exited comes first, whatever `n_max`,
    // and without warning again
    if (!arrow_chunk_kept()) {
    if (arrow_columns_.empty()) {
    for (size_t j = 0; j < cache.ncols_; ++j) {
    arrow_columns_.push_back(new SqliteArrowColumn(
    stmt,
    static_cast<int>(j),
    cache.names_[j],
    with_alt_types_
    ));
    }
    }
    ArrowChunk chunk(arrow_columns_, n_max, nrows_);
    fetch_loop(chunk, n_max, [&] {
    chunk.finish(arrow_chunk_->array.get(), arrow_chunk_->schema.get());
    });
    // The warning comes once the chunk is complete and the fetch loop is left,
    // while the result stays busy, see run_guarded() in DbResult.cpp.
    // Its handlers can't find a chunk half-built,
    // and an error made of the warning, as with options(warn = 2),
    // or a handler that exits leaves the result as it is:
    // the chunk is kept and comes with the next fetch.
    warn_arrow_coercions();
    }
    arrow_chunk_->array.move(array);
    arrow_chunk_->schema.move(schema);
    ,
    // At most `n` rows, all of them for -1, as a nanoarrow_array of a struct type.
    ,
    // Fetches at most `n_max` rows, all of them if negative, into a struct array,

    (Confirmed) A fetch with n = 100 whose warning handler calls stop() is followed by a fetch with n = 1, which returns 100 rows. The description states this, but the entry point's comment and the header don't. Today the entry point is internal. It will matter once anything builds on its n, such as dbFetch(n) through Arrow in pull requests 19 and 20. The design is otherwise sound, and it is more forgiving than dbFetch(): with warn = 2, dbFetch() drops its rows and completes the result.

    Suggested fix: say "at most n rows, or all of a kept chunk" in both comments, and test a kept chunk longer than the next n. A simpler alternative is to raise the warning inside the fetch loop's try, so that an exiting warning ends the execution as it does for dbFetch(). That drops KeptArrowChunk and its special cases in complete(), n_rows_fetched(), fetch() and bind(), at the cost of the rows. It is the maintainers' call, and it may be settled by the open question of whether data-frame and Arrow fetches may be mixed on one result.

  2. Each warning costs about 0.4 ms, which dominates small chunks that have conversions.

    warn_coercion <- function(coercions) {
    n <- length(coercions)
    header <- paste0(
    "Values converted to the Arrow type of ", n,
    if (n == 1) " column:" else " columns:"
    )
    bullets <- vapply(coercions, format_coercion_column, character(1))
    rlang::warn(
    c(header, rlang::set_names(bullets, "*")),
    class = "RSQLite_warning_coercion",
    coercions = coercions
    )
    }

    (Confirmed) The test fetched 2 million rows of an int64 column holding text, muffling the warnings. In chunks of 1000 it took 1.03 to 1.27 s against 0.19 s on the base. In chunks of 10000 it took 0.28 s against 0.17 s, and in one chunk 0.23 to 0.26 s against 0.22 s. One warn_coercion() call takes 0.41 ms, against 0.19 ms for rlang::warn() and 0.02 ms for warning(). The cost doesn't matter for chunks of the usual size, but streams with small batches (pull request 9) would pay it per batch.

    Suggested fix: keep it if streams use large batches. Otherwise, signal the same condition object, with its class and coercions field, through warning(), and format the bullets in RSQLite.

  3. Merging "out of range" into "converted" can put the groups out of the order of their first rows.

    void CoercionLog::merge(
    int column_type,
    COERCION_REASON from,
    COERCION_REASON to
    ) {
    Entry* source = find(column_type, from);
    if (source == NULL) {
    return;
    }
    Entry* target = find(column_type, to);
    if (target == NULL) {
    source->reason = to;
    return;
    }
    target->count += source->count;
    // Each keeps its first rows in order,
    // so the first rows of both are the first of the two lists merged
    std::vector<int64_t> rows;
    std::merge(
    target->rows.begin(),
    target->rows.end(),
    source->rows.begin(),
    source->rows.end(),
    std::back_inserter(rows)
    );
    if (rows.size() > N_ROWS) {
    rows.resize(N_ROWS);
    }
    target->rows.swap(rows);
    entries.erase(entries.begin() + (source - &entries[0]));
    }

    (Confirmed) VALUES (1), ('99999999999999999999'), (x'00'), ('abc'), (2.5) warns "1 blob value converted (row 3); 2 text values converted (rows 2 and 4)". The merged text group takes the position of the later group, while every other group keeps the order of its first row.

    Suggested fix: when the source entry comes first, merge into the source's slot, or order the entries by their first row in as_list().

  4. A binary column logs a value before reading it, unlike the other branches that read one and the description ("the log notes a value only after reading it").

    case AK_BINARY:
    if (column_type != SQLITE_BLOB) {
    note(column_type, CR_CONVERTED);
    }
    check_arrow(
    ArrowArrayAppendBytes(array.get(), value_bytes(column_type)),
    "Can't append to Arrow array"
    );
    break;

    (by reading) note() runs before value_bytes(), which can stop because of an out-of-memory error. Nothing reaches a warning, because the failed chunk's log is cleared by the next start_chunk().

    Suggested fix: read value_bytes() into a local first, then note(), as append_string() does.


Generated by Claude Code

…row order

The review of #862 found four Low points.
`warn_coercion()` builds the condition and signals it with `warning()`,
with the same class, `coercions` field and message:
through `rlang::warn()` each warning took about 0.4 ms, now about 0.05 ms,
so that two million rows with conversions in chunks of 1000 take 0.30 s instead of 1.1 s, against 0.17 s without the report.
The bullets are `*` everywhere, as rlang drew them without cli.
A group of values beyond `int64` merged into the converted group when a real widens the column
takes the slot of the earlier of the two, so that the groups stay in the order of their first rows.
A `binary` column logs a value only after reading it, as the other columns do.
The comments of `result_fetch_arrow_chunk()` and `fetch_arrow_chunk()` say that a kept chunk comes whole, whatever `n`,
and the test of `options(warn = 2)` pins its length.

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

krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the new copy.

The clean review found nothing above Low: no row is lost or duplicated with options(warn = 2) and varying n, the kept chunk is freed on every path, the log is complete and bounded, the data-frame path's warnings are unchanged, and AddressSanitizer found nothing. Its four Lows are answered in ea9f836: the comments and a test say that a kept chunk comes whole whatever n, the warning is signalled with base R (about 0.05 ms instead of 0.4 ms per chunk), groups stay in the order of their first rows after a merge, and a binary value is logged after it is read. These remain:

  • src/SqliteResultImpl.cpp#L121: when the coercion warning of a chunk ends in an error (options(warn = 2), an erroring or exiting handler), the chunk is kept and the next fetch returns it whole, whatever its n; until then dbGetRowCount() leaves its rows out, dbHasCompleted() is FALSE, dbFetch() refuses, and dbBind() drops the chunk. The simpler alternative, raising the warning inside the fetch loop so that such an error ends the result as it does for dbFetch(), removes this machinery (about 50 lines with tests) but loses the chunk's rows and the rest of the result; the description lays out both. Uncheck this box to switch to the alternative. Relevance: medium; reviewer's confidence: high.
  • R/warn-coercion.R#L14: one warning per chunk still costs about 0.05 ms, so many small chunks with conversions are slower than without the report (2M rows with text in every hundredth row, chunks of 1000: 0.29 s against 0.17 s); one large chunk costs the same. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L586-L605: the report covers the Arrow path only; dbFetch() keeps its existing per-column warnings, and extending the per-chunk report to it would be a separate, user-visible change. Relevance: low; reviewer's confidence: high.
  • The full suite, AddressSanitizer and R CMD check ran before the merges of feat: Build Arrow date, time and timestamp arrays with extended_types #861 and the review fixes; the five Arrow test files pass after them, against an installed build too. Relevance: low; reviewer's confidence: medium.

Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Moved: should an Arrow chunk whose warning exits be kept for the next fetch, rather than end the result?

Moved to #880: #880 (comment). Please answer there.

When the coercion warning of a chunk ends in an error (options(warn = 2), an erroring or exiting handler), the chunk is kept and the next fetch returns it whole, whatever its n. Until then dbGetRowCount() leaves its rows out, dbHasCompleted() is FALSE, dbFetch() refuses, and dbBind() drops the chunk: src/SqliteResultImpl.cpp#L329-L354. The simpler alternative raises the warning inside the try of the fetch loop, so that such an error ends the result as it does for dbFetch(). That removes the kept chunk and its special cases in complete(), n_rows_fetched(), fetch() and bind(), about 50 lines with their tests, and the n of a fetch always holds; but the chunk's rows are lost, and so is the rest of the result, so that with options(warn = 2) the first chunk with a conversion ends the read. The mixed-fetch question is resolved as "no", so once #864 claims a result for a stream, the refusal of dbFetch() here no longer comes up there. Against this pull request's head, built from source:

library(DBI)
con <- dbConnect(RSQLite::SQLite())
dbExecute(con, "CREATE TABLE t (id INTEGER, x)")
#> [1] 0
dbExecute(con, "INSERT INTO t VALUES (1, 1), (2, 2), (3, 'three'), (4, 4), (5, 5)")
#> [1] 5
res <- dbSendQuery(con, "SELECT x FROM t ORDER BY id")
fetch_chunk <- function(n) {
  nanoarrow::convert_array(RSQLite:::result_fetch_arrow_chunk(res@ptr, n))$x
}

# The warning about the text in row 3 becomes an error
options(warn = 2)
try(fetch_chunk(4))
#> Error : (converted from warning) Values converted to the Arrow type of 1 column:
#> * Column `x` (int64): 1 text value converted (row 3)

# The chunk is kept: its rows don't count yet, and dbFetch() refuses
dbGetRowCount(res)
#> [1] 0
dbHasCompleted(res)
#> [1] FALSE
try(dbFetch(res))
#> Error : Can't fetch a data frame before the Arrow chunk that was kept when the warning about its values exited.

# The next fetch hands out the kept chunk whole, whatever its n
fetch_chunk(1)
#> [1] 1 2 0 4
fetch_chunk(1)
#> [1] 5
dbHasCompleted(res)
#> [1] TRUE
dbClearResult(res)
dbDisconnect(con)

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

  • Keep the chunk, so that no row is lost and a loop until dbHasCompleted() reads them all (recommended)
  • End the result, as an error of dbFetch() does, and drop the kept chunk with its special cases

Kirill decides. If nobody decides, the chunk is kept, and #864's stream relies on it to go on after such an error.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the coercion warning cost less for small chunks?

The warning comes once per chunk with conversions and costs about 0.05 ms, built and signalled with base R's warning() (R/warn-coercion.R#L11-L28); through rlang::warn() it cost about 0.4 ms. In many small chunks with conversions this still shows: two million rows of an int64 column with text in every hundredth row, warnings muffled, take 0.29 to 0.30 s in chunks of 1000 rows against 0.17 to 0.18 s on #861, and the same time in one chunk. The measurements are in the description.

  • Accept the cost, which matters only for small chunks that have conversions (recommended)
  • Build the message only when it is shown, from a conditionMessage() method of the condition class, so that a muffled warning costs only the condition

Kirill decides. If nobody decides, the cost stays as it is.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should dbFetch() report its conversions once per fetch, as the Arrow chunks do?

The report of this pull request covers the Arrow path only (src/SqliteResultImpl.cpp#L585-L606). dbFetch() keeps its existing warnings, one per column and kind, raised while it reads and without row numbers. Against this pull request's head, built from source:

library(DBI)
con <- dbConnect(RSQLite::SQLite())
dbExecute(con, "CREATE TABLE t (id INTEGER, x)")
#> [1] 0
dbExecute(con, "INSERT INTO t VALUES (1, 1), (2, 2), (3, 'three'), (4, 'four')")
#> [1] 4

# dbFetch() keeps its warning per column, raised while it reads
dbGetQuery(con, "SELECT x FROM t ORDER BY id")
#> Warning: Column `x`: mixed type, first seen values of type integer, coercing
#> other values of type string
#>   x
#> 1 1
#> 2 2
#> 3 0
#> 4 0

# The Arrow chunk reports the converted values once per chunk, with their rows
res <- dbSendQuery(con, "SELECT x FROM t ORDER BY id")
chunk <- RSQLite:::result_fetch_arrow_chunk(res@ptr, -1L)
#> Warning: Values converted to the Arrow type of 1 column:
#> * Column `x` (int64): 2 text values converted (rows 3 and 4)
dbClearResult(res)
dbDisconnect(con)

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

  • Keep dbFetch()'s warnings as they are in this pull request (recommended)
  • Report dbFetch()'s conversions once per fetch in the same form, in a separate pull request, since it changes what users see

Kirill decides. If nobody decides, dbFetch() keeps its warnings, and the data frames that pull requests 19 and 20 build through Arrow raise the per-chunk report.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the first Arrow chunk see the storage classes of a row that a data-frame read has converted?

A data-frame fetch reads the next row ahead. If dbColumnInfo() (or dbFetch(n = 0)) then reads that row as a data frame, SQLite converts a blob in a character column to text. The first Arrow chunk of the execution reads the storage classes only when it appends the row (src/SqliteArrowColumn.cpp#L124-L125), so it takes the blob for text: the column becomes utf8 instead of binary, and no conversion is reported. #863 keeps the storage classes for a row read ahead once Arrow columns exist, but before the first chunk there are none, so #863 behaves the same; its review found this, and the comment of read_ahead() in #863 records it. It needs a data-frame fetch before the first Arrow chunk on the same result, which #864 refuses for streams, so only the internal result_fetch_arrow_chunk() reaches it. Against this pull request's head, built from source:

library(DBI)
fetch_chunk <- function(res, n = -1L) {
  chunk <- RSQLite:::result_fetch_arrow_chunk(res@ptr, n)
  nanoarrow::convert_array(chunk)$s
}
con <- dbConnect(RSQLite::SQLite())
dbExecute(con, "CREATE TABLE t (i INTEGER, s)")
#> [1] 0
dbExecute(con, "INSERT INTO t VALUES (1, 'a'), (2, x'626262'), (3, 'c')")
#> [1] 3

# A data-frame fetch of row 1 reads row 2 ahead; the blob in row 2 makes
# `s` binary in the first chunk, which reports the text in row 3
res <- dbSendQuery(con, "SELECT s FROM t ORDER BY i")
dbFetch(res, 1)$s
#> [1] "a"
fetch_chunk(res)
#> Warning: Values converted to the Arrow type of 1 column:
#> * Column `s` (binary): 1 text value converted (row 3)
#> <blob[2]>
#> [1] blob[3 B] blob[1 B]
dbClearResult(res)

# dbColumnInfo() in between reads row 2 as text, which converts the blob:
# the first chunk takes it for text, makes `s` utf8, and reports nothing.
# Expected: the same binary chunk and warning as above
res <- dbSendQuery(con, "SELECT s FROM t ORDER BY i")
dbFetch(res, 1)$s
#> [1] "a"
info <- dbColumnInfo(res)
#> Warning: Column `s`: mixed type, first seen values of type string, coercing
#> other values of type blob
fetch_chunk(res)
#> [1] "bbb" "c"
dbClearResult(res)
dbDisconnect(con)

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

Kirill decides. If nobody decides, it stays as it is, recorded in #863's code comment.


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.

The clean review found nothing above Low: no row is lost or duplicated with options(warn = 2) and varying n, the kept chunk is freed on every path, the log is complete and bounded, the data-frame path's warnings are unchanged, and AddressSanitizer found nothing. Its four Lows are answered in ea9f836: the comments and a test say that a kept chunk comes whole whatever n, the warning is signalled with base R (about 0.05 ms instead of 0.4 ms per chunk), groups stay in the order of their first rows after a merge, and a binary value is logged after it is read. This copy replaces the previous one: each limitation links its question, the open choice about the kept chunk is a question of its own, the blob that a data-frame read converts before the first chunk moves here from #863, where the base already shows it, and the note on which tests ran before the merges is dropped, since the smoke test of CI has passed on every head since. These remain:

  • src/SqliteResultImpl.cpp#L329-L354: when the coercion warning of a chunk ends in an error, the chunk is kept and the next fetch returns it whole, whatever its n; meanwhile its rows don't count and dbFetch() refuses; question, still open. Relevance: medium; reviewer's confidence: high.
  • R/warn-coercion.R#L11-L28: one warning per chunk with conversions costs about 0.05 ms, which shows in many small chunks; question. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L585-L606: the report covers the Arrow path only, and dbFetch() keeps its own warnings; question. Relevance: low; reviewer's confidence: high.
  • src/SqliteArrowColumn.cpp#L124-L125: a blob that dbColumnInfo() converts to text after a data-frame fetch is taken for text by the first Arrow chunk, without a report; question. Relevance: low (internal entry point only); reviewer's confidence: high.

Found here, but on main too:


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: should an integer that a double column can't hold exactly be reported as converted?

The clean review of 2026-11-29 rated this Medium. An integer in an Arrow column of type double is never reported, on the premise that dbFetch() reads it the same way without a warning (src/SqliteArrowColumn.cpp#L255-L257). That holds up to 2^53 only. Beyond it, promote_to_double() (L632, from #859) and the append to a column that is already double change the value silently, while dbFetch() returns it as integer64, exactly, with its "mixed type" warning:

library(DBI)
con <- dbConnect(RSQLite::SQLite())
q <- "SELECT 9007199254740993 AS x UNION ALL SELECT 1.5"

dbGetQuery(con, q)$x
#> Warning: Column `x`: mixed type, first seen values of type integer64, coercing other values of type real
#> integer64
#> [1] 9007199254740993 1

res <- dbSendQuery(con, q)
ch <- RSQLite:::result_fetch_arrow_chunk(res@ptr, -1L)
sprintf("%.0f", nanoarrow::convert_array(ch$children[[1]], double()))
#> [1] "9007199254740992" "2"
# no warning: the first value changed unreported (the second is 1.5, printed with "%.0f")

Counting such a value as converted, when static_cast<int64_t>(static_cast<double>(v)) != v, costs one comparison per integer in a double column and a test; the report then names its row like any other lossy conversion, and values a double holds exactly stay unreported. Documenting the loss instead leaves the chunk silent. Typing such a column as int64 is not possible once a real value arrives in it.

  • Report an integer that a double can't hold exactly as converted, with its row, in the append to a double column and in promote_to_double() (recommended: the report's promise is that no value changes unseen)
  • Keep it unreported and say in the documentation that integers beyond 2^53 lose precision in a double column
  • Accept it as a limitation of this pull request

Kirill decides. The fix was not written in this session: the session's harness refused to start the agent that would have written it. If nobody decides, it stays as it is, listed as an accepted limitation.

Output from a run of this session with devtools::load_all() at 724c9fb, the head of #863, which carries this pull request.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review found nothing above Low: no row is lost or duplicated with options(warn = 2) and varying n, the kept chunk is freed on every path, the log is complete and bounded, the data-frame path's warnings are unchanged, and AddressSanitizer found nothing. Its four Lows are answered in ea9f836: the comments and a test say that a kept chunk comes whole whatever n, the warning is signalled with base R (about 0.05 ms instead of 0.4 ms per chunk), groups stay in the order of their first rows after a merge, and a binary value is logged after it is read. This copy replaces the previous one: each limitation links its question, the open choice about the kept chunk is a question of its own, the blob that a data-frame read converts before the first chunk moves here from #863, where the base already shows it, and the note on which tests ran before the merges is dropped, since the smoke test of CI has passed on every head since.

The clean review of 2026-11-29, after main (3.54.1) was merged up the stack, read this pull request at 56e80f1 and found one Medium here, an integer that a double column can't hold exactly changing without a report, listed below with its question; nothing else. 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:

  • src/SqliteResultImpl.cpp#L329-L354: when the coercion warning of a chunk ends in an error, the chunk is kept and the next fetch returns it whole, whatever its n; meanwhile its rows don't count and dbFetch() refuses; question, still open. Relevance: medium; reviewer's confidence: high.
  • R/warn-coercion.R#L11-L28: one warning per chunk with conversions costs about 0.05 ms, which shows in many small chunks; question. Relevance: low; reviewer's confidence: high.
  • src/SqliteResultImpl.cpp#L585-L606: the report covers the Arrow path only, and dbFetch() keeps its own warnings; question. Relevance: low; reviewer's confidence: high.
  • src/SqliteArrowColumn.cpp#L124-L125: a blob that dbColumnInfo() converts to text after a data-frame fetch is taken for text by the first Arrow chunk, without a report; question. Relevance: low (internal entry point only); reviewer's confidence: high.
  • src/SqliteArrowColumn.cpp#L255-L257: an integer beyond 2^53 in a double column changes value without a report, while dbFetch() returns it exactly as integer64 (question). Relevance: medium; reviewer's confidence: high.

Found here, but on main too:


Generated by Claude Code

…chunk

A result fetched as Arrow arrays refuses every data frame fetch,
so the refusal for a kept Arrow chunk no longer applies.
The tests fetch only Arrow chunks from their results.

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