Skip to content

Use simdutf for base64 - #108333

Merged
thevar1able merged 22 commits into
masterfrom
simdutf-base64
Jul 16, 2026
Merged

thevar1able merged 22 commits into
masterfrom
simdutf-base64

Conversation

@thevar1able

@thevar1able thevar1able commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Use simdutf library for base64.

Changes in performance

aarch64


┌─────┬─────────────────────────────────────────────────┬─────────┬─────────┬──────────────┬──────┐
│  #  │                    Operation                    │ Old (s) │ New (s) │   Speedup    │  Δ   │
├─────┼─────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 2   │ base64Encode(toString(number))                  │   0.144 │   0.093 │ 1.54× faster │ −35% │
├─────┼─────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 8   │ tryBase64Decode(base64Encode(toString(number))) │   0.253 │   0.183 │ 1.38× faster │ −28% │
├─────┼─────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 5   │ base64Decode(base64Encode(toString(number)))    │   0.252 │   0.185 │ 1.36× faster │ −27% │
├─────┼─────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 0   │ base64Encode('Hello, world!')                   │   0.134 │   0.102 │ 1.32× faster │ −24% │
├─────┼─────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 3   │ base64Decode(base64Encode('Hello, world!'))     │   0.254 │   0.214 │ 1.19× faster │ −16% │
├─────┼─────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 6   │ tryBase64Decode(base64Encode('Hello, world!'))  │   0.250 │   0.212 │ 1.18× faster │ −15% │
└─────┴─────────────────────────────────────────────────┴─────────┴─────────┴──────────────┴──────┘

amd64

┌─────┬────────────────────────────────────────────────┬─────────┬─────────┬──────────────┬──────┐
│  #  │                   Operation                    │ Old (s) │ New (s) │   Speedup    │  Δ   │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 1   │ base64Encode(<64-char string>)                 │   0.598 │   0.120 │ 4.99× faster │ −80% │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 4   │ base64Decode(base64Encode(<64-char>))          │   0.900 │   0.339 │ 2.66× faster │ −62% │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 7   │ tryBase64Decode(base64Encode(<64-char>))       │   0.892 │   0.344 │ 2.59× faster │ −62% │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 0   │ base64Encode('Hello, world!')                  │   0.162 │   0.082 │ 1.98× faster │ −50% │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 6   │ tryBase64Decode(base64Encode('Hello, world!')) │   0.357 │   0.245 │ 1.46× faster │ −31% │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 3   │ base64Decode(base64Encode('Hello, world!'))    │   0.356 │   0.246 │ 1.44× faster │ −31% │
├─────┼────────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 2   │ base64Encode(toString(number))                 │   0.128 │   0.099 │ 1.30× faster │ −23% │
└─────┴────────────────────────────────────────────────┴─────────┴─────────┴──────────────┴──────┘

┌─────┬─────────────────────────────────────────────┬─────────┬─────────┬──────────────┬──────┐
│  #  │                  Operation                  │ Old (s) │ New (s) │   Speedup    │  Δ   │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 2   │ base64Encode(URL)                           │   0.987 │   0.555 │ 1.78× faster │ −44% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 10  │ tryBase64Decode(base64Encode(URL))          │   1.573 │   0.959 │ 1.64× faster │ −39% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 6   │ base64Decode(base64Encode(URL))             │   1.554 │   0.962 │ 1.62× faster │ −38% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 3   │ base64Encode(Title)                         │   1.015 │   0.659 │ 1.54× faster │ −35% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 7   │ base64Decode(base64Encode(Title))           │   1.571 │   1.077 │ 1.46× faster │ −31% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 0   │ base64Encode(SearchPhrase)                  │   0.251 │   0.185 │ 1.35× faster │ −26% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 1   │ base64Encode(MobilePhoneModel)              │   0.015 │   0.012 │ 1.22× faster │ −18% │
├─────┼─────────────────────────────────────────────┼─────────┼─────────┼──────────────┼──────┤
│ 8   │ tryBase64Decode(base64Encode(SearchPhrase)) │   0.422 │   0.355 │ 1.19× faster │ −16% │
└─────┴─────────────────────────────────────────────┴─────────┴─────────┴──────────────┴──────┘

Version info

  • Merged into: 26.7.1.1021 (included in 26.7 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c2ccb3]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-386d) FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR replaces aklomp-base64 with simdutf for the SQL Base64 functions, Base64WriteBuffer, and terminal PNG output, while preserving the previously-reviewed decode edge cases around hybrid URL alphabets, padded-chunk leniency, and the new documented whitespace handling. I did not find a remaining correctness or compatibility regression in the current PR head.

PR Metadata
  • Changelog category: Performance Improvement is appropriate for the actual change.
  • Changelog entry: required for this category, but the current entry is too implementation-focused (Use simdutf library for base64.) and does not tell users what improves.
  • Suggested replacement: Improves base64Encode, base64Decode, tryBase64Decode, base64URLEncode, and base64URLDecode performance by switching them to the simdutf implementation while preserving previous decoding compatibility.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Jun 23, 2026
Following the migration of the base64 SQL functions to `simdutf`, move the
two remaining users of `libbase64` over as well and remove the
`contrib/base64` submodule entirely.

- `PNGTerminalOutput::writeImageKitty` now calls `simdutf::binary_to_base64`.
- `Base64WriteBuffer` is reimplemented on `simdutf`'s one-shot API. `simdutf`
  has no streaming base64 API, but base64 encodes independent 3-byte groups,
  so the buffer encodes whole groups eagerly and carries the trailing 0-2
  bytes across writes, emitting the padded final group in `finalizeImpl`.
- The standard `base64Decode` variant uses `strict` last-chunk handling to
  reject truncated input such as the 3-character `foo`, matching the previous
  `libbase64` behaviour. The URL variant keeps `loose` handling because
  base64url omits padding, so partial final chunks are valid.

The `USE_BASE64` build flag is replaced by `USE_SIMDUTF`, and
`ch_contrib::simdutf` is linked into `clickhouse_common_io` where
`ch_contrib::base64` used to be. Also tracks `contrib/simdutf-cmake`, which
the previous commit registered but left untracked.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
thevar1able and others added 2 commits June 24, 2026 00:19
The previous `base64URLDecode` implementation translated only '-' and '_'
before delegating to the standard base64 decoder, leaving '+' and '/'
untouched, so inputs such as `base64URLDecode('+w==')` or
`base64URLDecode('/w==')` decoded successfully. `simdutf::base64_url` accepts
only the URL-safe alphabet and would reject those, turning previously accepted
values into `INCORRECT_DATA`.

Decode the URL variant with `simdutf::base64_default_or_url`, the
standard/base64url hybrid alphabet, so both alphabets keep decoding. Encoding
still emits the URL-safe alphabet without padding. Add a regression test
covering both alphabets and their mix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/IO/Base64WriteBuffer.cpp Resolved
thevar1able and others added 2 commits June 24, 2026 00:43
`simdutf` ignores ASCII whitespace (' ', '\t', '\n', '\r', '\f') when decoding
base64, decoding such input to the same value as the whitespace-free input.
The previous `libbase64`-based decoder rejected whitespace with
`INCORRECT_DATA`, but that was an incidental side effect of calling it with
`flags=0` rather than a deliberate policy: no test asserted it and no rationale
was ever recorded. The relaxed behaviour is also RFC 2045 / MIME-compatible.

Measuring a whitespace-rejecting pre-scan showed it adds ~38% to decode time
even when written branchlessly to auto-vectorize, eroding the decode speedup
that motivated the migration, so the relaxation is kept intentionally.

Document the behaviour on `base64Decode` and `base64URLDecode`, and fold the
whitespace and standard-alphabet coverage into the existing
`00732_base64_functions` and `03167_base64_url_functions` tests instead of
keeping separate test files.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `no-fasttest` tag on the base64 tests was justified only by the
`aklomp-base64` library, which has been replaced by `simdutf` (now cloned in
the fast test submodule list). Drop the tag so the tests run in fast test.
Comment thread .gitmodules Resolved
Comment thread src/Functions/base64Decode.cpp Resolved
@clickhouse-gh

This comment was marked as low quality.

thevar1able and others added 3 commits June 24, 2026 18:33
`simdutf::binary_to_base64` and `simdutf::base64_to_binary` are dispatched
through an exported function that performs a sequentially-consistent atomic load
of the active implementation pointer on every call. For base64 functions, which
are invoked once per row, this fixed per-call cost dominates on short strings.

Resolve the active implementation once via `simdutf::get_active_implementation`
(a function-local `static`) and call its virtual methods directly. The pointer
is stable after first use, and `simdutf::implementation` exposes both methods as
public `const` virtuals.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Point the simdutf submodule at the ClickHouse fork, which carries two patches on
top of v9.0.0:
- aarch64 base64 decode/encode fast paths for short inputs (fixes the per-row
  decode regression on aarch64 versus the previous libbase64 codec);
- a guard providing the LoongArch HWCAP bits when the kernel headers in the
  cross-compilation sysroot lack them (fixes the loongarch64 build).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds the icelake masked-load MemorySanitizer unpoison patch to the simdutf
fork, fixing the use-of-uninitialized-value reports in `to_base64_mask` (and the
encoder tail) on the amd_msan build.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread contrib/simdutf-cmake/CMakeLists.txt Resolved
Comment thread src/Functions/base64Decode.cpp Resolved
Comment thread ci/jobs/fast_test.py Resolved
@rschu1ze rschu1ze self-assigned this Jun 24, 2026
@thevar1able
thevar1able marked this pull request as ready for review June 24, 2026 22:03
Comment thread .gitmodules Resolved
All amd_msan CI jobs failed with a use-of-uninitialized-value report in
`to_base64_mask` (contrib/simdutf/src/icelake/icelake_base64.inl.cpp:256,
`_mm512_permutex2var_epi8`). This is a false positive caused by an LLVM 21
MemorySanitizer bug: `maskedCheckAVXIndexShadow` checks the concrete index
value of AVX-512 permutation intrinsics instead of its shadow, so every
icelake base64 decode reports, no matter how the input was initialized.
That is also why the previous unpoisoning workarounds (now reverted in the
fork) could not help: the buggy check never looks at the shadow.

Introduced by llvm/llvm-project#147839, fixed by
llvm/llvm-project#148785 (first released in
LLVM 22, not backported to 21.x).

The fork now compiles out the icelake implementation when building with
MemorySanitizer under Clang 21 or older, and simdutf's runtime dispatcher
falls back to haswell, which uses no affected intrinsics with non-constant
indices. Verified with 2M randomized encode/decode iterations under both
Clang 21 (haswell selected, clean) and Clang 22 (icelake selected, clean);
non-MSan builds still select icelake.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108333&sha=39b5dad4fd3b746d7922ce16e650afb71e61828f&name_0=PR&name_1=Unit%20tests%20%28msan%2C%20function_prop_fuzzer%29
PR: #108333
Two backward-incompatible strictifications crept in with the migration to
simdutf and are reverted here:

- `base64Decode` rejected non-zero leftover bits in a complete, properly
  padded final chunk, e.g. `base64Decode('Zh==')`. The previous
  implementation (aklomp-base64) silently dropped them. `simdutf::strict`
  reports this case as `BASE64_EXTRA_BITS`; retry in loose mode, which
  drops the bits. This cannot accept anything else strict rejects, since
  `BASE64_EXTRA_BITS` is only reported after the completeness and padding
  checks passed.

- `base64URLDecode` rejected an underpadded final chunk, e.g.
  `base64URLDecode('Zg=')`. The previous implementation padded the input
  with '=' to a multiple of four characters before decoding. Append the
  missing '=' and retry; only the "two significant characters plus one
  '='" form can be underpadded. The copy happens only on this rare error
  path (the previous implementation copied every row).

Verified against the simdutf scalar reference implementation that the
retried cases are exactly the ones the previous implementation accepted.
The docs said "ASCII whitespace characters" are ignored, but simdutf only
ignores space, tab, line feed, carriage return, and form feed; vertical
tab (0x0B) is rejected. List the exact characters, and note that the
leniency is new in version 26.7 (earlier versions rejected any whitespace
in the input).
The example row referenced `/contrib/aklomp-base64/LICENSE`, which is
removed by this PR. Use `boost` instead (verified against the
`list-licenses.sh` output, alphabetical order preserved). Updated in all
language mirrors; changelogs are left untouched.
@mintlify

This comment was marked as off-topic.

The `__msan_unpoison(dst, ...)` calls after `simdutf::binary_to_base64` and
`simdutf::base64_to_binary` (and the accompanying comment about AVX-512
shuffles) were carried over verbatim from the previous aklomp-base64
implementation, whose AVX-512 kernels MemorySanitizer indeed could not
model. simdutf's output is fully initialized under MemorySanitizer:
verified with a standalone MSan reproducer running 2M randomized
encode/decode iterations that read back every output byte, with no
unpoisoning anywhere, under both Clang 21 (haswell kernel, the CI MSan
configuration after the fork disabled icelake) and Clang 22 (icelake
kernel).

This also resolves a review question about the asymmetry with the other
`simdutf::binary_to_base64` call sites (`Base64WriteBuffer`,
`PNGTerminalOutput`), which never had unpoisoning and are correct as is.
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 54.50% 85.80% +31.30%
Functions 61.30% 92.70% +31.40%
Branches 43.30% 78.00% +34.70%

Changed lines: Changed C/C++ lines covered: 71/76 (93.42%) · Uncovered code

Full report · Diff report

@thevar1able
thevar1able added this pull request to the merge queue Jul 16, 2026
Merged via the queue into master with commit b9dab5d Jul 16, 2026
175 of 177 checks passed
@thevar1able
thevar1able deleted the simdutf-base64 branch July 16, 2026 12:18
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @thevar1able @rschu1ze — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The body documents the performance gains (benchmark tables) but does not mention the user-visible decode behavior changes: ASCII whitespace is now ignored on decode (previously rejected), and the URL variant's padding/alphabet leniency is now handled by simdutf with explicit compatibility retry paths. Reviewers assessing backward compatibility need this called out.

  • Suggested addition:

    Note on behavior: base64 decoding now ignores ASCII whitespace (space, tab, \n, \r, \f) in the input, which earlier versions rejected (vertical tab and other non-alphabet characters are still rejected). The URL decode variant continues to accept both the standard (+ and /) and URL-safe (- and _) alphabets and tolerates underpadded final chunks, matching the previous aklomp-based implementation via explicit retry paths.

Ignore this if the current title/body is intentional.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
All amd_msan CI jobs failed with a use-of-uninitialized-value report in
`to_base64_mask` (contrib/simdutf/src/icelake/icelake_base64.inl.cpp:256,
`_mm512_permutex2var_epi8`). This is a false positive caused by an LLVM 21
MemorySanitizer bug: `maskedCheckAVXIndexShadow` checks the concrete index
value of AVX-512 permutation intrinsics instead of its shadow, so every
icelake base64 decode reports, no matter how the input was initialized.
That is also why the previous unpoisoning workarounds (now reverted in the
fork) could not help: the buggy check never looks at the shadow.

Introduced by llvm/llvm-project#147839, fixed by
llvm/llvm-project#148785 (first released in
LLVM 22, not backported to 21.x).

The fork now compiles out the icelake implementation when building with
MemorySanitizer under Clang 21 or older, and simdutf's runtime dispatcher
falls back to haswell, which uses no affected intrinsics with non-constant
indices. Verified with 2M randomized encode/decode iterations under both
Clang 21 (haswell selected, clean) and Clang 22 (icelake selected, clean);
non-MSan builds still select icelake.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108333&sha=39b5dad4fd3b746d7922ce16e650afb71e61828f&name_0=PR&name_1=Unit%20tests%20%28msan%2C%20function_prop_fuzzer%29
PR: ClickHouse#108333
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 7c2ccb3b Deployed Jul 16, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants