Repository navigation
Reuse AES key schedules and compose plain ECB/CBC on a streaming ECB context in encrypt/decrypt - #107339
Conversation
|
Workflow [PR], commit [889b9f0] Summary: ❌
AI ReviewSummaryThis PR reuses AES key schedules between rows and adds a block-composed fast path for plain AES ECB/CBC in Final VerdictStatus: ✅ Approve |
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. |
|
📊 Cloud Performance Report 🟢 AI verdict: 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 · Flagged queries (3 of 43)
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)
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
|
LLVM Coverage Report
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 |
| auto * encrypted = encrypted_result_column_data.data(); | ||
|
|
||
| KeyHolder<mode> key_holder{}; | ||
| [[maybe_unused]] CachedKeyState ctx_key_state; |
There was a problem hiding this comment.
I think we can remove [[maybe_unused]].
Antalya 26.3 Backport of ClickHouse#107339 - Reuse AES key schedules and compose plain ECB/CBC on a streaming ECB context in encrypt/decrypt
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.
Closes: #65116
Related: #99105
After #99105 removed the implicit per-row cipher re-fetch, the dominant remaining cost of
encrypt/decryptin OpenSSL 3.x isEVP_EncryptInit_ex/EVP_DecryptInit_exitself: 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_excan 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 exactlyECB(block XOR previous_ciphertext_block)plus PKCS#7 padding — both of which EVP only exposes through per-rowInit/Finalcalls. The fast path instead keeps a single streaming ECB context with padding disabled, initialized once per distinct key, and composes the mode manually:EVP_DecryptUpdateregardless of length, followed by the chaining XOR. PKCS#7 padding is validated in constant time over the whole last block, mirroringEVP_DecryptFinal_ex(all padding bytes checked, no data-dependent branches, so no timing padding-oracle).EVP_EncryptUpdateper 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_modesis 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),tryDecryptNULL semantics, and recovery after failed rows. A differential matrix against an unpatched binary is byte-identical, and all existingencrypt/decryptstateless tests pass. Decryption failures keep theOPENSSL_ERRORcode; the messages become more specific (Cannot decrypt: invalid PKCS#7 paddinginstead ofEVP_DecryptFinal_ex failed: ... bad decrypt).Performance (Release build, single thread, 10M rows of
toString(number), constant key, median of 3):encryptaes-128-cbcencryptaes-128-ecbencryptaes-128-ctr (commit 1 only)aes_encrypt_mysqlaes-128-cbcdecrypt(encrypt(...))aes-128-cbctryDecrypt, mixed valid/corruptedencryptaes-128-gcmencryptaes-128-cbc, key varies per rowencryptaes-128-cbc, 1000-byte rowsThe 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):
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, andaes_decrypt_mysqlfunctions by up to an order of magnitude, recovering the performance lost in the BoringSSL to OpenSSL 3.x migration (24.4).