Skip to content

Avoid per-row OpenSSL re-fetch in encrypt, decrypt and halfMD5 - #99105

Merged
alexey-milovidov merged 14 commits into
masterfrom
fix-encrypt-decrypt-performance
Jun 12, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
fix-encrypt-decrypt-performance

Conversation

@thevar1able

@thevar1able thevar1able commented Mar 9, 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):

Improve performance of the encrypt, decrypt, and halfMD5 functions by avoiding implicit per-row OpenSSL provider lookups in OpenSSL 3.x.

Version info

  • Merged into: 26.6.1.692

In OpenSSL 3.x, passing a legacy cipher (obtained via `EVP_get_cipherbyname`,
which has `prov == NULL`) to `EVP_EncryptInit_ex` / `EVP_DecryptInit_ex` causes
an implicit `EVP_CIPHER_fetch` call on every invocation, involving locking and
provider lookups. Since the encrypt/decrypt functions call `EVP_*Init_ex` once
per row, this creates significant overhead.

Fix: call `EVP_CIPHER_fetch` once per block via a new `fetchCipher` function
and pass the provider-backed cipher to the per-row loop, avoiding the implicit
fetch.

Also add a performance test for encrypt/decrypt with non-empty plaintext
covering CBC, CTR, and GCM modes, complementing the existing empty-string test.

Benchmarks (10M rows, single-threaded, CBC): 3.78s -> 2.03s (1.86x speedup).

Closes #65116

Assisted-by: Claude Opus 4.6 via GitHub Copilot
@clickhouse-gh

clickhouse-gh Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4f06b98]

Summary: ✅


AI Review

Summary

This PR avoids repeated OpenSSL provider lookups by fetching AES ciphers once per block for encrypt / decrypt and by reusing an initialized MD5 digest template for halfMD5. I did not find any current correctness, safety, or performance-review findings. The earlier bot findings are addressed in the current code: the constant-key context reuse was removed, EVP_MD_CTX_new failure is checked for the thread-local context, stale OpenSSL fetch errors are cleared for invalid modes, and the changelog entry now covers halfMD5.

Missing context / blind spots
  • ⚠️ The latest full CI run was still in progress at review time; completed Praktika / Style checks showed no failures. A fully green CI run would close this operational blind spot.
Final Verdict

Status: ✅ Approve

Minimum required actions: none from code review.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 9, 2026
Comment thread tests/performance/encrypt_decrypt.xml Outdated
</substitutions>

<!-- allow OpenSSL-related code load ciphers and warm-up -->
<fill_query>WITH {plaintext} as plaintext, repeat('k', 32) as key32, substring(key32, 1, 24) as key24, substring(key32, 1, 16) as key16, repeat('iv', 8) as iv16, substring(iv16, 1, 12) as iv12 SELECT count() FROM {table} WHERE NOT ignore({func}) LIMIT 1</fill_query>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Does encrypt/decrypt functions have explicit specialization for case, where key/iv is constant or not?
Because, it seems this optimization mostly about case like that.

thevar1able and others added 3 commits March 10, 2026 15:06
When key and IV columns are constant (the common case for non-GCM modes),
initialize the EVP_CIPHER_CTX once before the per-row loop with the full
cipher+key+IV, then on each iteration only reset the IV via
`EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv)`. This skips repeated
cipher lookup, setup and key schedule expansion in OpenSSL.

Applied symmetrically to both `doEncryptImpl` and `doDecryptImpl`.
GCM mode is left unchanged — it requires custom IV length and AAD setup
per row anyway.

Combined with the `fetchCipher` fix from the previous commit,
encrypt+decrypt CBC on 10M rows goes from ~3.78s to ~0.79s (4.8x speedup).

Assisted-by: Claude Opus 4.6 via GitHub Copilot
Restructure the performance test to cover both constant key+IV (the optimized
path) and variable key/IV (full init per row) scenarios. This ensures CI
catches regressions in both code paths.

Test cases:
- Constant key+IV: encrypt CBC, CTR, GCM; decrypt CBC, GCM
- Variable key, constant IV: encrypt CBC
- Constant key, variable IV: encrypt CBC

Also removed aes-256 variants to keep the test focused and fast, since
key size does not affect the init overhead being measured.

Assisted-by: Claude Opus 4.6 via GitHub Copilot
@filimonov

filimonov commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

Similar Altinity#1214 (AI written, shows expected performance boost, was not human-reviewed)

Comment thread src/Functions/FunctionsAES.h Resolved
Comment thread src/Functions/FunctionsAES.h Resolved
Comment thread src/Functions/FunctionsAES.h Resolved
@clickhouse-gh

This comment was marked as outdated.

thevar1able and others added 2 commits June 10, 2026 18:36
…pher-perf

# Conflicts:
#	src/Functions/FunctionsAES.h
`HalfMD5Impl::apply` created a fresh `EVP_MD_CTX` and called
`EVP_DigestInit_ex(ctx, EVP_md5(), nullptr)` once per row. In OpenSSL 3.x a
digest obtained via `EVP_md5` has `prov == NULL`, so passing it to
`EVP_DigestInit_ex` makes OpenSSL re-fetch the implementation from the provider
method store on every call. That lookup takes a read lock, and since the
function runs once per row all hashing threads serialize on it: with musl's
`pthread_rwlock` on aarch64 this doubled `cryptographic_hashes` times in CI,
with `__pthread_rwlock_tryrdlock` dominating the profile.

Initialize a context with the digest once and copy it per call with
`EVP_MD_CTX_copy_ex`, the same approach already used in
`FunctionsStringHashFixedString.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Functions/FunctionsAES.h Resolved
thevar1able and others added 4 commits June 10, 2026 20:23
The constant-key optimization initializes the cipher context once before the
row loop and then re-initializes only the IV per row via
`EVP_EncryptInit_ex(ctx, nullptr, nullptr, nullptr, iv)` (and the `EVP_Decrypt`
counterpart). When the IV argument is absent or an empty string, `iv_value.data()`
is null, so the re-init passes a null IV. OpenSSL keeps the previously used
working IV in that case instead of restoring the initial all-zero IV that the
per-row full initialization produces, so for stateful modes (CBC/CTR/CFB/OFB)
every row after the first is computed from the previous row's advanced IV and
produces wrong ciphertext/plaintext.

Pass an explicit zero IV when the IV is absent or empty so the reused context
starts each row from the same state as full per-row initialization. Verified
against the bundled OpenSSL 3.5.6: the all-null re-init leaks the advanced IV
while an explicit zero IV reproduces the original result.

Add a stateless regression test comparing the constant-key fast path against the
per-row path (forced by materializing the key). A plain encrypt/decrypt
round-trip does not catch this because encrypt and decrypt share the same defect.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@thevar1able
thevar1able marked this pull request as ready for review June 10, 2026 18:38
Comment thread src/Functions/FunctionsHashing.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f6215ece-030f-44c3-9bd1-d0a4958658d5
  • MIRAI run: 86bde960-c813-422d-b21f-43c6b13a429a
  • PR check IDs:
    • clickbench_279738_1781195460
    • clickbench_279888_1781195493
    • clickbench_279998_1781195533
    • tpch_adapted_1_official_280084_1781195561
    • tpch_adapted_1_official_280104_1781195562
    • tpch_adapted_1_official_280265_1781195598

Comment thread src/Functions/FunctionsAES.cpp Resolved
Comment thread src/Functions/FunctionsHashing.h Resolved
@thevar1able thevar1able changed the title Fix encrypt/decrypt performance regression with OpenSSL 3.x Avoid per-row OpenSSL re-fetch in encrypt, decrypt and halfMD5 Jun 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.20% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 46/58 (79.31%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Jun 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 12, 2026
Merged via the queue into master with commit 9eab6c1 Jun 12, 2026
327 of 328 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-encrypt-decrypt-performance branch June 12, 2026 02:21
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 12, 2026
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants