Skip to content

Faster negative LIMIT BY over sorted input with many small groups - #131166

Merged
nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:faster-negative-limit-by-small-sorted-groups
Nov 13, 2026
Merged

nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:faster-negative-limit-by-small-sorted-groups

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125013 (comment)
Related: #125000

Changelog category (leave one):

  • Performance Improvement

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

Negative LIMIT BY (for example LIMIT -1 BY k) over data sorted by the key is several times faster when the groups are small.

Description

The negative_limit_by_in_order queries #0, #1 and #8 (millions of groups) are reported slower together on PRs that do not touch them (#125013 and three others in 30 days). Their time goes to the per-group bookkeeping of NegativeLimitBySortedStreamTransform: every group, even one inside a chunk, went through the sliding window, whose window = {} freed the deque block and map after each group, so a one-row group cost two memory-tracked allocations, two frees and two shared_ptr copies. The #125013 job's counters for #0 show ~1,030 instructions per group, the same on both sides, with +15% cycles in one build; #125000, whose only change to this transform was the allocator of its containers, moved exactly #0, #1 and #8 by 16-19% at master d3ee313.

A group that ends inside the chunk while the window is empty also started in this chunk, so its rows are staged for output directly, and adjacent rows of one chunk form one pending slice. Groups that touch a chunk boundary still use the window. The output is unchanged.

Local A/B (release build, no ThinLTO, the perf test's tables and queries, 12 rounds, ratio new / master, 95% CI):

Query master new ratio
#0, 10M groups of 1 row 0.764 s 0.096 s 0.12 [0.11, 0.14]
#1, 1M groups of 10 rows 0.098 s 0.049 s 0.46 [0.41, 0.51]
#8, 5M groups, two String keys 0.447 s 0.116 s 0.25 [0.24, 0.27]

#2 (100k groups) is 0.71x; #3-#7 (100 groups) are 0.86-1.03x, within noise. User-space instructions of #0 drop from ~1,190 to ~190 per group. Existing negative LIMIT BY tests cover both paths: each of four mutations of the new code fails 3 to 8 of them.


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

Version info

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

…up window

`NegativeLimitBySortedStreamTransform::consume` sent every group, even one
that starts and ends inside the current chunk, through the sliding window:
`append_run` pushed a `ChunkSlice` into the empty window deque (allocating the
deque map and a block, and copying the chunk `shared_ptr`), `finalizeWindow`
copied it into `pending` (a second `shared_ptr` copy) and then `window = {}`
(libc++: `clear(); shrink_to_fit();`) freed the block and the map. So each
one-row group cost two memory-tracked allocations, two frees and two atomic
increment/decrement pairs, plus one `pending` entry.

The window is only needed for a group that touches a chunk boundary. A group
that ends inside the chunk while the window is empty also started inside this
chunk, so its output is known when its end is found: the last
`min(L, length + offset)` rows of the run without the trailing `offset` rows,
the same rows `append_run` + `dropExcessRows` + `dropOffsetRows` keep for a
one-slice window. Such groups are now staged into `pending` directly, and
`appendToPending` extends the last pending slice when the new rows continue
it in the same chunk, so the one-row groups of a chunk become one slice.
`generate()` produces the same chunk for a merged slice (same rows, first
start and last end). Groups touching a chunk boundary still use the window.

Evidence that this path is what moves the `negative_limit_by_in_order`
queries #0, ClickHouse#1 and ClickHouse#8 (millions of groups): ClickHouse#125000, which changed only the
allocator of these deques, moved them by -19/-16/-17% on master d3ee313 while
ClickHouse#2-ClickHouse#7 stayed flat; and the ClickHouse#125013 perf job's prewarm counters for #0 show
equal instructions on both sides (10301M vs 10333M, ~1030 per group) and +15%
cycles on one build.

Local A/B (release build, `CMAKE_BUILD_TYPE=None`, no ThinLTO, the perf
test's tables and queries, 12 rotating rounds, geomean of per-round ratios
new/base with bootstrap 95% CI):

  #0 10M one-row groups      0.764 s -> 0.096 s  0.123 [0.113, 0.135]
  ClickHouse#1 1M groups of 10         0.098 s -> 0.049 s  0.457 [0.413, 0.510]
  ClickHouse#2 100k groups of 100      0.025 s -> 0.019 s  0.707 [0.642, 0.785]
  ClickHouse#3-ClickHouse#7 100 groups           0.86-1.03, no CI lower bound above 1.0 (4-15 ms)
  ClickHouse#8 5M two-key groups       0.447 s -> 0.116 s  0.250 [0.236, 0.265]

User-space instructions of 5 runs of #0: 60.3G -> 10.2G (~1190 -> ~190 per
group after subtracting 5 runs of ClickHouse#3), cycles 16.2G -> 3.1G; ClickHouse#8: 31.4G ->
6.4G instructions. In the base profile of #0 about half of the samples are
in the deque allocation, `shrink_to_fit`, `CurrentMemoryTracker` and
jemalloc; none of them is in the top 15 after the change.

Replacing only `window = {}` by `clear()` (keeps the deque blocks) gives
0.526 / 0.594 / 0.583 on #0 / ClickHouse#1 / ClickHouse#8, so the direct staging is 4.3x and
2.3x faster than that on #0 and ClickHouse#8.

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 (2 findings, both on the PR text, none on the code).

# Sev Finding Verdict Evidence / action
1 💡 Description said #125000 "changed only the allocator of these deques", but #125000 touches 90 files AGREE, fixed in the description its only change to this transform is the container allocator; CIDB master d3ee313: #0 968 -> 782 ms, #1 117 -> 97 ms, #8 552 -> 454 ms, #2-#7 flat
2 💡 Changelog entry said "up to 8 times", a local build number (no ThinLTO) AGREE, fixed in the entry entry now says "several times"; the local A/B table stays in the description, labelled local; this PR's own perf CI gives the real number

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

Session id: cron:clickhouse-review-slot-9:20261113-003800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local over the perf test's tables, release build, 12 rotating rounds: #0 0.764 s on master vs 0.096 s, #8 0.447 s vs 0.116 s in every round; perf stat instruction counts repeat to 0.2%.
b Root cause explained? Every group, even one inside a chunk, went through the sliding window; window = {} freed the deque block and map, so each one-row group paid 2 memory-tracked allocations, 2 frees and 2 shared_ptr copies (~1,190 instructions per group locally, ~1,030 in the #125013 job's counters).
c Fix matches root cause? Yes. Groups that end inside the chunk with an empty window (they also started in it) are staged directly, and adjacent rows of one chunk share one pending slice. Replacing only window = {} by clear() was measured too and is 4.3x / 2.3x slower than this on #0 / #8.
d Test intent preserved / new tests added? Output is unchanged, so no new test. The existing negative LIMIT BY tests cover both paths: four mutations of the new code each fail 3 to 8 of them. The existing perf test negative_limit_by_in_order.xml (#0, #1, #8) is the performance evidence; it is not modified.
e Both directions demonstrated? Yes. master vs this change on the same data and CPUs: #0 0.12x, #1 0.46x, #8 0.25x, #3-#7 within noise; the LIMIT BY test family gives the same result on master and on this change (90 tests, random and fixed settings), and 50 randomized runs of each of the 9 negative LIMIT BY tests pass.
f Fix is general across code paths? Groups touching a chunk boundary keep the window path, and getRemaining() is unchanged (the last run of a chunk always stays in the window). The unsorted NegativeLimitByTransform and the positive LIMIT BY transforms are different code and do not tear down a window per group.
g Fix generalizes across inputs (params/datatypes/wrappers)? The new path only uses the end of the run returned by the existing key search, so all key types behave as before (UInt64, String, LowCardinality, Nullable, DateTime, two-column keys). LIMIT -0 BY, OFFSET larger than the group, a saturated window size and max_block_size 1/2/3 are covered by the existing tests.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or output change.
i Invariants and contracts preserved? The pending slices hold the same rows in input order. A slice is extended only with adjacent rows of the same chunk (the chunk's shared_ptr is alive while referenced), and generate() builds the same chunk from a merged slice. The only throwing call is the push_back, as before, and the window is untouched on that path.

Session id: cron:clickhouse-impl-slot-4:20261112-233501

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4ddb63b]

Summary: ✅


AI Review

Summary

The PR speeds up sorted negative LIMIT BY by staging complete groups within a chunk directly and merging adjacent output slices, avoiding per-group window allocations. Review of head 4ddb63bad9d4d4f4fda1d9b71fec113b18d9a8a8 found no actionable issues. The PR supplies before/after measurements from 12 benchmark rounds, and all ten negative LIMIT BY tests passed in Fast test, including offset, chunk-boundary, large-input, permuted-key, and distributed cases.

The slice consumers reviewed were generate and materializeSliceToChunkIfNeeded for range materialization, canGenerate for pending output, and getRemaining for the final window flush. Their handling remains valid when adjacent groups share a slice.

Final Verdict

✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4ddb63bad with master 5ea9bec93 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.63, programs/clickhouse-keeper ×0.66 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.6 s 12.9 s +9.4 s (+267%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.2 s +5.1 s (+246%)
Compile time of recompiled translation units

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

Job report

@nihalzp

nihalzp commented Nov 13, 2026

Copy link
Copy Markdown
Member

@groeneai Check if similar issue exist in LimitRangeTransform as well and if so fix it in this PR.

@nihalzp nihalzp self-assigned this Nov 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

I checked LimitRangeTransform: it does not have this problem, so this PR leaves it unchanged.

The cost removed here was the per-group window: a DequeWithMemoryTracking allocated and freed for every group, plus two shared_ptr copies. LimitRangeTransform keeps no per-window state: transformAll appends each selected range as a {start, length} pair to output_slices, a vector reused across chunks (adjacent ranges are merged), and each chunk is materialized once.

Measured with the amd_release binary of this PR's CI on SELECT number FROM numbers(100000000) ... FORMAT Null, 5 runs each, user-space instructions from perf stat, per window after subtracting the 100-window query:

LIMIT clause Windows Time per run Instructions per window
LIMIT 1 AFTER number % 1000000 = 0 ALL 100 0.077 s -
LIMIT 1 AFTER number % 2 = 0 ALL 50M 0.61 s 140
LIMIT AFTER number % 2 = 0 ALL UNTIL number % 2 = 1 50M 0.76 s 248

For comparison, the sorted negative LIMIT BY spent about 1,190 instructions per one-row group before this PR and 190 after (local build, same subtraction). In perf record of the two 50M-window queries no allocator or memory tracker function is in the top 15 (CurrentMemoryTracker::allocImpl is at 0.15%); 62% and 73% of the samples are in the loop over boundary matches of transformAll, inlined into transform.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4ddb63b

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
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 05137_lazy_load_tables_replace_proxy_after_load flaky, not from this PR (it changes only NegativeLimitByTransform): total_bytes_uncompressed read 0 instead of 1 after the lazy load, and the runner's 37 reruns with the same settings passed. The test also failed on 2 master runs and 6 other PRs since 2026-11-12 a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same one as above)

Apart from the Config Workflow / Pre Hooks row of the first run (it only waited for the can be tested label; the re-run passed), CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261113-043010

@nihalzp
nihalzp enabled auto-merge November 13, 2026 05:08
@nihalzp
nihalzp added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit 21809ea Nov 13, 2026
606 of 608 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05137_lazy_load_tables_replace_proxy_after_load: #131220

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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