Skip to content

feat: Build Arrow date, time and timestamp arrays with extended_types - #861

Draft
krlmlr wants to merge 18 commits into
claude/arrow-text-columnsfrom
claude/arrow-date-columns
Draft

krlmlr wants to merge 18 commits into
claude/arrow-text-columnsfrom
claude/arrow-date-columns

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Sixth step of the Arrow rework (plan: #829 (comment)): with extended_types = TRUE, the internal Arrow engine of #860 builds date32, time64 and timestamp arrays from columns declared as DATE, TIME, DATETIME or TIMESTAMP. The entry point result_fetch_arrow_chunk() stays internal, so nothing changes for users.

Commits:

  1. refactor: Split the date and time parsers from their warnings. SqliteColumnDataSource gets the static parse_date(), parse_time() and parse_datetime_local(), which parse the text of these columns into whole days or microseconds and return whether they could, instead of warning. fetch_date(), fetch_time() and fetch_datetime_local() call them, scale the result as before (static_cast<double>(days) and micros * 1e-6) and raise the same warnings for text they can't parse and for blobs. feat: Report coerced values once per chunk or dbFetch(), with their rows #800 (ef68461) split the same functions into members that read the current value and return seconds; parsing text into integers instead lets the Arrow path keep every microsecond, so it needs no second copy of the boost calls, as the old stack's parse_micros() had (2e62ede in feat: Request Arrow types for result columns with schema #801).
  2. feat: Build Arrow date, time and timestamp arrays with extended_types. The Arrow handling of feat: Implement the DBI Arrow interface natively #795 (43db19f) with its refinements up to 3436358, read from the type rules at the top of 34363581:src/SqliteArrowColumn.h.
  3. Merges of feat: Build Arrow arrays from text and blob columns #860 at 3ac16c6 and at 32dea06, whose conflicts were adjacent additions; a merge of the CI's auto-update (2e3606e), keeping its formatting of src/SqliteResultImpl.cpp, and a commit that restores the .dd files it filled with absolute paths (Incremental builds miss changes to bundled extensions under src/vendor/extensions/ #836).
  4. fix: Fail date and time chunks on out of memory, and round seconds exactly, from the review of 229c74a.
  5. fix: Round real seconds to the nearest microsecond of their double, from the review of cfba409.

What changes:

  • With extended_types = TRUE, a column declared as DATE, TIME, DATETIME or TIMESTAMP is date32, time64[us] or timestamp[us, UTC] from the start, whatever its values, as the data-frame path reads it as Date, hms or POSIXct in UTC. The declared types match through datatype_from_decltype() of the data-frame path, made public for this, so both paths agree on names such as datetime (they match the whole name, case-insensitive: DATETIME(6) is not one). A column of only NULL takes these types too, also in a result of no rows. Expressions and other declared types follow the value-based rules of feat: Build Arrow arrays from text and blob columns #860.
  • Values are read as the data-frame path reads them:
    • Text goes through the parsers of the first commit, read as UTF-8 with feat: Build Arrow arrays from text and blob columns #860's value_text(): a conversion that runs out of memory fails the chunk at once, as for the other columns, instead of becoming NULL.
    • A number in a DATE column is a count of days since 1970-01-01, truncated toward zero; in a TIME or TIMESTAMP column it is seconds, since midnight or since 1970-01-01 00:00:00 UTC, rounded to the nearest microsecond. A Julian day is such a count too, as for dbFetch().
    • A real number of seconds becomes the microsecond nearest to what its double holds, which dbFetch() keeps, as CPython's datetime.fromtimestamp() rounds it: std::modf() splits it into whole seconds and their fraction, both exact, and only the fraction is rounded, with std::nearbyint(), halves to even in the default rounding mode, which R keeps. Rounding the seconds times 1e6 rounds twice, since the product is rounded to a double first, a multiple of 1/4 µs for present-day timestamps: feat: Implement the DBI Arrow interface natively #795's std::floor(x * 1e6 + 0.5) and std::nearbyint(x * 1e6) (cfba409) missed the nearest microsecond of about one present-day timestamp in eight (1759618878.0778434 gave …844 where the double holds …843.43), and the former also rounded an odd count between 2^52 and 2^53 one up (5000000000.000001 gave …002). std::llround() would round halves away from zero, and is unspecified for an infinity or a value beyond 64 bits. The whole seconds are range-checked before their cast, and the sum stays within the int64 microseconds but their smallest value, which bit64 reads as NA, as for an integer: a real of -9223372036854.775808 s gave exactly -2^63 µs at cfba409. The tests pin three present-day timestamps that the product missed, the 2^52 example and its negative, the exact halves 0.0078125 s and 0.0234375 s (7812 and 23438 µs), and the double nearest to -2^63 µs (…775391 µs) with the next one down (NULL).
    • An integer number of seconds is scaled exactly, and text keeps all its microseconds, also beyond the 2^53 that a double holds (2e62ede).
  • NULL takes the place of a blob and of text that can't be parsed, where dbFetch() warns and returns NA, and of values beyond the range of the Arrow type:
    • a count of days beyond 32 bits, which dbFetch() reads with sqlite3_column_int() and wraps; here it is read in full (b99d110);
    • a huge or infinite real in a DATE column, which sqlite3_column_int() saturates at 64 bits before keeping the low 32: dbFetch() reads 1e300 and 9e999 as 1969-12-31 and -9e999 as 1970-01-01, without a warning;
    • a number of seconds beyond the range of int64 microseconds, -2^63 µs included, or an infinity (fc0d6d8);
    • a time outside [00:00:00, 24:00:00), such as 86400, -1 or '25:00:00', which time64 can't hold and Arrow's full validation rejects; dbFetch() keeps such durations as hms. Rounding a number just below midnight stops at the last microsecond of the day (ca06a58).
  • None of these conversions is reported yet, as feat: Build Arrow arrays from the integer, real and NULL columns of a result #859 and feat: Build Arrow arrays from text and blob columns #860 keep theirs silent until pull request 7.
  • Without extended_types, these columns follow the value-based rules as before: text is utf8, numbers int64 or double, and a column of only NULL takes the double of NUMERIC affinity.

The data-frame path is unchanged. New tests in test-extendedTypes.R pin its exact values, the order and text of its warnings, and that a warning made an error completes the result; they pass on #860 and after each commit. Two of the pinned values, the time and the timestamp of the last row, differ between micros * 1e-6 and micros / 1e6, so the pin catches a change of the formula (checked by mutation).

The shared parser has quirks that this pull request keeps on both paths, and the tests pin them, since the Arrow arrays must read what dbFetch() reads: it knows no T between date and time, no Z, no +02:00 and no UTC (all NA or NULL); a timestamp needs a time; a date ignores anything after a space that follows the day; years run from 1400 to 9999. It also misreads a negative UTC offset, without a warning, on main today and so on both paths here: boost's tokenizer splits on - and takes the fields after the seconds for the fraction of a second. '2024-01-02 12:00:00-02:00' reads as 12:00:00.02 (-05:30 and -0500 as .05 s), '2024-01-02 12:00-02:00' as 12:00:02, and after a fraction ('2024-01-02 12:00:00.5-02:00') the offset is dropped; TIME columns read '12:00:00-02:00' the same way. The instant is off by the whole offset. The tests pin the first shape in both test-extendedTypes.R and test-arrow-dates.R as behavior shared with dbFetch(); fixing the shared parser, for both paths at once, is left to a separate pull request.

Deliberately left out:

  • Reporting converted and NULL values once per chunk with their rows is pull request 7.
  • Requested types, such as date64, time32 or other units and time zones, are pull requests 13 and 14.
  • The Arrow data-frame path, which builds times and timestamps as doubles in seconds to keep the default path's precision and range, is pull request 19.
  • Byte limits are pull request 8, the DBI methods pull request 16.

Tested:

  • New tests/testthat/test-arrow-dates.R: each declared type with ISO text, month names, numbers (days, Unix seconds, reals, Julian days), fractional seconds from one to nine digits, time zones and offsets in timestamps under a session time zone that is not UTC, dates and timestamps from 1400 to 9999 with 1969, 1900 and 2038 around them, values beyond the range of each Arrow type and infinities, blobs and text that can't be parsed (invalid month and day, empty text, a year before 1400, a timestamp without a time), NULL and all-NULL columns, a result of no rows, text, numbers, blobs and NULL mixed in one column fetched in chunks of all rows, of 1 row up to one past the end, and of 2, 3 and 4 rows, a rebound statement, declared names in other cases and with a size, aliases and expressions, a UTF-16 database, and extended_types = FALSE. Where the rules agree, each chunk is compared with dbFetch() on the same connection in the same chunk sizes, with the values converted to the same instants, and with dbHasCompleted() and dbGetRowCount() after each chunk; exact microseconds are compared as integer64.
  • A callr test runs out of memory while the text of a DATE, TIME and TIMESTAMP column is converted to UTF-8 (generated columns whose 20 million characters are computed as they are read, in a UTF-16 database) and expects the chunk to fail at once, as feat: Build Arrow arrays from text and blob columns #860's test does for the other columns; fetch_arrow_chunk_out_of_memory() takes setup statements and extended_types for it. It passes against an installed build and fails without value_text(); under load_all() it skips, as feat: Build Arrow arrays from text and blob columns #860's does, since the callr session loads another RSQLite.
  • tests/testthat/helper-arrow.R: arrow_values() converts date32, time64 and timestamp to Date, hms and POSIXct in UTC, expect_same_chunks() takes unparsable = TRUE where dbFetch() warns of values it can't convert, and the new arrow_micros() and fetch_arrow_all() read exact microseconds and fetch a whole result. Every chunk passes expect_valid_chunk(), nanoarrow's full validation.
  • By hand, arrow 26.0.1's ValidateFull() accepts all 29 chunks that test-arrow-dates.R builds under load_all(), and all 124 chunks of the three Arrow test files (arrow is not a test dependency here). It rejects a time64 of 24:00:00, which nanoarrow's validation accepts, so the range of time64 is checked explicitly in the tests.
  • Mutations: without the range check of time64, without the stop at the last microsecond of the day, with either former rounding, or reading days with sqlite3_column_int(), one or two blocks fail; without extended_types reaching the Arrow column, all blocks but the one with extended_types = FALSE and the callr one fail.
  • Each test_that() block of test-arrow-dates.R, test-arrow-columns.R, test-arrow-text.R and test-extendedTypes.R passes on its own in a fresh session right after pkgload::load_all().
  • At 229c74a, 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).
  • At 229c74a, under AddressSanitizer (gcc, -O1), test-arrow-dates.R, test-extendedTypes.R, test-arrow-columns.R, test-arrow-text.R, test-read-ahead.R, test-dbSendQuery.R, test-dbClearResult.R, test-error.R and test-dbBind.R pass without a report, and so does a script with chunks of several sizes over dates, times and timestamps from text, numbers, blobs, infinities and values out of range, rebinding, and arrays converted after their result was cleared and the connection closed, also under gctorture(TRUE).
  • At 229c74a, R CMD check --no-manual --no-tests --ignore-vignettes on a built tarball: Status: OK. src/SqliteArrowColumn.dd gains the three package headers it now includes, written by hand, since the build adds absolute system paths to it (Incremental builds miss changes to bundled extensions under src/vendor/extensions/ #836).

Timing at 229c74a, one million rows in one chunk from a file database, median of nine runs, three rounds with the same result, on an -O2 build:

  • Timestamps as text (2023-11-14 22:13:57.123): 0.70 s for the Arrow chunk, 0.94 s for dbFetch().
  • Timestamps as reals: 0.09 s for the Arrow chunk, 0.30 s for dbFetch().
  • Dates as text: 0.35 s against 0.59 s; times as text with six fractional digits: 0.44 s against 0.74 s.
  • dbFetch() takes the same time as on feat: Build Arrow arrays from text and blob columns #860 within 1 to 3 %, which is the spread between rounds. The Arrow chunk of text takes 0.11 s on feat: Build Arrow arrays from text and blob columns #860, where it stays utf8: the boost parser is most of the cost on both paths.

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

Size

About 260 hand-written lines of C++: 175 in SqliteArrowColumn.cpp and .h, 85 in SqliteColumnDataSource.cpp and .h, of which about 40 move the existing parsing into the new functions, and 6 in SqliteResultImpl.cpp. Tests add about 480 lines: 360 in test-arrow-dates.R, 80 in test-extendedTypes.R and 40 in helper-arrow.R.

Review

Two review rounds (first, second) led to cfba409 and 5465c7b; see the accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

`SqliteColumnDataSource` parses the text of DATE, TIME, DATETIME and TIMESTAMP columns
with `extended_types = TRUE` in the static `parse_date()`, `parse_time()` and `parse_datetime_local()`,
which return whether the text could be parsed instead of warning,
so that the Arrow arrays of the next commit can parse the same text without the warning.
They parse into whole days and microseconds,
which `fetch_date()`, `fetch_time()` and `fetch_datetime_local()` scale as before,
and raise the same warnings for text they can't parse and for blobs.

New tests pin the exact values and the warnings of the data-frame path for these columns,
and that a warning made an error completes the result;
they pass before and after this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
With `extended_types = TRUE`, a column declared as DATE, TIME, DATETIME or TIMESTAMP
becomes a `date32`, `time64[us]` or `timestamp[us, UTC]` array in `result_fetch_arrow_chunk()`,
whatever its values, as the data-frame path reads it as Date, hms or POSIXct in UTC.
The declared types match as `datatype_from_decltype()` matches them for the data-frame path.

Values are read as the data-frame path reads them.
Text goes through the parsers of the previous commit, into days or whole microseconds.
A number is a count of days, truncated toward zero, or of seconds, rounded to the nearest microsecond.
A blob, text that can't be parsed, a count of days beyond the range of `date32`,
a number of seconds beyond the range of int64 microseconds,
and a time outside the day that `time64` holds are NULL,
where the data-frame path warns, wraps the days in 32 bits, or keeps the duration.
Rounding a time before midnight stops at the last microsecond of the day.
None of these conversions is reported yet.

Without `extended_types`, these columns follow their values as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
@krlmlr
krlmlr added this pull request to stack #851 November 12, 2026 19:20
krlmlr and others added 4 commits November 12, 2026 19:27
Conflicts were adjacent additions, both sides kept:
`value_text()` and `text_real()` next to `append_date()` and `append_time()`
in `src/SqliteArrowColumn.cpp` and `.h`,
and `fetch_arrow_chunk_out_of_memory()` next to `arrow_micros()` and `fetch_arrow_all()`
in `tests/testthat/helper-arrow.R`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The CI's auto-update regenerated `src/SqliteResultImpl.dd` and `src/cpp11.dd` with GCC,
whose dependency output indents continuation lines by one space,
which the filter in `src/Makevars.deps` does not drop,
so the files gained hundreds of absolute and vendored paths (#836).
This restores them as they were and keeps the auto-update's formatting of `src/SqliteResultImpl.cpp`.

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 229c74a, by a Claude Code reviewer with clean context that read the description, both commits (1d77e80 and 229c74a) against #860 at 689a5c5, the code around them (SqliteColumnDataSource, DbColumnStorage, SqliteResultImpl, SqliteArrowColumn), the date and time handling of the old stack at 3436358, and the new tests; built the pull request and its base into separate libraries at -O2, plus one build with AddressSanitizer and UBSan; and ran the tests and reproducers below. I posted nothing on GitHub myself.

What was run

  • The new and changed test files against both builds: on 229c74a, test-arrow-dates.R (78), test-extendedTypes.R (25), test-arrow-columns.R (125) and test-arrow-text.R (139) pass; on the base, the two new test-extendedTypes.R blocks pass and test-arrow-dates.R fails (31 failures, 5 errors), as it should.
  • Each of the 12 blocks of test-arrow-dates.R and the 2 new blocks of test-extendedTypes.R alone in a fresh session after pkgload::load_all(): all pass.
  • devtools::test() with NOT_CRAN=true: no failures, only the three known test-httpvfs.R errors.
  • R CMD check --no-manual --ignore-vignettes on a tarball built from the worktree, tests included: Status: 1 NOTE, for the .git file a worktree has.
  • Own reproducers, base against pull request: dbFetch() with extended_types = TRUE over 20,351 rows (20,000 random ISO texts with 0 to 9 fractional digits, 22 odd texts, 29 edge numbers and blobs, 300 random reals) whole and in chunks of 997; the same with options(warn = 2); timings on one million rows; an Arrow probe of 53 edge values in DATE, TIME and TIMESTAMP columns in chunks of 1, of 2 to 100 and of all rows, each validated by nanoarrow's IPC round trip and arrow 26.0.1's Table$ValidateFull(); a probe of UTC offsets on the base; what Python's sqlite3 stores for an aware datetime.
  • AddressSanitizer and UBSan (gcc, -O1): test-arrow-dates.R, test-extendedTypes.R, all the reproducers above and an Arrow fetch under gctorture(TRUE): no report.

What holds

  • The refactor changes nothing on the default path: the 20,351 values are bit-identical (identical(num.eq = FALSE)) whole and chunked, including 1,101 timestamps where / 1e6 would differ from * 1e-6; the 67 warnings match in text and order; with warn = 2 both builds fail with the same converted warning and leave the same dbHasCompleted() and dbGetRowCount(). Medians of seven runs over one million rows, three rounds: timestamps as text 0.96 to 0.98 s on the base against 0.98 to 1.01 s, times 0.73 to 0.74 against 0.74 to 0.77, dates 0.60 against 0.60 to 0.64, reals 0.31 against 0.30 to 0.31, within the spread between rounds.
  • The data-frame path of 229c74a is that of 1d77e80: only the private: of datatype_from_decltype() changes.
  • Arrow arrays are date32[day], time64[us] and timestamp[us, tz=UTC]; every chunk of every probe passes both validations, including 86400, 86399.9999996, ±2^31 days, ±9223372036854 s, ±infinity, 1e300, 1e19, blobs, empty text and '23:59:60' (NULL as a time, the next midnight as a timestamp, as dbFetch() reads it).
  • Days are truncated toward zero as sqlite3_column_int() does, also before 1970; days beyond 32 bits, seconds beyond int64 microseconds, infinities and times outside [0, 24h) are NULL; text keeps every microsecond up to 9999-12-31 23:59:59.999999. NaN can't reach a column: SQLite stores it as NULL.
  • Declared types match through the shared datatype_from_decltype(): whole name, any case, aliases keep the type, DATETIME(6), DATE_ and expressions follow their values on both paths.
  • The deliberate differences from dbFetch() are those the code makes; the description says what the code does, and the scope matches the title.
  • src/SqliteArrowColumn.dd gains exactly the three headers now included, all relative, and builds leave it unchanged.

High

None.

Medium

  1. The negative-offset misreading the tests pin is wider and more serious than the description says, and it is on main today.

    bool SqliteColumnDataSource::parse_datetime_local(
    const char* text,
    int64_t& micros
    ) {
    namespace bp = boost::posix_time;
    namespace bg = boost::gregorian;
    namespace bd = boost::date_time;
    if (text == NULL) {
    return false;
    }
    try {
    bp::ptime dttm(bd::parse_delimited_time<bp::ptime>(text, ' '));
    bp::time_duration delta =
    dttm - bp::ptime(bg::date(1970, 1, 1), bp::seconds(0));
    micros = delta.total_microseconds();
    } catch (...) {
    return false;
    }
    return true;
    }

    (Confirmed, on the base build, whose parser is main's.) With extended_types = TRUE, '2024-01-02 12:00:00-02:00' reads as 12:00:00.02 UTC, -05:30 and -0500 as 12:00:00.05, '2024-01-02 12:00-02:00' as 12:00:02, and after a fraction ('12:00:00.5-02:00', '12:00:00.123-08:00') the offset is dropped altogether; TIME columns read '12:00:00-02:00' the same way. All of this comes without a warning, where SQLite's own datetime() reads the first as 14:00 and the last as 20:00:00.123. Positive offsets, Z and T give NA with a warning. Python's sqlite3 stores an aware datetime exactly as '2024-01-02 12:00:00-05:00' (checked), so timestamps written from Python anywhere west of UTC come back hours off, silently, against the documented "NA with a warning". This pull request doesn't cause it and is right to read what dbFetch() reads, but it now pins the misreading in two test files, so the follow-up has to be planned rather than left open.

    Suggested fix: say in the description that the instant is off by the whole offset, in three shapes; open an issue now; in the follow-up, make parse_datetime_local() and parse_time() reject (or apply) any trailing offset, so both paths give NA/NULL with a warning instead of a wrong instant.

Low

  1. Rounding seconds as std::floor(x * 1e6 + 0.5) is off by one microsecond for odd counts between 2^52 and 2^53 microseconds.

    } else if (column_type == SQLITE_FLOAT) {
    const double seconds = sqlite3_column_double(stmt, j);
    // Both bounds are exact as doubles, and casting a value outside,
    // an infinity included, would be undefined
    const double rounded = std::floor(seconds * 1e6 + 0.5);
    ok = rounded >= -9223372036854775808.0 && rounded < 9223372036854775808.0;
    if (ok) {
    micros = static_cast<int64_t>(rounded);
    }

    (Confirmed.) Real seconds 5000000000.000001, 6000000000.000003 and 4503599627.370497 in a TIMESTAMP column become …002, …004 and …498 microseconds, and -5000000000.000001 becomes -…000, where dbFetch() holds …001, …003, …497 and -…001: x * 1e6 is an exact odd integer there, and x + 0.5 is a tie that rounds to even. This hits timestamps stored as reals from 2112-09-17 to 2255-06-05 and from 1684-07-28 to 1827-04-16; time64 can't reach it. The formula comes from the old stack (3436358).

    Suggested fix: std::round(seconds * 1e6) (exact for integers, halves away from zero) or std::nearbyint(), with one of these values in the tests.

  2. The description's list of differences leaves out infinite and huge reals in a DATE column, which dbFetch() silently turns into dates.

    return static_cast<double>(sqlite3_column_int(get_stmt(), get_j()));

    (Confirmed.) sqlite3_column_int() saturates and keeps the low 32 bits, so 9e999 and 1e300 read as 1969-12-31 and -9e999 as 1970-01-01 without a warning; the Arrow array has NULL, which is better. Also, two pinned values of row 8 in test-extendedTypes.R (the time and the timestamp) tell * 1e-6 from / 1e6, not one.

    Suggested fix: name infinities and reals beyond 32 bits next to the wrapped integers in the description, and pin dbFetch()'s values for them in the new test-extendedTypes.R block.


Generated by Claude Code

…actly

`append_date()` and `append_time()` read text through `value_text()` of #860,
so that a conversion of text that runs out of memory fails the chunk at once,
as for the other columns, instead of becoming NULL.
`fetch_arrow_chunk_out_of_memory()` takes setup statements and `extended_types`,
and a new test runs it on DATE, TIME and TIMESTAMP columns
whose text is computed as it is read.

Reals are rounded to microseconds with `std::nearbyint()`,
to the nearest integer, halves to even in the default rounding mode.
`std::floor(x * 1e6 + 0.5)` rounded an odd count between 2^52 and 2^53 one up,
such as `5000000000.000001` seconds, where the count is exact and adding 0.5 makes a tie.
`std::llround()` would round halves away from zero,
but is unspecified for an infinity or a value beyond 64 bits,
which the range check after rounding handles as it is.
The tests pin that example, its negative, and two exact halves,
and the dates that `dbFetch()` makes of huge and infinite reals in a DATE column,
which the Arrow array holds as NULL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
Conflicts kept both sides:
the declaration of `text_real(int column_type)` next to `append_date()` and `append_time()`
in `src/SqliteArrowColumn.h`,
and in `fetch_arrow_chunk_out_of_memory()` the setup statements and `extended_types`
next to the returned value of column `x`.

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 the fixes in this pull request at cfba409 (the commits since 229c74a), by a Claude Code reviewer with clean context that read the description, the merge c3518d3 of #860 at 3ac16c6 (its remerge diff, and each side's changes compared line by line), the merge 3c6c68c of the CI's formatting commit, the restored .dd files of 893c1f4 and the fix cfba409, with the code and tests around them; built the pull request, its base #860 at 3ac16c6 and a mutation of cfba409 without value_text() in append_date() and append_time() into separate libraries at -O2; and ran the tests and reproducers below. I posted nothing on GitHub myself.

What was run

  • The Arrow and extended-types test files against installed builds, so that the callr blocks run: at cfba409 test-arrow-dates.R (87), test-arrow-text.R (168), test-arrow-columns.R (125) and test-extendedTypes.R (25) pass without skips; on the base test-arrow-dates.R fails (31 failures, 5 errors), as it should; against the mutation the new out-of-memory block fails all nine of its expectations.
  • Each of the 44 blocks of test-arrow-dates.R, test-arrow-text.R, test-dbClearResult.R and test-extendedTypes.R alone in a fresh session after pkgload::load_all(): 42 pass, and the two callr blocks skip.
  • devtools::test() with NOT_CRAN=true: no failures, only the three known test-httpvfs.R errors. R CMD check --no-manual --ignore-vignettes on a built tarball, tests included: Status: 1 NOTE, for the .git file a worktree has; the callr blocks run there.
  • Own reproducers: out of memory under PRAGMA hard_heap_limit in a process of its own, for DATE, TIME and TIMESTAMP, with stored and generated text, in chunks of one and two rows, on all three builds; 100,009 real times and timestamps against the nearest microsecond of the double that dbFetch() returns (glibc's exact sprintf("%.6f")), and CPython's datetime.fromtimestamp() for some; a C++ probe with exact 128-bit products over a million random doubles per binade, for std::nearbyint(x * 1e6), the former std::floor(x * 1e6 + 0.5) and rounding after std::modf(); negative UTC offsets on both paths; huge and infinite reals in a DATE column; a real of −2^63 µs.
  • valgrind: test-arrow-dates.R, test-arrow-text.R, test-extendedTypes.R and the out-of-memory reproducer: 0 errors.

What holds

  • The merge loses nothing: the added and removed lines of c3518d3 against 229c74a are exactly those of feat: Build Arrow arrays from text and blob columns #860 from 689a5c5 to 3ac16c6, and against 3ac16c6 exactly those of 229c74a. The three conflicts keep both sides; text_reals, text_real(), the blob handling of value_bytes() and stop_out_of_memory() are intact next to the date code. 3c6c68c and 893c1f4 leave the tree of c3518d3 with only the CI's formatting of src/SqliteResultImpl.cpp.
  • No src/*.dd at cfba409 holds an absolute, vendored or drive path; since 229c74a only feat: Build Arrow arrays from text and blob columns #860's two removals changed them. SqliteArrowColumn.dd lists exactly the local headers of a regenerated one, and building the checkout leaves all of them unchanged.
  • Out of memory now fails the chunk in all 12 combinations with "Column x: out of memory while reading a value." and leaves the result completed after one row, as feat: Build Arrow arrays from text and blob columns #860 does for the other columns. The mutation silently returns NULL where the value ends a chunk (and SQLite's own "out of memory" otherwise). The callr test runs the installed build under test and skips after load_all().
  • The rounding fix does what it says between 2^52 and 2^53 µs: ±5000000000.000001 s give ±…001. Exact halves (0.0078125 s) go to even with either sign; infinities and products beyond ±2^63 are NULL; a time just before midnight stops at 86399999999. R keeps the default rounding mode; under FE_UPWARD, 0.0000004 s would become 1 µs.
  • The new dbFetch() pins are stable: SQLite's sqlite3RealToI64() saturates explicitly, and the (int) cast in sqlite3_value_int() is implementation-defined but reduces modulo 2^32 on gcc (documented), clang and MSVC, which covers every R toolchain, Rtools included. The wrapped integers the block already pinned rest on the same cast. 1e300, 9e999 and 9.3e18 read as −1, their negatives as 0.
  • The description now states the negative-offset misreading accurately: I reproduced each shape on both paths (.02 s, .05 s for -05:30 and -0500, 12:00:02, the offset dropped after a fraction, TIME the same), all without a warning.
  • CI is green at cfba409.

High

None.

Medium

None.

Low

  1. std::nearbyint(seconds * 1e6) misses the nearest microsecond for about one in eight present-day real timestamps; the fix cures only 2^52 to 2^53 µs.

    // To the nearest microsecond, halves to even in the default rounding mode.
    // Adding 0.5 and rounding down would round an odd count between 2^52 and
    // 2^53 one up: the count is exact there, and adding 0.5 makes a tie.
    // Both bounds are exact as doubles, and casting a value outside,
    // an infinity included, would be undefined.
    const double rounded = std::nearbyint(seconds * 1e6);
    ok = rounded >= -9223372036854775808.0 && rounded < 9223372036854775808.0;
    if (ok) {
    micros = static_cast<int64_t>(rounded);

    (Confirmed.) The product is first rounded to a double, a multiple of 1/4 µs for timestamps from 2005 to 2041 and of 1/2 µs from 2041 to 2112, so a fraction within 1/8 (1/4) µs of a half becomes an exact half, which goes to even. Of 100,000 random reals between 1.7e9 and 1.8e9 s in a TIMESTAMP column, 12,458 come out one microsecond away from the nearest microsecond of the double that dbFetch() returns: 1759618878.0778434 (exactly …077843427658) becomes …844, where CPython's datetime.fromtimestamp() gives …843. The exact probe finds the same rates, about 12 % and 24 %, for the former formula. The error stays below 5/8 µs, and values written with six decimals are unaffected. The pinned 0.0000025 and 0.0000035 aren't exact halves as doubles (the nearest microsecond is 3 for both); their products round to halves, so they pin this double rounding rather than ties to even, although CPython also gives 2 and 4.

    Suggested fix: round as CPython does: split with std::modf(), round frac * 1e6 with std::nearbyint(), and add the whole seconds times 1000000 in int64, with the range check on the whole seconds and the sum. In my probe this matches the exact nearest microsecond in every binade (0 of 10 million present-day values off) and keeps the pinned 2 and 4. Pin 1759618878.0778434 → …843, and an exact half such as 0.0078125 → 7812.

  2. The range check after rounding admits exactly −2^63 µs, which bit64 reads as NA.

    const double rounded = std::nearbyint(seconds * 1e6);
    ok = rounded >= -9223372036854775808.0 && rounded < 9223372036854775808.0;
    if (ok) {
    micros = static_cast<int64_t>(rounded);

    (Confirmed.) A real of −9223372036854.775808 s becomes a valid INT64_MIN, which convert_array(..., bit64::integer64()), and so the tests' arrow_micros(), reads as NA (pandas as NaT), while nanoarrow and arrow give a POSIXct in the year −290308; the integer path stops at -INT64_MAX / 1000000 s. This dates from 229c74a and is far from real data.

    Suggested fix: rounded > -9223372036854775808.0, symmetric with the integer path.


Generated by Claude Code

`append_time()` rounded the seconds of a real times 1e6 with `std::nearbyint()`.
The product is itself rounded to a double, a multiple of 1/4 µs for present-day timestamps,
so about one in eight came out one microsecond off the nearest,
such as `1759618878.0778434`, read as …844 where the double holds …843.4.
It now splits the seconds with `std::modf()` into whole seconds and their fraction, both exact,
and rounds only the fraction, halves to even in the default rounding mode,
as CPython's `datetime.fromtimestamp()` does.
The whole seconds are range-checked before their cast,
and the sum stays within the int64 microseconds but their smallest value,
which bit64 reads as NA, as the integer path does:
a real of -9223372036854.775808 s gave exactly -2^63 µs before.

The tests pin three present-day timestamps that the former rounding missed,
exact halves (0.0078125 and 0.0234375 s) in place of 0.0000025 and 0.0000035 s,
which are no halves as doubles,
and the double nearest to -2^63 µs with the next one down, which is NULL.

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.

Two review rounds: the first confirmed that the parser refactor leaves dbFetch() unchanged (values bit-identical on 20,351 rows, all 67 warnings in text and order, speed) and raised as Medium the shared parser's misreading of negative UTC offsets, which is on main too; cfba409 read date and time text through value_text() (failing the chunk on out of memory), fixed the rounding at 2^52 to 2^53 µs and completed the description. The second found nothing above Low; 5465c7b rounds real seconds to the nearest microsecond of their double, as CPython does, and excludes −2^63 µs. #860's later heads are merged in (c3518d3, 6d490fb). These remain:

  • src/SqliteColumnDataSource.cpp#L156-L205: the date and time parser that dbFetch() and the Arrow path share misreads UTC offsets, silently: '2024-01-02 12:00:00-05:00' reads as 12:00:00.05, '12:00-02:00' gets 2 seconds, an offset after fractional seconds is dropped, and TIME columns behave the same; Python's sqlite3 writes aware datetimes in exactly this form. It also rejects T, Z, +hh:mm and UTC, a timestamp without a time, and years outside 1400 to 9999, and a DATE ignores everything after a space. This pull request keeps both paths in agreement and pins today's behavior; fixing it changes dbFetch() on main and is asked as a question. Relevance: high (on main today); reviewer's confidence: high.
  • src/SqliteArrowColumn.cpp#L461: by design, the Arrow arrays differ from dbFetch() where the latter has no valid answer: times outside [0, 24h) become NULL where dbFetch() keeps an hms duration, days beyond 32 bits and huge or infinite reals in a DATE column become NULL where dbFetch() wraps or saturates them, and numeric seconds are rounded to microseconds. The tests pin both sides. Relevance: low; reviewer's confidence: high.
  • src/SqliteArrowColumn.cpp#L231: unparsable and out-of-range values become NULL silently here; feat: Report values converted to an Arrow column's type once per chunk, with their rows #862 reports them once per chunk. Relevance: medium (internal entry point only until pull request 16); reviewer's confidence: high.

Generated by Claude Code

krlmlr and others added 2 commits November 12, 2026 20:14
The CI's auto-update regenerated `src/SqliteArrowColumn.dd` and `src/cpp11.dd` with GCC,
whose dependency output indents continuation lines by one space,
which the filter in `src/Makevars.deps` does not drop,
so the files gained hundreds of absolute and vendored paths (#836).
This restores them as they were at 5465c7b
and keeps the auto-update's formatting of `src/SqliteArrowColumn.cpp`.

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

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should the Arrow arrays hold the values that dbFetch() gives where date32 and time64 can't?

With extended_types = TRUE, the Arrow chunk has NULL where its type can't hold a value: a time outside [00:00:00, 24:00:00), which dbFetch() keeps as an hms duration, and a day count beyond 32 bits or a huge or infinite real in a DATE column, which dbFetch() wraps or saturates into a date near 1970 (#878). Numeric seconds are rounded to microseconds, which time64[us] and timestamp[us] hold. The rules are in the comments at src/SqliteArrowColumn.cpp#L455-L461 and #L489-L496, the range check of time64 at #L541-L543, and the tests pin both sides. Against this pull request's head, built from source:

library(DBI)
con <- dbConnect(RSQLite::SQLite(), extended_types = TRUE)
dbExecute(con, "CREATE TABLE t (id INTEGER, d DATE, tm TIME)")
#> [1] 0
dbExecute(con, "INSERT INTO t VALUES
  (1, 4294967297, 86400), (2, 1e300, -1), (3, 0, '25:00:00')")
#> [1] 3

# dbFetch() wraps or saturates the days (#878) and keeps the times as durations
dbGetQuery(con, "SELECT d, tm FROM t ORDER BY id")
#>            d        tm
#> 1 1970-01-02  24:00:00
#> 2 1969-12-31 -00:00:01
#> 3 1970-01-01  25:00:00

# The Arrow chunk: NULL where date32 and time64 can't hold the value
res <- dbSendQuery(con, "SELECT d, tm FROM t ORDER BY id")
chunk <- RSQLite:::result_fetch_arrow_chunk(res@ptr, -1L)
nanoarrow::convert_array(chunk)
#>            d tm
#> 1       <NA> NA
#> 2       <NA> NA
#> 3 1970-01-01 NA
dbClearResult(res)
dbDisconnect(con)

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

  • Keep NULL for these values, which feat: Report values converted to an Arrow column's type once per chunk, with their rows #862 reports once per chunk; a wrapped date isn't a valid answer, and a time beyond the day isn't one that time64 can hold (recommended)
  • Hold times outside the day in a duration[us] column instead of time64, as dbFetch() keeps them, and leave the dates as they are
  • Copy dbFetch() exactly, wrapped dates included, so that both paths always agree

Kirill decides. If nobody decides, the arrays keep NULL, and fixing #878 on main brings dbFetch() closer to them.


Generated by Claude Code

krlmlr commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Question: should this pull request report the values that it turns into NULL?

The Arrow chunk puts NULL in place of text that isn't a date or time, of any blob, and of values beyond the range of its type, without a warning, where dbFetch() warns once per value: src/SqliteArrowColumn.cpp#L231-L236. #862, the next pull request of the stack, reports them once per chunk with their rows. The entry point result_fetch_arrow_chunk() stays internal until pull request 16, so no user sees the silent NULL in between. Against this pull request's head, built from source:

library(DBI)
con <- dbConnect(RSQLite::SQLite(), extended_types = TRUE)
dbExecute(con, "CREATE TABLE t (id INTEGER, d DATE)")
#> [1] 0
dbExecute(con, "INSERT INTO t VALUES (1, '2024-01-02'), (2, '2024-13-01'), (3, x'00')")
#> [1] 3

# dbFetch() warns for each value it can't convert
dbGetQuery(con, "SELECT d FROM t ORDER BY id")
#> Warning: Unknown string format, NA is returned.
#> Warning: Cannot convert blob, NA is returned.
#>            d
#> 1 2024-01-02
#> 2       <NA>
#> 3       <NA>

# The Arrow chunk has NULL in their place, without a warning
res <- dbSendQuery(con, "SELECT d FROM t ORDER BY id")
chunk <- RSQLite:::result_fetch_arrow_chunk(res@ptr, -1L)
nanoarrow::convert_array(chunk)
#>            d
#> 1 2024-01-02
#> 2       <NA>
#> 3       <NA>
dbClearResult(res)
dbDisconnect(con)

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

Kirill decides. If nobody decides, the values stay silent here and #862 reports them.


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

Two review rounds: the first confirmed that the parser refactor leaves dbFetch() unchanged (values bit-identical on 20,351 rows, all 67 warnings in text and order, speed) and raised as Medium the shared parser's misreading of negative UTC offsets, which is on main too; cfba409 read date and time text through value_text() (failing the chunk on out of memory), fixed the rounding at 2^52 to 2^53 µs and completed the description. The second found nothing above Low; 5465c7b rounds real seconds to the nearest microsecond of their double, as CPython does, and excludes −2^63 µs. #860's later heads and main are merged in since. This copy replaces the previous one: each limitation links its question, and the findings that main shows are issues now. These remain:

Found here, but on main too:


Generated by Claude Code

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants