Skip to content

Reduce per-row overhead of encrypt and decrypt - #124103

Merged
thevar1able merged 3 commits into
ClickHouse:masterfrom
groeneai:aes-argument-reader-once-per-block
Oct 7, 2026
Merged

thevar1able merged 3 commits into
ClickHouse:masterfrom
groeneai:aes-argument-reader-once-per-block

Conversation

@groeneai

@groeneai groeneai commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #81944

Changelog category (leave one):

  • Performance Improvement

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

encrypt and aes_encrypt_mysql are faster on values shorter than 16 bytes in the aes-*-ecb and aes-*-cbc modes (up to 2x for encrypt with aes-128-ecb).

Description

Performance Comparison (amd_release) keeps reporting encrypt_decrypt #0/#1/#2/#4/#5/#13 as slower in unrelated PRs and on master (#81944 run). The code of encrypt and of the OpenSSL functions it calls is byte-identical in the slow build and in fast builds on the same base; in the slow build the extra time is in the per-row loop of encrypt, which for every row makes 3-5 virtual getDataAt calls and, for a value shorter than one AES block, one EVP_EncryptUpdate (three levels of OpenSSL provider dispatch) for a single 16-byte block.

Two commits:

  1. Argument columns are resolved once per block: String and FixedString are read through their final classes, a constant once, anything else keeps the virtual call. All four encrypt/decrypt loops.
  2. In the ECB-composed path of aes-*-ecb/aes-*-cbc encryption, a row shorter than 16 bytes is one block with no chaining, so the block is built in place in the output and a run of such rows is encrypted with one in-place EVP_EncryptUpdate. Longer rows and decryption are not batched.

tests/performance/encrypt_decrypt.xml, release build, one thread, new time divided by old time, measured on two CPUs: #0 0.51 and 0.49, #1 0.67 and 0.65, #4 0.68 and 0.67, #5 0.82 and 0.82, #10 0.72 and 0.71, #13 0.86 and 0.85, #2 0.94 and 0.93; the other queries of the test, and encryption of values of 16 bytes or more, are at most 2% slower. Outside the test, aes_encrypt_mysql('aes-128-cbc', ...) on short values: 0.84 and 0.85. This makes the loop cheaper; I have not shown that it stops the placement-dependent flips.

New test 05331_encrypt_decrypt_argument_columns: FixedString, constant and String argument mixes for every mode, and hashes of many-row blocks mixing short and long values, key changes and per-row IVs, produced by the previous implementation.


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

Version info

  • Merged into: 26.10.1.1752-master (included in 26.10 and later)

groeneai and others added 3 commits October 5, 2026 19:29
Every row of the encrypt/decrypt loops called the virtual IColumn::getDataAt
for the input, key, IV and AAD columns (plus once more in the output-size
pre-pass), and for a constant argument ColumnConst::getDataAt forwards to a
second virtual call into the nested column. The column kinds are fixed for
the whole block, so resolve them once: String and FixedString are read
through their final classes, a constant is read once, and anything else
keeps the virtual call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In the ECB-composed path of encrypt and aes_encrypt_mysql for aes-*-ecb and
aes-*-cbc, every row shorter than one AES block made its own EVP_EncryptUpdate
call for a single 16-byte block, and that call chain (EVP_EncryptUpdate ->
ossl_cipher_generic_block_update -> cipher_hw_aesni_ecb -> aesni_ecb_encrypt)
costs more than the AES rounds themselves. Such a row has no chaining inside
it: its ciphertext is ECB(pad(P)) for ECB and ECB(pad(P) XOR IV) for CBC. So
build that block in place in the output and encrypt a run of them with one
in-place EVP_EncryptUpdate, flushed before the key changes, before any longer
row, every 4096 bytes and after the last row. In-place ECB on the same buffer
is allowed by EVP and the AES-NI ECB kernel.

tests/performance/encrypt_decrypt.xml queries, one thread, 3M rows, release
build, fix/base on two CPUs: ECB encrypt 0.51/0.49, CBC encrypt 0.67/0.65,
ECB encrypt+decrypt 0.68/0.67, CBC encrypt+decrypt 0.82/0.82, alternating
keys 0.72/0.71, per-row IV 0.86/0.85. Rows of 16 bytes and longer keep the
previous code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Wrap literal names in the new FunctionsAES.h comments in inline code and drop a sentence that narrated the deferred-row path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

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

Pre-publication review by an independent model (engine: codex; 3 findings over 2 runs on the same head).

# Sev Finding Verdict Evidence / action
1 ⚠️ The timings read as new 0.51 vs old 0.49; the aes_encrypt_mysql speedup had no measured row AGREE, fixed in the description Timings say "new time divided by old time"; measured aes_encrypt_mysql('aes-128-cbc') row added (0.84 and 0.85)
2 ⚠️ 05331 cannot catch a reverted optimization; add a counter such as a ProfileEvent DISAGREE tests/performance/encrypt_decrypt.xml runs exactly the batched path in Performance Comparison (reverting is about 2x on query #0); a counter would be test-only code in a hot path; 05331 catches each of 7 mutations of the new branches
3 💡 New comments do not put literal names in inline code AGREE, fixed Comment-only commit

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

Session id: cron:clickhouse-review-slot-11:20261005-212500

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [60474c4]

Summary: ✅


AI Review

Summary

This PR reduces per-row overhead in encrypt and decrypt by caching string-argument access and batching single-block ECB/CBC encryption for short rows. I reviewed the current src/Functions/FunctionsAES.h implementation against the PR diff, the added stateless coverage in tests/queries/0_stateless/05331_encrypt_decrypt_argument_columns.sql, the PR description, prior discussion, and the available CI status; I did not find an unresolved correctness, compatibility, or test-coverage issue in the current revision.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 60474c4.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 142/146 (97.26%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 5, 2026
@thevar1able thevar1able self-assigned this Oct 5, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes the AES encrypt/decrypt functions: it reads String and FixedString arguments without a virtual call per row, and it batches rows shorter than one block into a single ECB call. It also adds a stateless test. Neither clickbench nor tpch_adapted_1_official calls these functions, so no benchmark query runs the changed code. The only flagged result, clickbench Q34 at -5.4% (1256 to 1188 ms), was compared against a thin 5-run baseline and stays inside master's current range of 1093-1370 ms, so it is downgraded to not_sure. To measure the PR's real effect you would need a micro-benchmark that calls encrypt or decrypt on short strings.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1256 1188 -5.4% <0.0001 aggregation: ClickBench Q34 is a GROUP BY over hits that never calls encrypt or decrypt, so this PR's AES-only change cannot affect it. The -5.4% sits inside master's current range of 1093-1370 ms, measured against a thin 5-run baseline.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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

🟢 No significant changes

Debug info
  • StressHouse run: 8ee370f8-60e3-47fc-a3c7-20435217419b
  • MIRAI run: 0d7edbb5-1b71-4d0f-a6a2-c1908188aed1
  • PR check IDs:
    • clickbench_3442958_1791243944
    • clickbench_3442972_1791243944
    • clickbench_3442978_1791243945
    • tpch_adapted_1_official_3443000_1791243944
    • tpch_adapted_1_official_3443006_1791243944
    • tpch_adapted_1_official_3443028_1791243945

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 60474c448 with master 289363a9f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 407e25ae0; 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.

Object file sizes

7 object files changed (+84.71 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/encrypt.cpp.o 275.27 KiB 297.27 KiB +22.00 KiB (+7.99%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/decrypt.cpp.o 288.15 KiB 306.09 KiB +17.93 KiB (+6.22%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/tryDecrypt.cpp.o 288.99 KiB 306.58 KiB +17.59 KiB (+6.09%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

12 translation units recompiled, 22 s compile time in total, 12 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 60474c4

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / S3_ERROR No such key thrown not caused by this PR: a re-CREATE in 05137_table_disk_drop_deduplication_log (s3_plain_rewritable table_disk) reads a deleted __root/format_version.txt a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20261006-040251

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_release) S3_ERROR No such key (05137, format_version.txt): #124298.

@thevar1able
thevar1able added this pull request to the merge queue Oct 7, 2026
Merged via the queue into ClickHouse:master with commit 5d34976 Oct 7, 2026
294 of 296 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 17, 2026
A table with `table_disk = true` keeps its parts and its root files
(`format_version.txt`, `detached/`, `deduplication_logs/`, mutation entries) at
the root of its disk, so two writable tables on one root overwrite and delete
each other's data (issue ClickHouse#98512), and the stress test's AST fuzzer clones of
such a table (`<name>__fuzz_N`, same disk) raced the original's `DROP` and left
a metadata entry whose object was gone (`S3_ERROR` No such key on
`__root/format_version.txt` in `Stress test (arm_release)`).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124103&sha=60474c44812b8fadcb983207ab8e87a4a1af41f5&name_0=PR&name_1=Stress%20test%20%28arm_release%29
PR: ClickHouse#124103

A writable `table_disk` table now owns the root of its disk (storage endpoint +
namespace + disk path; nested paths conflict) until the instance is destroyed;
another writable table on that root is refused with `BAD_ARGUMENTS`. Read-only
and write-once disks are not owners, so the one-writer/many-readers setup keeps
working.

The root is not released when `dropAllData` finishes: the rest of the drop
(`dropReplica`, removing `store/<uuid>` and the metadata) can still throw and
re-queue the table, and after a restart the dropped table is rebuilt from
`metadata_dropped` before the other tables are loaded, so a released root could
be taken by another table whose parts the retried drop would then delete.
`DatabaseCatalog` destroys the dropped storage before it notifies the
`DROP ... SYNC` waiters, so `DROP ... SYNC` followed by a `CREATE` on the same
disk works; the new `database_catalog_drop_finally_after_notify` failpoint
pauses the drop job right after that notification, so a test can check it. A
table dropped or detached without `SYNC` keeps the root until its instance is
gone, and the error says to retry after that (`SYNC` waits for it).

An `ALTER` cannot change the disk or the storage policy of a `table_disk`
table: the new disks would join the table without being owned, and
`RESET SETTING disk` moved the table onto the `default` disk with the server's
data directory as its data path, so a later `DROP TABLE` deleted that whole
directory.

The default database of `clickhouse-local` is a writable `Overlay` over an
`Atomic` database, which keeps a detached table instance until no query uses
it. `Overlay` did not forward `checkDetachedTableNotInUse` and
`waitDetachedTableNotInUse`, so an `ATTACH` did not first destroy the unused
detached instance and `DETACH ... SYNC` did not wait; with the ownership above
that refused `DETACH TABLE t; ATTACH TABLE t`. Both are now forwarded to every
member, as the server's `Atomic` database does.

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... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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