Skip to content

feat: Add a UTF-8 validator for strings read from SQLite - #845

Merged
krlmlr merged 8 commits into
mainfrom
claude/utf8-infra
Nov 13, 2026
Merged

krlmlr merged 8 commits into
mainfrom
claude/utf8-infra

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

As asked on #799, which is reimplemented from main as a stack: this pull request adds the UTF-8 infrastructure, and #846 builds the checks of text columns on it.

rsqlite_is_utf8_string(), declared in src/utf8.h and defined in src/utf8.cpp, tells whether a byte range is well-formed UTF-8 without a NUL byte, which is what an R string can hold. It follows RFC 3629, so it rejects overlong forms, surrogates and code points beyond U+10FFFF. ASCII text is checked eight bytes at a time; a word that holds a NUL or a byte above 127 is checked sequence by sequence, and the loop then returns to whole words. text may be NULL when size is 0.

Nothing calls the validator yet, so there is no user-visible change. #795 carries its own copy of the validator for the Arrow path (src/utf8.h, with the fast path in src/SqliteArrowColumn.cpp); when it switches to this one is a question on #829. Defining the function in a .cpp file follows the recommended answer to the question about the header.

The unexported utf8_valid() exposes the validator to the tests, whose fixtures live in tests/testthat/helper-utf8.R, so every block runs on its own after load_all(). tests/testthat/test-utf8.R compares it with a reference built from base R (validUTF8() after a check for NUL bytes) on every 1- and 2-byte string, grids of 3- and 4-byte strings, padding across the eight-byte words, a NUL at every position up to 20 bytes, and random strings. Breaking the validator in six ways, one at a time (the limits after E0, ED and F4, NUL detection in the fast path and for single bytes, accepting C0 and C1), makes the tests fail each time. R CMD check --no-manual reports Status OK.

A clean review found nothing above Low; its three findings about what the tests can detect are fixed in eda8143, so the test hook now copies each input into a buffer with continuation bytes behind it and passes NULL for empty input, and what remains is under Accepted limitations.

https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE


Generated by Claude Code

`rsqlite_is_utf8_string()`, declared in `src/utf8.h` and defined in `src/utf8.cpp`, tells whether a byte range is well-formed UTF-8 without a NUL byte, which is what an R string can hold.
It follows RFC 3629, so it rejects overlong forms, surrogates, and code points beyond U+10FFFF.
ASCII text is checked eight bytes at a time.

Nothing calls the validator yet, so there is no user-visible change.
It is the shared infrastructure for checking text that is read from SQLite, in the data frame path and in the Arrow path.
The unexported `utf8_valid()` exposes it for the tests, which compare it with `validUTF8()` from base R.

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

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

CI note for #845 and #846: the smoke test failed on both before any R code ran. The shared install step could not resolve the Ubuntu package mirrors (Temporary failure resolving 'security.ubuntu.com', and the same for archive.ubuntu.com and azure.archive.ubuntu.com) while installing aspell, and stopped with exit code 100, as on the HTTP VFS stack since about 14:00 UTC (see #832). That is the runners' network, not these changes, and there is no fix to port. The jobs will be re-run once the mirrors resolve again; the fixes from the clean reviews of both pull requests will also trigger new runs.


Generated by Claude Code

krlmlr commented Nov 11, 2026

Copy link
Copy Markdown
Member Author

Review of this pull request at fe9f927, by a Claude Code reviewer with clean context that read the description and commit message, src/utf8.h, src/utf8.cpp, tests/testthat/test-utf8.R, the generated R/cpp11.R and src/cpp11.cpp, src/utf8.dd together with the dependency rules in src/Makevars, src/Makevars.deps and .Rbuildignore, and the copy of the validator in #795; built and installed the head commit and ran the new tests and R CMD check; copied the validator unchanged into a standalone harness and compared it with an independent reference on several billion inputs, also under ASan and UBSan, as a 32-bit build, and with a simulated big-endian load; checked the base R reference on four R versions; ran 18 single mutations against the tests; and posted nothing itself. "Confirmed" means reproduced by running code. The validator agreed with the reference on every input, and nothing blocking turned up; the three findings below are about what the tests can detect. On a pull request from a branch of this repository only the smoke test runs, and on fe9f927 it failed while installing system packages (apt could not resolve security.ubuntu.com), before the package was built, as the CI note above says; neither CI nor this review exercised macOS or Windows.

What was run

  • Built and installed with R 4.5.3, gcc 13.3 and -std=gnu++17. cpp11::cpp_register() regenerates R/cpp11.R and src/cpp11.cpp byte for byte.
  • test-utf8.R, with every result listed: 37 expectations, all successes, with no skip, warning or error.
  • R CMD check --no-manual with NOT_CRAN=true on a tarball built from git archive: Status OK. The suite reports [ FAIL 3 | WARN 6 | SKIP 61 | PASS 10415 ], and main gives the same with PASS 10378, so the only difference is the 37 new expectations. The three FAILs are the HTTP VFS tests that also error on main in this sandbox (see 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).
  • A standalone harness with the validator copied unchanged, compared with a reference that decodes code points and then rejects overlong forms, surrogates, values above U+10FFFF and U+0000. It covers every 1-, 2- and 3-byte string behind 0 to 15 ASCII bytes and again followed by 1 to 15 ASCII bytes; every 4-byte string with a lead byte of 80 or above, any second byte and 17 edge values in bytes 3 and 4, at the same offsets; every code point, encoded, at every offset and truncated at every length; 2-byte strings after runs of multibyte characters; and 20 million mutated random strings. That makes 5.96 billion cases with 0 disagreements under gcc -O2, and again with every 8-byte load byte-swapped to emulate a big-endian host. A 238-million-case subset also gives 0 disagreements with clang -O3 and with gcc -m32 (32-bit size_t).
  • The same subset under ASan and UBSan with -fno-sanitize-recover, with every input in an exactly sized heap block, plus NULL with size 0: no reports. As a control, the same build with the bound at L44 removed reports a heap-buffer-overflow.
  • The test's reference (the NUL check, then validUTF8(rawToChar())) compared with an RFC 3629 reference on R 4.1.3, 4.3.3, 4.5.3 and 4.6.2, over all 1- and 2-byte strings, all 3-byte strings with a lead byte of C0 or above, and 4-byte strings with a lead of E0 or above, any second byte and edge values in bytes 3 and 4: 0 disagreements on each version.
  • 18 single mutations of src/utf8.cpp, each rebuilt and tested: each limit after E0, ED, F0 and F4; C0, C1 and F5 accepted as leads; the continuation ranges; NUL in each path; the fast-path predicate; the end-of-buffer bound in three ways; and the sequence loop running past the end. 17 of them make the tests fail. The survivor never returns to the word loop, which only makes it slower.
  • On 64 MiB buffers the validator checks ASCII at 4.8 GB/s, against 0.26 GB/s for the same checker going byte by byte. On text with a 2-byte character every 9 bytes both run at 0.32 GB/s, so the word loop pays off and costs nothing on mixed text.

What holds

  • The byte ranges are those of RFC 3629: C2–DF; E0 then A0–BF; E1–EC and EE–EF; ED then 80–9F; F0 then 90–BF; F1–F3; F4 then 80–8F. Every other lead byte is rejected. Both paths reject a truncated sequence at the end and a NUL anywhere.
  • ((word - ones) | word) & highs is zero exactly when all eight bytes are in 1..127, whatever the byte order: the least significant zero byte always borrows, and the borrow only affects bytes above it. After a word fails, the sequence loop runs to the end of that word, possibly up to three bytes past it, and the next word is then loaded through memcpy from whatever offset that leaves.
  • There is no read beyond size: the length is checked before s[1], size - i cannot underflow, i + 8 <= size whenever a word is read, and no arithmetic can overflow for any size. NULL with size 0 is never dereferenced.
  • The code is portable as written: only memcpy, <stdint.h> and unsigned arithmetic, with no intrinsics and no alignment assumptions. It compiles cleanly with gcc -Wall -Wextra -pedantic -Wconversion -Wsign-conversion -Wcast-align=strict as C++98 and as C++11.
  • Packaging: src/utf8.dd has the same shape as the other .dd files and is left out of the tarball with them. utf8_valid() is in the namespace but not exported, since NAMESPACE lists its exports one by one. The new symbols are local to RSQLite.so and clash with nothing in the vendored code.
  • The base R reference is sound on every R version the tests can run on. DESCRIPTION says R (>= 3.1.0) and validUTF8() only arrived in R 3.3.0, but testthat 3 needs R 4.1.0 and cpp11 needs R 4.0.0, so no supported test run is affected.
  • The description's claims hold. Only the test hook calls the validator, and the suite matches main apart from the new tests, so nothing user-visible changes. The six mutations it lists make the tests fail (reproduced). The declaration matches the inline one in feat: Implement the DBI Arrow interface natively #795, so feat: Implement the DBI Arrow interface natively #795 can switch to it by dropping its own header; until then the two src/utf8.h files have the same path and include guard and will conflict, as the description says.

High

None.

Medium

None.

