Skip to content

Validate many rows per simdutf call in isValidUTF8 - #123835

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:is-valid-utf8-ascii-column-pass
Oct 7, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
groeneai:is-valid-utf8-ascii-column-pass

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

isValidUTF8 validates a String or FixedString column with one simdutf call over the whole column instead of one call per row, which makes it up to 2.7 times faster on short strings.
isValidUTF8 validates a String or FixedString column with one simdutf call over the whole column instead of one call per row, which makes it up to 2.8 times faster on short strings.

Description

isValidUTF8 called DB::UTF8::isValidUTF8 once per row. Now it calls simdutf::validate_utf8_with_errors from the current row to the end of the column. The bytes before the first error are valid UTF-8, so a row there is valid iff the byte after it is not a continuation byte (its start is checked as the previous row's end); the row holding the error is invalid, and the call restarts from the next row. Builds without simdutf keep the per-row loop.

Invalid UTF-8 is assumed to be rare. A column where every row is malformed pays one simdutf call per row and is slower than master (1-byte rows 3.7 times, 5-byte rows 2.7 times). The all-malformed perf query 7 is replaced by a column with one malformed row in 1000.

Release build, CPU cycles of 100 runs of each query in one process, median of 3 rounds, startup subtracted, this PR / master:

is_valid_utf8.xml query ratio
0: 8 ASCII bytes 0.67
1: 1023 ASCII bytes 0.96
2: 21 x 3-byte + 2 ASCII 0.95
3: 341 x 3-byte 0.95
4: 96 ASCII + 26 x 2-byte 1.00
5: 6 x 2-byte 0.36
6: 4 x 4-byte 0.35
7: 1 malformed row in 1000 0.57
repeat('a', 100000) || 'Ñ', 1000 rows 1.00
old 7: '\xFF' and 15 a on every row 1.21

00934_is_valid_utf8 gains rows that are malformed or split a code point, as String and FixedString. Results match master on seven generators of 6M rows (split code points, random bytes, sparse malformed rows) at block sizes 1, 7, 1000 and 65536.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/123835]

Version info

  • Merged into: 26.10.1.1766-master (included in 26.10 and later)

isValidUTF8 called DB::UTF8::isValidUTF8 once per row. For short strings
the query is a tight per-row call loop into a small function in another
translation unit, and on the CI runners its speed depends on code
placement: across 16 CI builds whose code for both functions is identical,
`is_valid_utf8` query #0 (8-byte ASCII rows) is about 20% slower exactly
in the builds where the loop's cache lines alias (mod 4 KiB) the callee's
hot lines. The performance comparison then reports a confirmed regression
on PRs that do not touch this code.

Now the String and FixedString paths find the length of the column's
leading run of ASCII bytes with one simdutf::validate_ascii_with_errors
call. Rows that end inside that run are valid without being visited; the
row that holds the first non-ASCII byte is validated from that byte (a
leading ASCII run never changes the verdict), and the per-row loop
continues from the next row. An all-ASCII column no longer runs the
per-row loop at all. Builds without simdutf skip the shortcut.

Local A/B, release build (non-LTO), cycles:u of 100 x the query in one
process, medians over 5 rounds and over 4 (base) / 3 (fix) code layouts
(the callee moved by 0 to 3008 bytes, code unchanged):

  query                                     base    fix     fix/base
  #0 repeat('a', 8), 3M rows                3.09e9  1.65e9  0.54
  ClickHouse#2 21 x 3-byte + 'aa', 3M rows            11.6e9  11.7e9  1.01
  ClickHouse#4 96 ASCII + 26 x 2-byte, 3M rows        18.2e9  18.5e9  1.02
  ClickHouse#5 6 x 2-byte, 3M rows                    7.31e9  7.33e9  1.00
  ClickHouse#6 4 x 4-byte, 3M rows                    8.07e9  7.97e9  0.99
  ClickHouse#7 '\xFF' + 15 x 'a', 3M rows             10.8e9  9.94e9  0.92

Single layout: ClickHouse#1 (1023-byte ASCII rows) 0.95, ClickHouse#3 (1023-byte CJK) 1.00.
SELECT isValidUTF8(materialize(repeat('a', 8))) FROM numbers(300000000):
0.689 s -> 0.325 s (median of 15 runs each, 4 cores).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new 00934 lines cannot tell the column pass from the old per-row path: returning 0 from asciiPrefixLength keeps every result, so nothing rejects a no-op shortcut DISAGREE On String a no-op is the old per-row loop, 1.87x the fix's cycles on is_valid_utf8 #0, which the Performance Comparison already flags (it confirmed a 1.19x excursion). Two boundary mutations that are no-ops at prefix 0 each turn the new lines red on String and FixedString.
2 💡 Folding the mixed row into the per-row loop (prev_offset = prefix) is a few lines shorter noted Equivalent, and measured equal within noise. Kept as is.
3 💡 The non-ASCII per-row path costs a few instructions per row more (vector is no longer inlined) noted Queries #2 to #7 measure 0.92x to 1.02x of base cycles over several code layouts. This is within the layout spread of those queries.
4 💡 No is_valid_utf8.xml query now reaches the per-row 8-byte ASCII arm of DB::UTF8::isValidUTF8 noted Deliberate. A query for it would bring back a per-row loop sensitive to placement. The file comment says #0 and #1 measure the column pass.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261004-064300

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78c9df7]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 1/6) FAIL Performance dashboard
float_formatting #25 FAIL dashboard IGNORED
float_formatting #1 slower query history IGNORED
Stateless tests (arm_asan_ubsan, azure, sequential) ERROR IGNORED

AI Review

Summary

This PR changes isValidUTF8 so the String and FixedString vector paths validate the concatenated column with simdutf and then recover per-row results from row boundaries, restarting after invalid rows. I do not see a remaining correctness, safety, or contract issue in the current implementation, and the added row-boundary coverage matches the new algorithm’s critical cases. The only issue I found is a duplicated Changelog entry line in the PR body.

PR Metadata
  • 💡 Changelog category: Performance Improvement matches the actual change.
  • 💡 Changelog entry: required for this category, and the current entry is specific and user-readable, but it is duplicated in the PR body. Replace the two lines with exactly one line:
    isValidUTF8 validates a String or FixedString column with one simdutf call over the whole column instead of one call per row, which makes it up to 2.8 times faster on short strings.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit 78c9df7: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_3.profdata.

Comment thread src/Functions/isValidUTF8.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78c9df77e with master af72d84f3 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 7 s compile time in total, 7 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

no significant changes detected. K_source=5 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 54cbaa35-b458-4715-aeac-6b3265630407
  • MIRAI run: 33d93b46-c06e-40ae-b04a-9e3ac328913a
  • PR check IDs:
    • clickbench_98761_1791334345
    • clickbench_98861_1791334387
    • tpch_adapted_1_official_98999_1791334429
    • tpch_adapted_1_official_99163_1791334448
    • tpch_adapted_1_official_99271_1791334455

@rschu1ze

rschu1ze commented Oct 4, 2026

Copy link
Copy Markdown
Member

@groeneai Sorry, I won't find time to review.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b3a760c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 05023_lazy_url_glob_expansion not from this PR, which changes isValidUTF8 only: with parallel replicas url is served by StorageURLCluster, which reads several addresses at once, so the LIMIT 1 arm prints 1 instead of 0. The same failure hit 9 other PRs and master in the last 3 days #123815 (mine, open)
Mergeable Check, PR rollups of the row above #123815 (mine, open)

CIDB has no other FAIL or ERROR row on this head, and CH Inc sync passed.

Session id: cron:our-pr-ci-monitor:20261004-113103

@Algunenano Algunenano self-assigned this Oct 4, 2026

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 things:

  • I don't understand why we apply this optimization using ascii.
  • This isn't fixing the reported issue.

It seems this PR is mixing 2 issues and I don't like it:

  • If the problem is that depending on the alignment of simdutf (or at least that's what I understood), then we should find the proper way to address this, ideally globally.
  • The idea of validating whole columns instead of row per row makes sense, but why put a fastpath for ascii. It seems it's done just purely to improve the performance query but I don't see any validation on the decision and why not use the more universal isValidUTF8. For example if I do: SELECT isValidUTF8(materialize(repeat('a', 100000) || 'Ñ')) FROM numbers(1) you've added an expensive check for no reason. Not only that, but if we wanted to have a fast path that consider ASCII first shouldn't that be inside validate_utf8_with_errors?

groeneai and others added 2 commits October 5, 2026 13:28
…II prefix

Replace the ASCII-prefix pass with validate_utf8_with_errors over chunks of
1024 rows. The bytes before the first error are valid UTF-8, so a row there
is valid iff the byte after it is not a continuation byte. Rows from the
first error to the end of the chunk are validated one at a time, as before.
This covers every valid column, not only ASCII, and a long row is validated
once, as on master. Chunks keep the row boundaries in cache and bound the
cost of a malformed row to the rest of its chunk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Validate the leading ASCII run of a column in one pass in isValidUTF8 Validate many rows per simdutf call in isValidUTF8 Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Both points are right; I reworked the PR in e97f093 and e3bcf3c.

The reported issue. This PR does not fix it, so I removed it from the description. For the record, query #0 never reaches simdutf: its 8-byte rows end in the scalar ASCII loop of DB::UTF8::isValidUTF8. The extra time is in the per-row call loop, in the builds where that loop and the callee's loop share their addresses mod 4 KiB, official master builds included. Any per-row loop can show this, and I don't have a measured global fix for it.

The ASCII path. There was no good reason for it. validate_utf8_with_errors already skips ASCII blocks inside its checker, so the PR now calls only that, once per 1024 rows. The bytes before the first error are valid UTF-8, so a row there is valid iff the byte after it is not a continuation byte; rows from the first error to the end of the group are validated one at a time, as before. A long row is validated once, as on master: your repeat('a', 100000) || 'Ñ' over 1000 rows takes 0.99x of master's cycles.

Validation. Release build, cycles, this PR / master, startup subtracted: is_valid_utf8 #0 0.68, #1 0.96, #2 0.75, #3 0.96, #4 0.86, #5 0.35, #6 0.36, #7 unchanged (same instruction count), one malformed row in 1000 0.80. I use groups rather than one pass over the whole column because with one pass the 1023-byte and 148-byte queries took about 4% more cycles than master, and a malformed row now costs at most the rest of its group.

@groeneai
groeneai requested a review from Algunenano October 5, 2026 14:06
Comment thread src/Functions/isValidUTF8.cpp Outdated

static void vector(const ColumnString::Chars & data, const ColumnString::Offsets & offsets, PaddedPODArray<UInt8> & res, size_t input_rows_count)
/// Rows validated in one pass, few enough that their bytes are still in cache when the row boundaries are checked.
static constexpr size_t chunk_rows = 1024;

@Algunenano Algunenano Oct 5, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't make sense. Why 1024 rows? Why not use a byte based approach?

Also, in general this doesn't make much sense anyway. Why do we need to keep the bytes still in cache? We can call simdutf::validate_utf8_with_errors for the whole column, then mark as 1 all the covered rows and 0 the failed one, then start back from failed + 1 to end and keep going till the end. The performance of all failures should be equivalent to know, and we skill many calls (or all but one) when everything is valid

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 0e3fc07: no grouping. simdutf::validate_utf8_with_errors runs from the current row to the end of the column, the covered rows get 1, the failing row 0, then it restarts.

One addition, measured: restarting right after every invalid row made a column of 1-byte invalid rows 3.7x slower than master (5-byte rows 2.7x), since each row then paid a full simdutf call. So the rows after an invalid one are checked one by one up to the next valid row, and then the column-wide call restarts. Runs of invalid rows are back at master ('\xFF' on every row 1.07x, query #7 0.94x); an invalid row on every second row is 1.24x.

On the cache question, it is only speed: with the same instruction counts, the whole-column version is 0.95x / 1.02x of master on queries #2 / #4, while bounding each call (1024 rows, or a 256 KiB byte budget) gave about 0.75-0.8x / 0.85x, because the boundary loop rereads one byte per row after the block has left L2. I kept the whole column as you suggested. The description has the updated numbers.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One addition, measured: restarting right after every invalid row made a column of 1-byte invalid rows 3.7x slower than master (5-byte rows 2.7x), since each row then paid a full simdutf call.

Why? Is it because master calls DB::isValidUTF8 which does different things based on the length? Why don't we call DB::isValidUTF8 here too? How does it measure?

On the cache question, it is only speed: with the same instruction counts, the whole-column version is 0.95x / 1.02x of master on queries #2 / #4, while bounding each call (1024 rows, or a 256 KiB byte budget) gave about 0.75-0.8x / 0.85x, because the boundary loop rereads one byte per row after the block has left L2

I don't understand why / were we reread one byte per row. Can you point it to me and explain it? I'm missing it

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? Is it because master calls DB::isValidUTF8 which does different things based on the length? Why don't we call DB::isValidUTF8 here too? How does it measure?

Yes. DB::UTF8::isValidUTF8 enters simdutf only from 64 bytes (or from 16 bytes left after its ASCII skip), so on master a 1-byte '\xFF' row is rejected by the scalar walk. Restarting after every invalid row called simdutf::validate_utf8_with_errors on the rest of the column once per row: a dispatch, the AVX-512 kernel, then the scalar rewind that locates the error. On '\xFF' rows that was 181 instructions per row for the whole query against 52 on master, and perf record puts 108 of them in simdutf (kernel 60, rewind 29, dispatch 18).

Calling DB::UTF8::isValidUTF8 is what the addition does: lines 53-58 check each row after an invalid one with it (through the wrapper on line 21) until one is valid, then restart the column-wide call. That call has to stay validate_utf8_with_errors, since it needs the error position to know which rows it covered.

How it measures (release builds of master and both versions, same compiler, no LTO; each query 100 times per clickhouse local process pinned to 4 cores; perf stat cycles minus a SELECT 1 process; ratio to master):

  • '\xFF' on every row: restart only 3.69x, this PR 1.07x
  • 'abcd\xC3' on every row: 2.70x, 1.12x
  • query 7 ('\xFF' and 15 a): 1.21x, 0.94x

I don't understand why / were we reread one byte per row. Can you point it to me and explain it? I'm missing it

It is the data[end] load on line 42. simdutf validated [begin, valid_end) as one string, but a row boundary can still fall inside a code point: a row ending in '\xC3' followed by a row starting with '\xB1' is valid together and invalid on its own. So each row's verdict needs the first byte of the next row, and the loop reads it after simdutf has streamed the whole column. In query 2 a block is 65409 rows of 65 bytes, about 4.3 MB, more than the 2 MB L2, and at 65 bytes per row nearly every such byte is in its own cache line, so the loop brings the block back from L3.

mem_load_retired.l2_miss over 100 runs of query 2 (300M rows): master 4.3M, 1024 rows per call 6.0M, whole column 286M, and perf annotate puts 94% of them on that load (cmpb $0xc0,(%r12,%rsi,1)). Query 4 (148-byte rows): 36M vs 342M. Query 5 (12-byte rows, a 785 KB block that fits in L2): 1.3M vs 1.5M, about the same cycles. That reread is why I had bounded the calls: bounding keeps those bytes in L2.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm sorry, but I think we are optimizing the wrong thing. Invalid UTF8s are really unlikely. Optimizing for rows with one single byte and it being invalid doesn't make any sense.

We should assume the bytes are valid by default or that the likelyhood is very low. Obviously there are use cases where most will be invalid, but I'm not sure those fit well inside a database. Please focus on real use cases and not on corner cases. Tune the performance test queries if you need to.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 78c9df7: after an invalid row the column-wide call now simply restarts from the next row, as you proposed, and the per-row run is gone. In the perf test I replaced the all-malformed query 7 with a mostly valid column that has one malformed row in 1000.

Release build vs master, cycles: query 0 0.67, query 1 0.96, query 2 0.95, query 3 0.95, query 4 1.00, query 5 0.36, query 6 0.35, the new query 7 0.57, and your repeat('a', 100000) || 'Ñ' example 1.00. A column where every row is malformed is slower now (1-byte rows 3.7x); the description states it.

Drop the grouping of 1024 rows per call. simdutf::validate_utf8_with_errors
now runs from the current row to the end of the column; every row ending
before the first error is valid unless it ends inside a code point, and the
row holding the error (or ending inside a code point) is invalid.

The rows after an invalid one are checked one by one up to the next valid
row, and the column-wide call restarts after it. Restarting the call right
after every invalid row made a column of 1-byte invalid rows 3.7x slower
than the per-row check, since each row then paid a whole simdutf call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai requested a review from Algunenano October 5, 2026 17:39
Invalid UTF-8 is rare in practice, so after an invalid row the column-wide
simdutf call simply restarts from the next row, as suggested in review. A
column where most rows are invalid pays one simdutf call per row; that case is
not worth extra code.

The all-malformed perf query is replaced by a mostly valid column with one
malformed row in 1000, which exercises the restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 78c9df7

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) job timeout, not from this PR: the job was killed at its 9000 s limit after test 1143 of 1168, with no failed test. The same job timed out on 46 other runs since 2026-10-05 (38 PRs, 8 master runs) #123849 (mine, open), which splits this job into 2 batches
Performance Comparison (amd_release, master_head, 1/6) / float_formatting #25, #1 #25 is a dashboard confirmed_regression, client_time 0.082 -> 0.227 s (+176%), still +180% after the harness restarted both servers; the shard report also calls #1 slower (0.059 -> 0.209 s). The queries are toString(toFloat64(rand())) and toString(toFloat64(number % 2)): they never call isValidUTF8, the only function this PR changes, and two earlier heads of this PR ran the same test without these rows. Same per-binary code-placement class on amd as the other float_formatting reds (#1 was slower on 6 other runs in 7 days, master included) a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the rows above #123849 and a fix task is created (the same owners as above)

All 149 check runs completed and Finish Workflow is green. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261007-033349

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good

@Algunenano
Algunenano added this pull request to the merge queue Oct 7, 2026
Merged via the queue into ClickHouse:master with commit b11de69 Oct 7, 2026
146 of 149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants