Skip to content

Faster ORDER BY ... COLLATE: compare UTF-8 directly in ICU - #126829

Merged
thevar1able merged 2 commits into
ClickHouse:masterfrom
groeneai:collator-strcoll-utf8
Oct 20, 2026
Merged

thevar1able merged 2 commits into
ClickHouse:masterfrom
groeneai:collator-strcoll-utf8

Conversation

@groeneai

@groeneai groeneai commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126735

Changelog category (leave one):

  • Performance Improvement

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

ORDER BY ... COLLATE is up to 3 times faster: strings are now compared with ICU's UTF-8 collation API instead of a character iterator. Comparing a string of 2 GiB or more under a collation now throws TOO_LARGE_STRING_SIZE instead of returning a wrong order.

Description

Collator::compare, used by every collated string comparison, wrapped both strings in UCharIterators and called ucol_strcollIter: an indirect call per code unit and no fast path. ucol_strcollUTF8 compares the common prefix bytewise, uses ICU's Latin fast path and otherwise iterates UTF-8 directly.

The order does not change: both APIs decode each maximal ill-formed UTF-8 subsequence as U+FFFD and keep embedded zero bytes. Sorting 150k generated strings (48% ill-formed) under all 145 system.collations locales and 10 modifier variants gives the same order on master and with this PR. The new SQL test pins the order of valid and ill-formed strings under 12 collations (reference generated on master).

ucol_strcollUTF8 reads a negative length as a NUL-terminated string, so a string of 2 GiB or more (ICU lengths are int32_t) is now rejected with TOO_LARGE_STRING_SIZE; a unit test covers this, as SQL cannot build such a string cheaply. Before, it was compared with a wrapped-around length: on master, ORDER BY s COLLATE 'en' puts a 3,072,000,000-byte string before 'b'.

Release build, 20M rows, max_threads = 16, medians of 11 rotated rounds (two master servers agreed within 12%):

Query master this PR
ORDER BY s COLLATE 'en' LIMIT 10, ASCII 653 ms 264 ms
same, Cyrillic, 'ru' 785 ms 506 ms
same, CJK, 'zh' 492 ms 284 ms
full sort of 2M ASCII strings, 'en' 5383 ms 1694 ms
kway_merge_expensive_comparator.xml query 3 7557 ms 3292 ms
ORDER BY s LIMIT 10, no COLLATE (60 runs) 102 ms 104 ms

Non-Latin text and numeric collation ('en-u-kn-true': 950 to 820 ms) gain less: they miss the Latin fast path. The existing perf tests kway_merge_expensive_comparator.xml and collations.xml cover both.


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

Version info

  • Merged into: 26.11.1.318-master (included in 26.11 and later)

groeneai and others added 2 commits October 19, 2026 21:28
`Collator::compare` wrapped both strings in `UCharIterator`s (`uiter_setUTF8`)
and called `ucol_strcollIter`. That path
(`RuleBasedCollator::compare(UCharIterator &, UCharIterator &)`,
contrib/icu/icu4c/source/i18n/rulebasedcollator.cpp) reads every code unit
through an iterator function pointer and has no `CollationFastLatin` path.
`ucol_strcollUTF8` (`internalCompareUTF8` -> `doCompare(const uint8_t *, ...)`)
skips the common prefix bytewise, tries `CollationFastLatin::compareUTF8`, and
otherwise iterates UTF-8 directly with `(FCD)UTF8CollationIterator`.

The order is unchanged. Both entry points decode ill-formed UTF-8 with the
same maximal-subpart U+FFFD policy (`utf8IteratorNext` in common/uiter.cpp,
`UTF8CollationIterator::handleNextCE32`, and `UTF8NFDIterator` for the
identical level all use `U8_NEXT_OR_FFFD`), and with explicit lengths both
treat a zero byte as U+0000. ICU's own collationtest.cpp checks the UTF-16,
UTF-8 and UCharIterator APIs against each other.

`internalCompareUTF8` reads a negative length as NUL-terminated (`uprv_strlen`),
whereas `uiter_setUTF8` turned a length below -1 into an empty iterator.
`ColumnString` values are not NUL-terminated, so passing
`static_cast<int32_t>(length)` for a string longer than `INT32_MAX` bytes would
read past the value. All ICU collation lengths are `int32_t`, so such a string
cannot be compared correctly at all; throw `TOO_LARGE_STRING_SIZE` instead.
Previously it was compared with a wrapped-around length (a 3,072,000,000-byte
string sorted before 'b').

Alternatives not taken: keeping the old iterator path for long strings (it
only reproduces the wrong order), and per-row sort keys (`ucol_getSortKey`),
which would change the sorting design rather than the comparison.

Related: ClickHouse#126735

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Checks that `Collator::compare` rejects a length above `INT32_MAX` for either operand with `TOO_LARGE_STRING_SIZE`; SQL cannot reach a value of 2 GiB or more cheaply.

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

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

Pre-publication review by an independent model (engine: codex; 2 distinct findings over 4 runs; the last run, on the final head, found nothing).

# Sev Finding Verdict Evidence / action
1 ⚠️ The TOO_LARGE_STRING_SIZE length check in Collator::compare had no test (src/Columns/Collator.cpp:143) AGREE, fixed @ a8f1daf SQL needs a value of 2 GiB or more, so a unit test (gtest_collator.cpp) checks lengths above INT32_MAX on either operand; it fails with the check removed, without reading past the buffer
2 💡 The description said "longer than 2 GiB" (the check rejects exactly 2^31 bytes too) and the changelog entry did not mention the new exception AGREE, fixed Description and entry say "2 GiB or more" and name the exception

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

Session id: cron:clickhouse-review-slot-8:20261019-223300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Release build, max_threads = 16: kway_merge_expensive_comparator.xml query 3 (ORDER BY s COLLATE 'en' over 5M strings) 7557 ms on master vs 3292 ms with this PR (medians of 11 rotated runs; a second master instance gave 7757 ms). The 2 GiB case: WITH repeat(repeat('c', 1024), 1000000) AS p SELECT length(s) FROM (SELECT arrayJoin([concat(p, p, p), 'b']) AS s) ORDER BY s COLLATE 'en' returns 3072000000, 1 on master.
b Root cause explained? ucol_strcollIter walks both strings through UCharIterator function pointers (one indirect call per code unit) and has no fast path; ucol_strcollUTF8 compares the common prefix bytewise, uses CollationFastLatin, else iterates UTF-8 directly.
c Fix matches root cause? Yes: the API switch at the only ICU comparison call in src/. The length check covers the one contract difference of the new API (a negative int32_t length means NUL-terminated, and ColumnString values are not NUL-terminated).
d Test intent preserved / new tests added? New 05408_collation_ill_formed_utf8 pins the order of 59 valid and ill-formed strings under 12 collations with both tie-breaks (reference generated on master). Two mutants (truncating at NUL; dropping ill-formed sequences) both fail it. A unit test (gtest_collator.cpp) checks that a length above INT32_MAX on either operand is rejected; it fails with the length check removed. No new perf test: kway_merge_expensive_comparator.xml and collations.xml cover both text classes.
e Both directions demonstrated? Same output on master and with this PR: the new test, all 37 collation tests, and a differential sort of 150k strings (48% ill-formed) under all 145 locales + 10 modifiers (310 sort orders, identical). Faster in every COLLATE arm (1.2x to 3.2x); no-COLLATE control unchanged (102 vs 104 ms, 60 runs). 2 GiB case: master orders the 3 GB string as empty, this PR throws TOO_LARGE_STRING_SIZE.
f Fix is general across code paths? Every collated comparison (ColumnString permutation comparator, compareAtWithCollation, and the Nullable / LowCardinality / Array / Tuple wrappers delegating to them) goes through Collator::compare.
g Fix generalizes across inputs (params/datatypes/wrappers)? Lone continuation bytes, overlongs, surrogates, > U+10FFFF, truncated sequences, NUL, U+FFFD/FFFE/FFFF, empty strings; every system.collations locale plus strength, numeric, alternate, case-first and phonebook modifiers; wrapper types via existing tests 01532/01533/01542/01543; lengths 2,048,000,000 (sorted correctly) and 3,072,000,000 (rejected).
h Backward compatible? (maintainer-approved exception only) Same order for every string up to INT32_MAX bytes; no setting, format or serialization change. A longer string under COLLATE now throws instead of being ordered by a wrapped-around length (no ICU API accepts longer strings).
i Invariants and contracts preserved? Same strict weak order and -1/0/1 result; U_FAILURE handling unchanged; the length check runs before any ICU call and allocates nothing; the shared const UCollator * is used read-only, as before.

Session id: cron:clickhouse-impl-slot-4:20261019-194800

@thevar1able thevar1able self-assigned this Oct 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8f1daf]

Summary: ✅


AI Review

Summary

The PR switches Collator::compare to ucol_strcollUTF8 to accelerate ORDER BY ... COLLATE, rejects lengths exceeding INT32_MAX before calling ICU, and adds ordering and length-boundary regression tests. No actionable findings at head a8f1daf5d67bb76c2b28e72ff24fb8d54183c414; the supplied benchmarks support the performance claim.

Missing context / blind spots
  • ⚠️ No local ClickHouse build or binary is available, so the SQL and unit tests were not rerun during this review. The author reports successful local validation; ICU-enabled stateless, unit, and performance CI jobs remain pending. Their completed results would close independent execution coverage; the passing fast test excludes the new ICU-dependent SQL test.
Final Verdict

Status: ✅ Approve. No source changes requested; pending CI results remain to be checked before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @thevar1able @azat, could you review this and add the can be tested label so CI runs? Collator::compare now calls ucol_strcollUTF8 instead of wrapping both strings in UCharIterators for ucol_strcollIter (same order, including ill-formed UTF-8), and rejects strings of 2 GiB or more, whose length ICU cannot take as int32_t.

@thevar1able thevar1able added the can be tested Allows running workflows for external contributors label Oct 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a8f1daf5d with master fefdea4c1 (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, 6 s compile time in total, 7 of them have a recent master baseline.

Job report

@thevar1able
thevar1able enabled auto-merge October 20, 2026 14:05
@thevar1able
thevar1able added this pull request to the merge queue Oct 20, 2026
Merged via the queue into ClickHouse:master with commit abd790a Oct 20, 2026
353 of 354 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 20, 2026
BorisTyshkevich pushed a commit to BorisTyshkevich/ClickHouse that referenced this pull request Nov 15, 2026
The collation sort (#2, 5M rows) and the single-column string sort (ClickHouse#3,
20M rows) take 1.2-1.9 s on MasterCI on both arches. They get
disabled="1" (text and number unchanged) and are appended as ClickHouse#9 and ClickHouse#10
on a quarter of the rows with max_block_size = 16384, a quarter of the
default 65409. `numbers_mt` hands out blocks of exactly max_block_size
rows, so each copy has as many blocks as its original (77 and 306): the
same number of cursors in every per-stream merge and the same 16-stream
final merge, with a quarter of the rows per block. EXPLAIN PIPELINE of
each original and its copy is identical (16 streams).

Measured on official MasterCI release builds, two servers pinned to 24
cores of one NUMA node, perf.py, 25 runs: copy / original time 0.248
(#2) and 0.252 (ClickHouse#3), projected CI medians 380 / 487 ms amd, 298 / 483 ms
arm. On the builds before/after ClickHouse#115869 (sorted array of cursors) #2 is
1.161x faster and its copy 1.159x; on those before/after ClickHouse#126829
(cheaper collation) 2.179x and 2.111x; ClickHouse#3 and its copy show no change
on either pair (1.005 / 1.008, 1.004 / 1.001), as the heap guard should.

#0 and #1 stay as they are: on this rig the ClickHouse#115869 change did not show
on them beyond the A/A resolution, so there was no measured guarantee
that copies would keep their sensitivity.

About 32 s (amd) and 29 s (arm) of query time less per master
performance job; 9 queries stay enabled, so all of them still run.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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... 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.

3 participants