Skip to content

Do not copy the key range for every atom in the lightweight primary key analysis - #129381

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:sparse-key-analysis-no-range-copy
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:sparse-key-analysis-no-range-copy

Conversation

@groeneai

@groeneai groeneai commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #100394 (comment)

Changelog category (leave one):

  • Performance Improvement

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

Primary key analysis is faster for filters with many comparisons on the key columns (for example a long OR of time ranges): the default lightweight analysis no longer copies the key range of a column for every comparison it checks.

Description

Perf test key_condition_multi_atom_wide_or query #0 went red in this job of #100394 (+35.8%), and was reported slower on master (8112065) and on #102194 in the same two days. The PRs' own code is not involved: the slow builds run the same instructions in more cycles. The official binaries reproduce it on my machine at equal instruction counts: master 8112065 is 43% slower than the commit before it, and the #100394 build is 101% slower than its reference.

Almost all of that query's time is primary key analysis in the default lightweight (sparse) KeyCondition::checkInHyperrectangle. For every atom (about 120 per call here, thousands of calls per query), its IN_RANGE branch copied the key range of the column, passed it through applyMonotonicFunctionsChainToRange even when the chain is empty, and walked hasNullOrNaNInside through the generic Tuple worklist twice.

Now that branch points at the key range and copies it only to widen its upper bound or to apply a non-empty chain, as the other overload of this function already does. hasNullOrNaNInside answers a bound that is not a Tuple directly. The same Field values are compared in the same order, so the results do not change. This does not remove the slow mode of some builds itself (all my local builds are in the fast one); it makes the loop that mode slows down about 40% cheaper.

Validation: release build A/B from one tree, median of 30 runs, 5 rounds: query #0 index analysis 8.0 ms -> 4.7 ms (-42%), instructions -20%. Other perf tests: key_condition_multi_expression_key -25%, primary_key_exclusion_search_non_key_conditions -20%, long_primary_key and key_condition_multi_atom_large_in unchanged. On a debug build the 172 key analysis tests pass (one PostgreSQL-protocol test could not run locally), and 37 of them pass 50 times with random settings.


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

…ey analysis

The IN_RANGE branch of the sparse `KeyCondition::checkInHyperrectangle` (the
default `use_lightweight_primary_key_index_analysis` path) copied the key range
of its column for every atom, moved it through
`applyMonotonicFunctionsChainToRange` even for an empty chain, and then ran the
generic `Tuple` worklist of `hasNullOrNaNInside` twice. A filter with many
comparisons on the key columns evaluates thousands of such atoms per query.

Point at the key range and copy it only when the upper bound is widened or a
non-empty chain is applied, as the non-sparse overload already does
(eed8220), and answer a non-`Tuple` bound of `hasNullOrNaNInside` directly.
The results are the same.

`key_condition_multi_atom_wide_or` query #0 was red on Performance Comparison
on several unrelated builds (official master 8112065, PR builds of ClickHouse#100394
and ClickHouse#102194): those builds run the same instructions in up to 2x the cycles,
and the extra samples are in this loop. Locally (release, median of 30 x 5
rounds) its index analysis goes from 8.0 ms to 4.7 ms and its instructions
drop by 20%.

Related: ClickHouse#100394 (comment)

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

groeneai commented Nov 4, 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; 0 findings) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 MergeTreeSetIndex::checkInRange (Set.cpp:1255, :1407) also copies the key range for an empty chain DISAGREE Out of scope: the IN-set path, other file; no measured cost
2 💡 The description should not imply the per-build slow mode is gone AGREE, fixed in the description The extra cycles of slow builds include intersectsRange/containsRange, which stay

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

Session id: cron:clickhouse-review-slot-8:20261104-210700

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The official slow binaries reproduce their slow mode locally in 3/3 rounds at equal instructions (master 8112065 +43% vs 84451f1, #100394 build c210c4b +101% vs its reference). The A/B oracle (query #0 x 30 in clickhouse local, FilteringMarksWithPrimaryKeyMicroseconds) separates base and fix in 5/5 rounds.
b Root cause explained? For every atom, the IN_RANGE branch of the sparse checkInHyperrectangle copied the key range of its column, passed it through applyMonotonicFunctionsChainToRange for an empty chain and ran the generic Tuple walk of hasNullOrNaNInside twice. The slow builds run the same instructions in more cycles in this loop; the fix removes the redundant part of its work, not the slow mode itself.
c Fix matches root cause? Yes. The branch points at the range and copies it only to widen it or to apply a non-empty chain, as the non-sparse overload already does. A non-Tuple bound skips the worklist. The perf test is unchanged. Not claimed: that no future code layout can be slow.
d Test intent preserved / new tests added? No new test: behaviour does not change, and key_condition_multi_atom_wide_or.xml measures the change. No existing test is modified.
e Both directions demonstrated? Release base vs fix from one tree with the same flags: 8.0 ms -> 4.7 ms index analysis (-42%), instructions 5.96G -> 4.76G, in 5/5 rounds.
f Fix is general across code paths? The non-sparse overload already had this shape. IS_NULL/IS_NOT_NULL are pointer-based. ARGS_IN_HYPERRECTANGLE copies on purpose. IN sets apply their own chains in Set.cpp. Every caller of hasNullOrNaNInside gets the non-Tuple path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, LowCardinality and Tuple keys, and nested NULL/NaN bounds, see the same Field values; Tuple bounds keep the full walk. 172 key-analysis tests pass on debug; 37 of them pass 50x with random settings (1850/1850). Other perf tests: no query slower than 3%.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default changes.
i Invariants and contracts preserved? Yes. upper_bound_widened is still computed from the unwidened bound and still clears contains. With widening plus a non-empty chain, the helper takes Range by value, so its argument is copied before the result replaces the storage. A failed chain still gives (true, true).

Session id: cron:clickhouse-impl-slot-4:20261104-200900

@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @CurtizJ, could you review this and add the can be tested label so CI runs? In the default lightweight KeyCondition::checkInHyperrectangle, the IN_RANGE branch no longer copies the key range of its column for every atom (only to widen the upper bound or to apply a non-empty monotonic chain), and hasNullOrNaNInside answers a non-Tuple bound directly; key_condition_multi_atom_wide_or index analysis is about 40% faster locally.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f297b3d]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-1bfa) FAIL cidb

AI Review

Summary

PR #129381 removes redundant Range copies from lightweight primary-key analysis and skips tuple-walk setup for scalar inputs to hasNullOrNaNInside. No actionable findings at head f297b3dd63a95b561481cfead7e9d315eb2962c3. The author reports repeated A/B measurements of 8.0 ms → 4.7 ms for index analysis; the Fast test report includes 125 passing key-condition tests and four skips. Review used source inspection and available CI results; benchmarks were not rerun locally.

Final Verdict

Status: ✅ Approve.

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

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f297b3dd6 with master 7c85a9b48 (stripped binary size, per-symbol sizes and ThinLTO time; 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, 25 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f297b3d

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
AST fuzzer (amd_debug, targeted) / Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-1bfa) not from this PR (it changes only how KeyCondition passes the key range to the sparse analysis): since #128992 the formatter splits a compound function name on every dot, so the back-quoted part remoteSecure('[::{1..4}]:9440', ...) of a fuzzed .COLUMNS(...) call is printed with an empty part, which does not parse back. The same shape failed the AST fuzzer on 7 other PRs since 2026-11-04 #129405 (mine, open)
PR praktika rollup of the row above #129405 (mine, open)

The Config Workflow / Pre Hooks failures in CIDB come from the two runs before the can be tested label and are superseded by this run. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261105-013005

@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 19, 2026

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant