Skip to content

Do not build a string for every range when index analysis looks up the cached result of a key function - #127495

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:key-condition-apply-function-cache-key-on-stack
Oct 23, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:key-condition-apply-function-cache-key-on-stack

Conversation

@groeneai

@groeneai groeneai commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #127480

Changelog category (leave one):

  • Performance Improvement

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

Faster primary and partition key analysis for conditions on a monotonic function of a key column, for example toDate(t) on a table ordered by t: the analysis no longer formats a string for every range it checks. The index analysis of the long_primary_key performance test is about two times faster on x86.

Description

In tests/performance/long_primary_key.xml the alias toDate(dt) AS dt puts toDate on the key in WHERE, so for each range the analysis checks, applyMonotonicFunctionsChainToRange calls applyFunction for both bounds of both toDate atoms, about a million calls per query. applyFunction caches the function result over the index column under the name _0x<function pointer>_<column index>, but it built that name on every call with a WriteBufferFromOwnString, writePointerHex and "_" + toString(...), i.e. several heap allocations per call.

Now the name is formatted into a stack buffer (the same text) and looked up as a std::string_view. A String is created only when a cache entry is added.

Validation (x86, RelWithDebInfo, clickhouse local, the test's tables with one part each, 16 interleaved launches, 3 runs per query each): median FilteringMarksWithPrimaryKeyMicroseconds 227 -> 116 ms, 225 -> 114 ms and 227 -> 114 ms for queries 0, 1 and 2 (-49%), query time 0.256 -> 0.143 s. In perf, applyFunction goes from 56% to 22% of the index analysis, and no allocation remains under it. EXPLAIN indexes = 1 output and query results are unchanged; the key condition, monotonicity and index analysis stateless tests pass.

This PR does not claim to fix the instability of long_primary_key on arm reported in #127480; I will check it on the arm builds after merge.


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

Version info

  • Merged into: 26.11.1.677-master (included in 26.11 and later)

groeneai and others added 2 commits October 22, 2026 22:22
`applyFunction` caches the result of a monotonic key function over the
index column in `field.columns` under the name
`_0x<function pointer>_<column index>`. It built that name on every call
with a `WriteBufferFromOwnString`, `writePointerHex` and
`"_" + toString(column_idx)`, and it is called for both bounds of every
range the analysis checks: about a million calls per query in the
`long_primary_key` performance test, where `toDate(dt) AS dt` puts
`toDate` on the key in `WHERE`.

Format the name into a stack buffer (byte-identical text: `_0x`, 16
lowercase hex digits, `_`, the decimal index) and look it up as a
`std::string_view`; make a `String` only when an entry is added.

x86 RelWithDebInfo, `clickhouse local`, the test's tables with one part
each, 16 interleaved launches: `FilteringMarksWithPrimaryKeyMicroseconds`
median 227 -> 116 ms (#0), 225 -> 114 ms (ClickHouse#1), 227 -> 114 ms (ClickHouse#2).

Related: ClickHouse#127480

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove the comment narrating why the cache key is built on the stack; the commit message of the change carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

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

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 static_cast<UInt64>(field.column_idx) before itoa is redundant (base/base/itoa.h has a size_t overload on every target) AGREE, noted behavior-neutral, not changed in this PR

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261022-222500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The long_primary_key tables (one part each) in clickhouse local, 16 interleaved base/fix launches x 3 runs per query: base FilteringMarksWithPrimaryKeyMicroseconds 222-364 ms, fix 111-275 ms, every paired fix/base ratio <= 0.54.
b Root cause explained? applyFunction built its cache key _0x<function pointer>_<column index> with a WriteBufferFromOwnString, writePointerHex and toString for each bound of every checked range, about 1M calls per query; it was 56% of the index analysis in perf, mostly the key.
c Fix matches root cause? Yes. The key is formatted into a stack buffer and looked up as a std::string_view; a String is made only when an entry is added.
d Test intent preserved / new tests added? No new test: no behavior change, and tests/performance/long_primary_key.xml benchmarks this loop. Key condition, monotonicity and index analysis stateless tests (264) pass with the same statuses as the base binary.
e Both directions demonstrated? Yes. PK analysis median 227/225/227 ms -> 116/114/114 ms for queries 0/1/2 (-49%); the allocation frames under applyFunction disappear only with the fix; EXPLAIN indexes = 1 and results identical.
f Fix is general across code paths? applyFunction has two callers (both bounds in applyMonotonicFunctionsChainToRange), which also serves MergeTreeSetIndex::checkInRange; no other per-call key builder in index analysis.
g Fix generalizes across inputs (params/datatypes/wrappers)? The key text is byte-identical (fixed-width 16 hex digits, decimal column index, 40-byte buffer); checked with a temporary abort-on-mismatch comparison over ~3M lookups and the 264 tests. Explicit fields, LowCardinality normalization and the failure sentinel are untouched.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format, protocol or on-disk change; the cache lives for one analysis.
i Invariants and contracts preserved? One cache entry per (function, column), first-match lookup and sentinel publication order unchanged; the view into the local buffer never escapes, the cache stores a copied String.

Session id: cron:clickhouse-impl-slot-6:20261022-213300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @CurtizJ, could you review this and add the can be tested label so CI runs? applyFunction in KeyCondition.cpp built its _0x<function pointer>_<column index> cache key with a WriteBufferFromOwnString for both bounds of every checked range (about 1M calls per query in long_primary_key); it now formats the same text into a stack buffer and looks it up as a std::string_view, which halves the index analysis time of that test on x86.

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8600f71]

Summary: ✅


AI Review

Summary

PR #127495, head 8600f71da884, removes per-range cache-key allocations in applyFunction during primary and partition key analysis. No actionable findings. The reported x86 measurements show roughly 49% faster index analysis in long_primary_key, with unchanged query results and existing regression tests reported passing.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 22, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 22, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 23, 2026

@alexey-milovidov alexey-milovidov 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.

The change itself is clear, but using a pointer is weird.

@alexey-milovidov alexey-milovidov self-assigned this Oct 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8600f71da with master 4d1bce945 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 179708c7e; 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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

The address stands for the identity of the function here. Before #68354 the key was _<function name>_<column>, and chain links with different constant arguments (x + 1, x + 2) shared one cache entry, because a link with a constant argument reports only the function name (FunctionWithOptionalConstArg::getName). The address cannot be reused while the cache exists: the functions belong to the KeyCondition, and the cache lives for one part's markRangesFromPKRange call. This PR keeps the key text as it was. Numbering the chain links when the KeyCondition is built would remove the address; I can send that separately if you want it.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, yes, send a follow-up PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I will send a follow-up PR that numbers the monotonic chain links when the KeyCondition is built and keys the cached function result by that number instead of the function address, and post its link here.

Merged via the queue into ClickHouse:master with commit c8e0e06 Oct 23, 2026
526 of 528 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The follow-up is #127658. The cache key is now _<function number>_<column>, with the numbers assigned in the KeyCondition constructor. Because a short numbered key could equal a key column name such as _0_1, the index block columns are unnamed now.

@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
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-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... 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