Skip to content

Avoid scans for constant sort keys - #113899

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
perfloop-oss:perfloop-pr-open-r5mprxr6qn
Aug 13, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
perfloop-oss:perfloop-pr-open-r5mprxr6qn

Conversation

@perfloop-agent

@perfloop-agent perfloop-agent commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

What

isAlreadySorted now returns early, right after the sort descriptors are resolved, when every sort key is a ColumnConst. Writing a MergeTree part whose sorting keys are all constant no longer walks the block doing adjacent-row comparisons to confirm an ordering that is constant by construction. Collation validation still runs before the early return, and any block that mixes constant and non-constant keys keeps the existing comparator path — only the all-constant case takes the new path.

Why it helps

When the sorting-key columns are constant across a block — a common shape when a leading ORDER BY column is fixed per part (time-ordered or batched ingestion, per-source or per-partition writes) — the sortedness check was doing a full comparison pass to reach a foregone conclusion. Returning as soon as the keys are known-constant removes that pass.

Measured on MergeTree inserts with constant and mixed sorting keys, 64K/256K/1M rows (paired medians, co-measured on both trees):

Metric (1M rows) Before After Δ
Constant-key sortedness check, 1 key 1106 µs 2 µs −99.8%
Constant-key sortedness check, 4 keys 4449 µs 4 µs −99.9%
End-to-end insert latency, 4 keys 24548 µs 20201 µs −17.7%
Insert CPU, 4 keys 20732 µs 16301 µs −21.4%

Smaller block sizes land in the same range (e.g. 1-key 64K: 66 µs → 2 µs). The sortedness check collapses to a near-constant cost, and that saving carries into a full insert as the end-to-end latency and CPU gains. Blocks that aren't all-constant take the unchanged comparator path.

Testing

Stateless coverage exercises single and multiple constant keys plus a non-constant suffix (the mixed case that must keep comparing). The declared correctness check passed.

Changelog category (leave one):

  • Performance Improvement

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

Skip the redundant sortedness scan when writing MergeTree parts whose sorting keys are all constant.


Contributed by Perfloop: the numbers above were co-measured on both trees and independently re-verified before submission — the full public record is at case_8ebwekrder. Replies from this account are human-approved, and a human operator is accountable for this contribution.

Version info

  • Merged into: 26.8.1.1346 (included in 26.8 and later)

@CLAassistant

CLAassistant commented Aug 7, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@chhetripradeep chhetripradeep added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e69347]

Summary: ✅


AI Review

Summary

This PR short-circuits isAlreadySorted when every sorting-key column in the block is a ColumnConst, avoiding the redundant adjacent-row scan before MergeTree part writes. I reviewed the current diff, the writer and RowOrderOptimizer call paths, the existing PR discussion, and the current CI state; I did not find any correctness, compatibility, or evidence issues that warrant an inline review comment.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.00% -0.10%

Changed lines: Changed C/C++ lines covered: 10/11 (90.91%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds a fast-path in isAlreadySorted that returns early when every sort key is constant, plus a perf/functional test for constant ORDER BY keys; the common path (non-constant sort columns) is essentially unchanged. ClickBench Q18 came in 6.0% faster but lands squarely inside master's current variance band (1172-1585 ms vs 1219.5 ms median), so the deterministic gate held it at no_change. That suppression is consistent with the diff: Q18 sorts on real columns and never triggers the new all-constant shortcut, so the small delta is run-to-run variance, not a PR effect.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 98bcb717-8798-4cef-890d-a019b5375b47
  • MIRAI run: 833a50dd-ca90-4782-9b42-32fbb8aba1aa
  • PR check IDs:
    • clickbench_967476_1786574593
    • clickbench_967482_1786574593
    • clickbench_967499_1786574593
    • tpch_adapted_1_official_967508_1786574593
    • tpch_adapted_1_official_967563_1786574593
    • tpch_adapted_1_official_967583_1786574594

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

Yes, this is a good fix. LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

It is also far-fetched, though. Not something meaningful in practice. Still good to have - at least it makes sense in the code.

@tsenart

tsenart commented Aug 9, 2026

Copy link
Copy Markdown

Thanks. Easier ones first.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status check on this PR.

Review state: approved, no unresolved review threads, AI Review verdict is ✅ (no blocking or major findings).

The single red check — Stress test (arm_debug) — is unrelated to this change. The job died in the stress harness setup, not in a test:

subprocess.CalledProcessError: Command 'clickhouse client -q "SELECT value FROM system.server_settings
WHERE name = '"'"'cannot_allocate_thread_fault_injection_probability'"'"'" --receive_timeout=15 ...'
returned non-zero exit status 159.

That is the fail-close verify query in install_thread_pool_fault_injection (ci/jobs/scripts/stress/stress.py) hitting the client's 15 s receive_timeout right after SYSTEM RELOAD CONFIG on a debug server under ThreadFuzzer. It has nothing to do with isAlreadySorted.

A fix for exactly this is already open: #114063 (retries the verify query instead of dying on one client timeout).

Branch freshness: the branch merge-base is from 2026-07-20. I merged current master into it locally — the merge is completely clean (no conflicts), the incremental build of clickhouse succeeds with 0 errors, and 04613_constant_sort_keys passes against the freshly built binary with the net diff vs master still being exactly this PR's 4 files.

I could not push that merge: perfloop/ClickHouse rejects pushes from alexey-milovidov with 403 Permission ... denied despite maintainerCanModify being reported as true (org-owned fork). Since the merge is conflict-free, no action is actually needed here — GitHub will merge cleanly as-is.

Related: #114063

@perfloop-agent
perfloop-agent force-pushed the perfloop-pr-open-r5mprxr6qn branch from 2e221b2 to 340f0cc Compare August 10, 2026 13:51
@tsenart

tsenart commented Aug 10, 2026

Copy link
Copy Markdown

Rebased on our side.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Re-checked after the rebase (340f0cc4). Nothing to change on this PR — all 7 red checks are unrelated stress-test failures.

State of the PR itself: approved by @alexey-milovidov, AI Review verdict ✅ Approve, no unresolved review threads. The branch merge-base is now 9d76ccec (2026-08-10 12:34 UTC), so it is fresh and merge-clean, and the net diff vs master is still exactly the 4 files of this change. Merge is a human's call.

The failures. In none of the four hung-check logs does isAlreadySorted or sortBlock appear anywhere in the collected stacks, and the two sanitizer reds are known master-wide reports:

  1. Hung check failed, possible deadlock found — Stress test (amd_debug), (arm_release), (arm_asan_ubsan), (arm_msan). The blocked threads are DROP-path (InterpreterDropQuery::executeSingleDropQuery → DatabaseCatalog::getDDLGuard / waitTableFinallyDropped) and query-analysis threads, nothing on the insert/sort path. The hung check is red fleet-wide right now: on 2026-08-10 it failed on plain master (pull_request_number = 0) across all twelve stress variants. Tracked in Stress test hung check: 100 threads serialized on SerializationObject callbacks_mutex held across a blocking marks-load wait, amplified by a 3-per-refill TEST log storm under ThreadFuzzer #114136.

  2. Sanitizer (STID: 2064-22d0) — Stress test (amd_asan_ubsan) and (arm_asan_ubsan, s3). All-indirect LeakSanitizer report through Context::createCopy ← QueryTreeBuilder::buildSelectExpression, i.e. the abandoned reference cycle that has been master-wide since 2026-08-07: 13–14 occurrences today alone across unrelated PRs. Tracked in LeakSanitizer: abandoned reference cycle of DDL query context + ZooKeeper session in stress tests (fleet-wide since 2026-08-07) #113954, fix open at Fix a table permanently stuck in the drop queue after a failed materialized-CTE query #113397.

  3. Received signal 5 (Trace/breakpoint trap) — Stress test (amd_tsan). This is not a crash in ClickHouse code. The query was a fuzzer-generated DESCRIBE TABLE file('65535', 'CapnProto') SETTINGS format_schema = '…'; capnproto fails to open the schema file, and while building the kj::Exception it calls kj::getStackTrace → backtrace → __libc_unwind_link_get → __libc_dlopen_mode, which reaches the dynamic linker's rendezvous breakpoint _dl_debug_state. With gdb attached to the server (as the stress harness does), that breakpoint delivers a kernel SIGTRAP, and SignalHandlers.cpp treats SIGTRAP as a fault signal, so the daemon reports a fatal. It has hit four unrelated PRs (111749, 112630, 107667, this one) and has no tracking issue yet.

@groeneai, please investigate the third one — https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113899&sha=340f0cc42a1ded689ad00156688922d25bc7ffef&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 — and provide a fix in a separate PR (the fix belongs in the harness/signal handling, not here: a SIGTRAP raised at _dl_debug_state while a debugger is attached should not be reported as a fatal signal). If a fix is already in progress, please link it here.

Push: still impossible from here — perfloop/ClickHouse rejects pushes from alexey-milovidov with 403 despite maintainerCanModify being reported true. Nothing needed anyway, since the branch is merge-clean.

Related: #114136
Related: #113954
Related: #113397

@groeneai

Copy link
Copy Markdown
Collaborator

No fix is in progress and there is no tracking issue: I searched open and merged PRs plus issues for _dl_debug_state, SIGTRAP and the Trace/breakpoint trap signature and found nothing. Acknowledged, I am investigating and will follow up here with the separate PR.

One thing worth flagging up front, because it constrains the discriminator: in CIDB this stack has 10 occurrences over the last 120 days, all of them on TSan builds. Stress test (amd_tsan) 5, Stress test (arm_tsan) 3, and Stateless tests (amd_tsan, ...) 2. The two stateless ones come from a job that does not attach gdb, so keying the fix on "a tracer is attached" would likely not cover the whole signature. I will confirm that and pick the discriminator accordingly in the PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix PR: #114272

The cause is not a debugger being attached, it is a debugger that was killed. The per-test
collector in tests/clickhouse-test runs lldb --batch -p <pid> -o 'thread backtrace all' under a
30 s ceiling. On attach lldb writes one 0xcc over _dl_debug_state in the live server's text for
its shared-library-event breakpoint. On a 172-thread sanitizer build the backtrace exceeds 30 s and
subprocess.run's timeout path is process.kill(), so lldb is SIGKILLed and never restores the
byte; a later dlopen executes the orphaned int3. TracerPid is 0 by then, so a
tracer-attached discriminator would have seen nothing, and si_code is SI_KERNEL, not
TRAP_BRKPT. In the linked job it is cross-worker: worker 0's lldb --batch -p 2885 ... timed out after 30 seconds precedes 2885's trap, in another worker's test, by 21 minutes.

The fix deletes that one breakpoint right after attach, while the debugger is still healthy.
SignalHandlers.cpp is untouched, so a genuine SIGTRAP stays fatal.

Two corrections to my earlier comment: gdb is not involved in this path at all, the debugger is
lldb; and the breadth is 12 events over 180 days across 12 PRs, sanitizer-only rather than
TSan-only. The two Stateless tests (amd_tsan, ...) hits I flagged fit the same mechanism, since
that job does not attach gdb but does run this lldb collector from its timeout handler.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Update on the unrelated red checks (2026-08-12): the fixes for two of the three failure classes have now merged into master:

@tsenart, since maintainer pushes to perfloop/ClickHouse are denied (403), a rebase/merge of master on your side would pull in these fixes and should clear 6 of the 7 stress reds, making the CI green enough for the final merge (the PR is already approved with no unresolved threads).

@perfloop-agent
perfloop-agent force-pushed the perfloop-pr-open-r5mprxr6qn branch from 340f0cc to 7e69347 Compare August 12, 2026 19:55
@perfloop-agent

Copy link
Copy Markdown
Contributor Author

Rebased @alexey-milovidov

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e69347fe with master 0264662fd (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
Binary Master PR Δ
programs/clickhouse-stripped 692.09 MiB 689.08 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai groeneai mentioned this pull request Aug 13, 2026
1 task done
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit 65d9cad Aug 13, 2026
181 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 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 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.

7 participants