Skip to content

Reuse AES key schedules and compose plain ECB/CBC on a streaming ECB context in encrypt/decrypt - #107339

Merged
thevar1able merged 8 commits into
masterfrom
aes-block-cipher-fast-path
Jun 16, 2026
Merged

thevar1able merged 8 commits into
masterfrom
aes-block-cipher-fast-path

Conversation

@thevar1able

@thevar1able thevar1able commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #65116
Related: #99105

After #99105 removed the implicit per-row cipher re-fetch, the dominant remaining cost of encrypt/decrypt in OpenSSL 3.x is EVP_EncryptInit_ex / EVP_DecryptInit_ex itself: provider dispatch plus AES key schedule expansion cost ~140 ns per row, an order of magnitude more than encrypting a typical short value (~14 ns), and the per-row provider traffic also contends between threads. This PR removes that per-row cost in two independent commits.

Commit 1 — generic key schedule reuse (all modes). The per-row loop remembers the key bytes the cipher context was last initialized with. When a row repeats the same key, the context is re-initialized with only the IV (null cipher and key), keeping the expanded key schedule. This compares key values per row, so it works for any key column, not only constants, and the code path stays the same for all rows. An absent IV is passed as an explicit zero IV, because an IV-only re-initialization with a null IV pointer would keep the previous row's advanced IV state instead of the zero IV that a fresh initialization produces. A failed decryption forces a full re-initialization on the next row, since a failed EVP_DecryptUpdate / EVP_DecryptFinal_ex can leave buffered input in the context.

Commit 2 — block-composed fast path for plain AES ECB/CBC (aes-{128,192,256}-{ecb,cbc}). ECB is the raw AES block transform, and CBC is exactly ECB(block XOR previous_ciphertext_block) plus PKCS#7 padding — both of which EVP only exposes through per-row Init/Final calls. The fast path instead keeps a single streaming ECB context with padding disabled, initialized once per distinct key, and composes the mode manually:

  • Decryption has no sequential dependency between blocks, so each row is decrypted with a single EVP_DecryptUpdate regardless of length, followed by the chaining XOR. PKCS#7 padding is validated in constant time over the whole last block, mirroring EVP_DecryptFinal_ex (all padding bytes checked, no data-dependent branches, so no timing padding-oracle).
  • Encryption is sequential per row for CBC. Short rows do one EVP_EncryptUpdate per block with the chaining XOR applied manually; rows of 64 bytes or more go through a CBC context re-initialized with only the IV between rows, because past the measured crossover (64–96 bytes) OpenSSL's stitched AES-NI CBC implementation wins over per-block calls.

The fast path is gated on exact mode names, so ciphers that merely report EVP_CIPH_CBC_MODE (e.g. aes-128-cbc-hmac-sha1) cannot take it. AES itself, the key schedule, and the block transform all remain inside OpenSSL — only the mode composition (a chaining XOR and the padding bytes) moves out, and it is pinned by tests.

Correctness. The new stateless test 04337_encrypt_decrypt_block_modes is a known-answer test whose reference output was generated with the previous generic implementation, covering ECB/CBC across key sizes, constant/varying/alternating keys and IVs, absent and empty IVs, input lengths crossing block boundaries and the 64-byte threshold, MySQL key/IV folding, full PKCS#7 validation (truncated, extended, corrupted, wrong-key ciphertexts), tryDecrypt NULL semantics, and recovery after failed rows. A differential matrix against an unpatched binary is byte-identical, and all existing encrypt/decrypt stateless tests pass. Decryption failures keep the OPENSSL_ERROR code; the messages become more specific (Cannot decrypt: invalid PKCS#7 padding instead of EVP_DecryptFinal_ex failed: ... bad decrypt).

Performance (Release build, single thread, 10M rows of toString(number), constant key, median of 3):

workload master this PR speedup
encrypt aes-128-cbc 1.27 s 0.22 s 5.7x
encrypt aes-128-ecb 1.00 s 0.20 s 5.0x
encrypt aes-128-ctr (commit 1 only) 1.22 s 0.29 s 4.2x
aes_encrypt_mysql aes-128-cbc 1.36 s 0.31 s 4.3x
decrypt(encrypt(...)) aes-128-cbc 2.55 s 0.85 s 3.0x
tryDecrypt, mixed valid/corrupted 0.87 s 0.12 s 7.1x
encrypt aes-128-gcm 0.52 s 0.51 s —
encrypt aes-128-cbc, key varies per row 0.40 s 0.40 s —
encrypt aes-128-cbc, 1000-byte rows 0.21 s 0.18 s 1.2x

The reproducer from the issue (100M rows, all threads) goes from 14.6 s to 0.50 s (29x); single-threaded it matches the BoringSSL-era 24.3 numbers reported there. The remaining gap to BoringSSL on a per-call basis is the fixed cost of the EVP provider layer, which cannot be removed without leaving the EVP API.

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, tryDecrypt, aes_encrypt_mysql, and aes_decrypt_mysql functions by up to an order of magnitude, recovering the performance lost in the BoringSSL to OpenSSL 3.x migration (24.4).

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [889b9f0]

Summary: ❌

job_name test_name status info comment
Unit tests (amd_llvm_coverage) FAIL
-FunctionsStress FAIL cidb, issue ISSUE EXISTS
Stress test (amd_debug) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue ISSUE CREATED
LLVM Coverage DROPPED IGNORED

AI Review

Summary

This PR reuses AES key schedules between rows and adds a block-composed fast path for plain AES ECB/CBC in encrypt, decrypt, tryDecrypt, aes_encrypt_mysql, and aes_decrypt_mysql. I found no unresolved correctness, safety, or evidence issues in the current code; the earlier concern about missing generic CTR/OFB alternating-key coverage is addressed by the latest stateless test additions.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 12, 2026
@UnamedRus

Copy link
Copy Markdown
Contributor

The remaining gap to BoringSSL on a per-call basis is the fixed cost of the EVP provider layer, which cannot be removed without leaving the EVP API.

Can we have/make tests with non constant key/iv (and compare them to old 24.3 version), not for sake keeping issue open, but just to understand how wide gap will be for that case between boring and openssl 3.

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 38 analysed

This PR only changes the AES encrypt/decrypt functions, adding a key-schedule cache and a block-mode fast path for OpenSSL 3.x. None of the flagged ClickBench or TPC-H queries call encrypt/decrypt, so the change cannot plausibly explain these improvements. ClickBench Q4 and Q22 showed borderline or very noisy deltas and were downgraded to variance. Q23, TPC-H Q7, and TPC-H Q20 show large, consistent drops that the trust gate keeps, but since they run no encryption code these likely reflect measurement or baseline differences rather than an effect of this change.

clickbench

🟢 1 improved · ⚠️ 2 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 23 improvement 297 199 -33.0% <0.0001 -33% is large and consistent, so the trust gate holds it; note this query runs no encryption code.
⚠️ 4 not_sure 264 234 -11.4% <0.0001 aggregation: ClickBench Q4 is a plain aggregation; AES-only diff cannot touch it. -11% is run-to-run variance.
⚠️ 22 not_sure 334 252 -24.7% <0.0001 Measurements very noisy and the AES-only diff doesn't exercise this query; delta is variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 7 improvement 113 72 -36.3% <0.0001 join_operator: -36% large and consistent; trust gate holds it. Join/agg query, no AES path; history is noisy.
🟢 20 improvement 248 124 -50.0% <0.0001 join_operator: -50% large and consistent; trust gate holds it. No AES code in this join query; history is noisy.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 7e8b1645-985d-424c-ad54-2a4c58356919
  • MIRAI run: 33af26ad-2a01-4a51-abed-d6e66c32dfcf
  • PR check IDs:
    • clickbench_187193_1781544639
    • clickbench_187208_1781544640
    • clickbench_187209_1781544638
    • tpch_adapted_1_official_187218_1781544638
    • tpch_adapted_1_official_187228_1781544638
    • tpch_adapted_1_official_187234_1781544638

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

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 243/270 (90.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 2 line(s) · Uncovered code

Full report · Diff report

@rschu1ze rschu1ze 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.

Nice work.

Comment thread src/Functions/FunctionsAES.h Outdated
auto * encrypted = encrypted_result_column_data.data();

KeyHolder<mode> key_holder{};
[[maybe_unused]] CachedKeyState ctx_key_state;

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 think we can remove [[maybe_unused]].

@thevar1able
thevar1able marked this pull request as ready for review June 15, 2026 11:16
@thevar1able
thevar1able added this pull request to the merge queue Jun 16, 2026
Merged via the queue into master with commit 2e9b8e6 Jun 16, 2026
163 of 166 checks passed
@thevar1able
thevar1able deleted the aes-block-cipher-fast-path branch June 16, 2026 13:50
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 16, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Jul 2, 2026
1 task done
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Oct 23, 2026
Antalya 26.3 Backport of ClickHouse#107339 - Reuse AES key schedules and compose plain ECB/CBC on a streaming ECB context in encrypt/decrypt
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Nov 16, 2026
encrypt and decrypt in GCM mode set up the cipher context from scratch on
every row. Passing the cipher to EVP_EncryptInit_ex makes OpenSSL 3 reset
the context: it frees and re-creates the provider context and updates the
reference count of the EVP_CIPHER that all threads share. With 16 threads
that atomic update took over 40% of the time, and GCM ran about 25x slower
than the other modes. ClickHouse#107339 fixed this for the other modes but left the
GCM branch as it was.

Pass the cipher only on the first row or after a failed decryption, and
the key only when it changes, as the other modes already do. A GCM round
trip over 100M rows with 16 threads goes from 23.7 s to 0.9 s, and from
3.9 s to 1.1 s on one thread. The output is byte-identical.
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.

encrypt/decrypt functions became 20x times slower after 24.4

5 participants