Low

1. The truncation tests cannot detect a read past the end (Confirmed). src/utf8.cpp#L98: the hook passes R's own vector memory to the validator. R allocates raw vectors in 8-byte units, so a validator that reads past size reads spare or neighbouring bytes instead of failing. With the bound at L44 removed, and in two separate mutations passing size instead of size - i at L81 and loosening the bound by one, the test "truncated sequences at the end are invalid" still passed in all three cases, in repeated runs. The bulk comparisons with base R did catch them, but only because of whatever bytes happen to sit after the vector: one of those tests caught the first mutation in one run and missed it in the next run of the same build. The validator is correct here (ASan saw no overread), so this is about keeping it correct under later changes, for example when #795's fast path moves in. Suggested fix: copy the input into a buffer with continuation bytes after it, so that a read past size reliably turns a truncated sequence into a valid one and the test fails; with that change, all three mutations fail the truncation test every time, and the current validator still passes.

2. No test passes NULL (Confirmed). src/utf8.h#L10 promises that text may be NULL when size is 0, but RAW() of raw(0) is not NULL, so utf8_valid(list(raw())) at test-utf8.R#L143 passes a valid pointer. The current code handles NULL correctly (confirmed under UBSan in the standalone build). The promise matters for callers that pass pointers straight from SQLite, which returns NULL for SQL NULL values and for zero-length blobs. Suggested fix: pass NULL for empty input in the hook; the existing empty-input test then covers it.

3. The test for non-raw input accepts any error (by reading). At test-utf8.R#L201, expect_error(utf8_valid(list("a"))) would also pass on "could not find function" if the hook were renamed or lost its registration. Suggested fix: expect_error(utf8_valid(list("a")), "expected 'raw'"); cpp11's message is "Invalid input type, expected 'raw' actual 'character'" (confirmed).


Generated by Claude Code

The test hook utf8_valid() now copies each input into a buffer with three continuation bytes behind it.
A validator that reads past the end then sees a truncated sequence as valid, and the truncation tests fail.
Empty input is passed to the validator as NULL, which the header allows, so the empty-input test covers it.
The non-raw input test now checks for cpp11's "expected 'raw'" message instead of accepting any error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The build regenerated it with system headers, and the previous commit picked that up by mistake.
The includes did not change, so the committed file stands.

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

krlmlr commented Nov 11, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by the current copy.

The clean review found nothing above Low. Its three Low findings, all about what the tests can detect, are fixed in eda8143: the test hook copies each input into a buffer with continuation bytes behind it, so that a read past the end fails the truncation tests, passes NULL for empty input, and the test for non-raw input expects cpp11's message. 1dc1f28 only removes a generated build file that eda8143 added by mistake. This remains:


Generated by Claude Code

claude and others added 3 commits November 11, 2026 15:27
`load_all()` sources `tests/testthat/helper*.R` but not the top level of a test file.
`utf8_reference()`, `hex()`, `ascii()`, `pad()` and `expect_utf8()` move to `helper-utf8.R`.
Helper files are shared by every test file, so the generic `hex()`, `ascii()` and `pad()` become `raw_hex()`, `raw_ascii()` and `raw_pad()`.
Every `test_that()` block of `test-utf8.R` now runs on its own after `load_all()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd3gjmufoKCWVDBPCgE
The CI's auto-update regenerated `src/cpp11.dd` and `src/utf8.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/utf8.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: avoid the conflict on src/utf8.h with #795?

#795 adds its own src/utf8.h, with the same path and include guard as this pull request but an inline definition of the validator, so whichever of the two merges second conflicts there. The conflict resolves by keeping this declaration and dropping #795's copy. #795 is now a draft that the reworked Arrow stack replaces, and that stack uses this validator, so the conflict only arises if #795 is merged after all.

If nobody decides, the conflict stays as described and is resolved as above if it ever comes up.


Generated by Claude Code

krlmlr commented Nov 13, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

The clean review found nothing above Low. Its three Low findings, all about what the tests can detect, are fixed in eda8143: the test hook copies each input into a buffer with continuation bytes behind it, so that a read past the end fails the truncation tests, passes NULL for empty input, and the test for non-raw input expects cpp11's message. 1dc1f28 only removes a generated build file that eda8143 added by mistake. This remains:


Generated by Claude Code

@krlmlr
krlmlr merged commit 36cb103 into main Nov 13, 2026
8 checks passed
@krlmlr
krlmlr deleted the claude/utf8-infra branch November 13, 2026 19:45
@krlmlr krlmlr mentioned this pull request Nov 14, 2026
16 of 22 tasks
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