Skip to content

Fix performance regression in short-circuit logical mask evaluation - #120520

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
acking-you:perf/short-circuit-mask-fusion
Sep 26, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
acking-you:perf/short-circuit-mask-fusion

Conversation

@acking-you

@acking-you acking-you commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

This fixes a performance regression in short-circuit evaluation of and/or introduced by #63723 (commit 4680d09e9a593524b85863acfbca421f0fb796a9). The unified execution path expands each filtered argument result back to the full block, then immediately scans it again to update the logical mask. The expansion is still present on upstream 2dc8de96f8bcbc1721b337651bb7daffe15d9e9f.

Consume the compact argument result directly while updating the mask at the original row positions. A separate null map preserves three-valued logic: NULL keeps a row active; a later decisive false for and or true for or overrides it. Generic maskedExecute retains its full-sized result contract for if/multiIf, and the public mask extraction functions still reject incorrectly sized numeric columns.

An isolated downstream 26.5-based comparison on an identical synthetic dataset and query reduced the cost of a four-way short-circuit predicate query:

Metric (median of 24 warm executions per build) Before After Reduction
Elapsed time 219.62 ms 203.82 ms 7.2%
Node cgroup CPU consumption 402.55 CPU ms 373.14 CPU ms 7.3%

Both candidates used 2,097,152 rows in 32 Wide parts, max_threads=2, the same CPU affinity and memory limit, and stopped background merges. Each read 1,097,393 rows / 208,029,785 bytes and returned the same checksum. Other changes were held constant. This is downstream evidence motivating the patch, not an upstream-master or production-wide speedup claim; other tested queries had small improvements or regressions.

Local verification: the new functional test and 11 existing short-circuit tests passed on both binaries in two runs each (48 test executions, zero skipped). The reference was generated from the baseline, agrees across disable/enable/force_enable, and was independently checked against a scalar three-valued-logic oracle. Both expected division-by-zero exceptions and skipped exceptions were exercised.

This local verification used the existing upstream Debug sandbox at a8d7dcd970551b8664e08b64f8c4fcf5efa10fa7, with the three affected source files taken from the PR base for the matched baseline and then patched. MaskOperations.cpp/.h were already identical to the PR base; intervening FunctionsLogical.cpp changes were documentation and exception wording. This is not a full build of current master; current-master CI remains to be run.

Isolated Debug timings and CPU sampling

Clang 21.1.8, the same Debug build configuration, max_threads=1, max_block_size=65536, compile_expressions=0, and short_circuit_function_evaluation='force_enable'. Candidate order was A/B/B/A; each case ran 12 times per start, with the first two discarded. Values below are medians of 20 retained executions per binary. Every case read 1,000,000 rows and had matching result checksums. Elapsed time is measured by the localhost HTTP client; CPU is UserTimeMicroseconds + SystemTimeMicroseconds from system.query_log. These are synthetic diagnostics on a shared development host, without confidence intervals, not Release speedup claims.

Case Elapsed ms, before → after Reduction Query CPU ms, before → after Reduction
AND SPARSE 10.508 → 8.045 23.43% 9.789 → 7.501 23.38%
OR SPARSE 11.037 → 8.621 21.89% 9.909 → 7.769 21.60%
AND MIXED 18.762 → 14.546 22.47% 17.994 → 13.814 23.23%
OR MIXED 19.792 → 15.171 23.35% 19.001 → 14.380 24.32%
AND DENSE 25.616 → 18.902 26.21% 24.890 → 18.120 27.20%
OR DENSE 26.774 → 19.904 25.66% 25.961 → 19.001 26.81%
AND NULLABLE 15.994 → 12.079 24.47% 15.321 → 11.163 27.14%
OR NULLABLE 16.834 → 12.635 24.94% 15.991 → 11.860 25.83%

The mixed or case is reproducible with:

SELECT or(
    number % 2 != 0,
    bitAnd(cityHash64(number), 1),
    bitAnd(cityHash64(number + 1), 1))
FROM numbers(1000000)
SETTINGS max_threads = 1, max_block_size = 65536,
    compile_expressions = 0, short_circuit_function_evaluation = 'force_enable'
FORMAT Null;

Separately, perf record -F 199 -e cpu-clock -g -p <server_pid> sampled repeated executions of the same case with 10,000,000 rows for about 20 seconds per binary (4,107 / 4,110 samples, zero lost samples):

Expansion symbol Baseline self / inclusive Patched
expandDataByMask<unsigned long> 25.15% / 25.20% Not present above the 0.1% report threshold

Only this logical-mask optimization differs between these two profiles. Missing a symbol at the report threshold is not proof of zero runtime; the lower independently measured query CPU supports the improvement. The source change removes expansion from this path while preserving it for generic masked execution.

The included performance test covers sparse, mixed, dense and nullable masks. The functional test covers all combinations of nullable logical inputs, nested and/or/if/multiIf, shared expressions, constants, LowCardinality, empty and partial blocks, and throwing suffixes that must execute or be skipped.

Related: #63723
Related: #114734

Changelog category (leave one):

  • Performance Improvement

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

Fix a performance regression in short-circuit evaluation of and and or by avoiding expansion of intermediate results that are only used to update the logical mask.


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

Version info

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

Consume filtered logical argument results directly when updating the
original row mask, preserving three-valued logic without expanding
intermediate columns. Keep the full-sized result contract for generic
masked execution used by `if` and `multiIf`.

Add functional coverage for nullable and nested expressions, constants,
shared arguments, filtered row positions, and skipped or required
exceptions, plus performance cases for different mask densities.

Related: ClickHouse#63723
@clickhouse-gh clickhouse-gh Bot added comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... external Author is not a member of the ClickHouse organization labels Sep 17, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e4322ec]

Summary: ✅


AI Review

Summary

This PR removes the extra full-block expansion in short-circuit and/or evaluation by consuming filtered intermediate results directly while preserving the existing full-sized contract for generic maskedExecute used by if and multiIf. I re-traced the nullable, constant, nested short-circuit, and LowCardinality paths against the previous implementation, checked the new functional and performance coverage, and did not find a correctness, compatibility, or evidence gap that warrants an inline review comment.

Final Verdict

✅ No new blocking or major issues found in the current diff.

LLVM Coverage Report

Measured on commit e4322ec.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 65/68 (95.59%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes short-circuit evaluation of and/or. Later arguments now run only on rows that are still undecided, and their compact result feeds the mask directly instead of being expanded back to full block size. The only flagged query is ClickBench Q30, at -10.5% (214 ms vs 239 ms). It was correctly kept as no change: 214 ms is inside master's current range of 199-286 ms, CPU time is flat (2392 ms vs 2422 ms), and none of the standard ClickBench queries around Q30 has a multi-argument and/or filter. No regressions were found on clickbench or tpch_adapted_1_official; the new short_circuit_compact_logical_masks perf test is the right place to measure this change.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 5d6c8ec9-ef37-4092-abc8-4cba62ca5a1b
  • MIRAI run: 8bc073ee-02e0-4f17-bfaa-471871975fbb
  • PR check IDs:
    • clickbench_1885537_1790393811
    • clickbench_1885543_1790393811
    • clickbench_1885549_1790393810
    • tpch_adapted_1_official_1885560_1790393811
    • tpch_adapted_1_official_1885572_1790393811
    • tpch_adapted_1_official_1885608_1790393811

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit a47213e Sep 26, 2026
176 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... external Author is not a member of the ClickHouse organization 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