Skip to content

Apply -WithMemoryTracking containers to src/Processors/Transforms - #125000

Merged
nickitat merged 20 commits into
masterfrom
wmt_processors_transforms
Nov 5, 2026
Merged

nickitat merged 20 commits into
masterfrom
wmt_processors_transforms

Conversation

@nickitat

@nickitat nickitat commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Version info

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

Replace the `std::` containers of the transforms with their
`-WithMemoryTracking` counterparts and add `src/Processors/Transforms` to
the style check.

Containers outside the directory are converted where a transform receives
or hands back their contents, so that nothing is copied at the boundary:

- `BlockInfo::out_of_order_buckets`, copied to and from
  `AggregatedChunkInfo`. It is serialized through the generic vector
  helpers, so the bytes on the wire do not change.
- `Aggregator::detachTemporaryData` and its `tmp_files`, which
  `AggregatingTransform` splices into its own list.
- `ExpressionActions::getInputPositions` and `executeOnColumns`, whose
  positions several transforms keep, and `ExecutionContext::inputs_pos`,
  which `executeOnColumns` already copies them into.
- `WindowDescription::window_functions` and `WindowStep`'s copy of it.
- `ConstraintsExpressions`, which `CheckConstraintsTransform` redeclared.
- The permutations and predicate inputs that `JoinStep`, `IEJoinStep`,
  `BlockNestedLoopJoinStep` and `SaveSubqueryResultToBufferStep` build for
  their transforms.

The positions overloads of `getEqualRangeEndAssumeSorted` take a
`std::span<const size_t>` instead of a `std::vector`, so they accept the
window transforms' tracked key indices and every existing caller as is.

The `ChunksToMerge` chain is the same change as in the `src/Processors/Merges`
pull request, applied byte for byte, so the two merge in either order.

Kept as `std::`, with the reason on the line: `applyPermutation`, which is
generic over the allocator, and the key columns `DistinctSetFilter` passes
to the aggregation-method interface, which takes a `std::vector`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b7344e8]

Summary: ✅


AI Review

Summary

PR #125000, reviewed at b7344e8b231988dd93936687ae99772d93aa0a47, replaces standard containers with memory-tracked containers across transforms and shared interfaces. The previously reported invalid group-index and excessive-reservation defects are fixed in the current code. No new correctness defect was identified, but the allocation-failure recovery still lacks focused regression coverage.

Tests
  • ⚠️ LimitByTransform.cpp:185–194: add a deterministic test that succeeds at emplaceKey, fails the subsequent group_counts.push_back, restores memory availability, and processes another chunk containing the same key. Assert valid output and column lengths. The existing ClearsOutputSlicesWhenTransformThrows deliberately retries with disjoint keys, so it cannot detect removal of the null-mapped recovery branch. The test should fail without that branch and pass with it. This coverage was already requested in the original review thread; no duplicate inline comment was posted.
Final Verdict

Status: ⚠️ Request changes — add the focused same-key allocation-failure regression test described above. The original code findings do not warrant reopening their resolved threads.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 9, 2026
@nickitat
nickitat requested a review from Algunenano October 9, 2026 22:26
@nickitat
nickitat marked this pull request as ready for review October 9, 2026 22:26
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b7344e8b2 with master e1c9e2684 (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.

Object file sizes

896 object files changed (+154.90 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 28.04 MiB 28.08 MiB +44.12 KiB (+0.15%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.4 s

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

No query shows a change that can be attributed to this PR. The diff mostly swaps std::vector, list, deque and unordered containers for memory-tracked versions in aggregation, join, window and transform code. These containers hold small per-query or per-block metadata, so they should not measurably affect ClickBench aggregation queries. Q30 (+10.7%) and Q31 (+10.0%) got slower in wall time but not in CPU time (both about 1% or less), their PR runs were noisier than the base, and both stay inside master's current range. The clickbench and tpch_adapted_1_official runs for this PR shared one host, which fits this pattern of contention. Q34 (-5.2%) is also within its normal range, and that query's history is noisy.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 220 243 +10.7% <0.0001 Wall time is +10.7%, but CPU time is flat (2331 vs 2347 ms) and the result sits inside master's current range. The PR's container swaps only touch small per-query or per-block metadata, so this delta cannot be pinned on the diff.
⚠️ 31 not_sure 259 285 +10.0% <0.0001 Wall time is +10.0%, but CPU time barely moves (+1%) and the result stays inside master's current range. The PR runs were also noisier than the base, which points to host contention rather than more aggregation work.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 28a7808f-d443-4e01-8bbd-2e257aa11d24
  • MIRAI run: bdb65179-3892-419f-8c1a-0d28a049c1cf
  • PR check IDs:
    • clickbench_750500_1791658764
    • clickbench_750512_1791658765
    • clickbench_750518_1791658764
    • tpch_adapted_1_official_750524_1791658765
    • tpch_adapted_1_official_750536_1791658765
    • tpch_adapted_1_official_750572_1791658765

@Algunenano Algunenano self-assigned this Oct 13, 2026

auto info = std::make_shared<ChunksToMerge>();
info->chunks = std::make_unique<Chunks>(std::move(chunks));
info->chunks = std::make_shared<VectorWithMemoryTracking<Chunk>>(std::move(chunks));

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.

Isn't it simpler to replace Chunks now? Otherwise we'll use std::make_shared<VectorWithMemoryTracking<Chunk>> until we change the global type and we'll need to change it again.

Convert the alias itself instead of spelling `VectorWithMemoryTracking<Chunk>`
at each converted site, as suggested in review. This also tracks the `Chunks`
used by `Aggregator`, `QueryResultCache`, `SortingTransform`, `Squashing`,
`SourceFromChunks` and the other transforms, and the sites converted earlier
go back to the `Chunks` spelling.

The only place where `Chunks` met an explicit `std::vector<Chunk>` is the
`ParquetBlockOutputFormat` row-group chain, which now takes `Chunks`.

Related: #125000 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
nickitat and others added 6 commits October 13, 2026 11:56
…sforms

# Conflicts:
#	ci/jobs/scripts/check_style/check_cpp.sh
#	src/Processors/Merges/Algorithms/FinishAggregatingInOrderAlgorithm.h
#	src/Processors/Transforms/FillingTransform.h
#	src/Processors/Transforms/IEJoinTransform.h
#	src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp
#	src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.h
Master added a `readField` overload for `std::vector<Int32>` that caps the
number of out of order buckets read from the peer at 256. This branch made
`BlockInfo::out_of_order_buckets` a `VectorWithMemoryTracking<Int32>`, so the
overload stopped matching and the generic, unbounded `readField` was picked
instead (caught by `-Wunused-function`). Take the field's type in the overload.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
…sforms

# Conflicts:
#	src/Interpreters/ExpressionActions.h
#	src/Processors/QueryPlan/WindowStep.cpp
#	src/Processors/QueryPlan/WindowStep.h
#	src/Processors/Transforms/BlockNestedLoopJoinData.cpp
#	src/Processors/Transforms/BlockNestedLoopJoinData.h
#	src/Processors/Transforms/Window/SlidingIndexes.cpp
#	src/Processors/Transforms/Window/SlidingIndexes.h
#	src/Processors/Transforms/Window/WindowTransformParams.cpp
#	src/Processors/tests/gtest_block_nested_loop_join_data.cpp
The test came from master and passed a `Chunks` to helpers taking
`std::vector<Chunk>`, which no longer compiles after `Chunks` became a
`VectorWithMemoryTracking<Chunk>`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
…sforms

# Conflicts:
#	src/Processors/Transforms/CopyTransform.h
#	src/Processors/Transforms/ScatterByPartitionTransform.h
#	src/Processors/Transforms/Window/WindowTransformParams.h
…sforms

# Conflicts:
#	src/Processors/Transforms/DistinctSetFilter.cpp
#	src/Processors/Transforms/ScatterByPartitionTransform.h
`group_counts` in `LimitByTransform` and `group_windows` in
`NegativeLimitByTransform` are now tracked, so their growth can throw
`MEMORY_LIMIT_EXCEEDED`. If that happened between `emplaceKey` and
`setMapped`, the key stayed in the hash table with a null mapped value, and
a later row with the same key would read a group index of `SIZE_MAX`.
Reserve the capacity before the key can be inserted, so the append after
`emplaceKey` never allocates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
nickitat and others added 3 commits November 2, 2026 21:57
…sforms

Take master's rewritten `WindowTransform` and apply `-WithMemoryTracking` containers to it, except the vectors handed
to `WindowArguments`, which owns `std::vector`. Convert containers in new master code of `FilterTransform`,
`RadixUniqExactTransform`, `AggregatingTransform` and `AddingDefaultsTransform`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
The per-row capacity check before `emplaceKey` made positive `LIMIT BY` 16-23% slower in the ARM performance
comparison. Even a once-per-chunk reserve inside `consumeImpl` changed its row loop codegen (the skewed-key query
of `limit_by` stayed 30% slower locally), so the reserve is done in `transform` before the dispatch. A chunk adds at
most `row_count` groups, so `push_back` still cannot throw between `emplaceKey` and `setMapped`.

Local A/B against master's `LimitByTransform` on 100M rows: all `limit_by` queries are within noise.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125000&sha=c2245b9f029431735798819ca5bc36c0dc64067a&name_0=PR&name_1=Performance+Comparison+%28arm_release%2C+master_head%2C+2%2F6%29&name_2=Check+Results
#125000

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
nickitat and others added 4 commits November 3, 2026 09:37
The reserves exist because `VectorWithMemoryTracking` throws `MEMORY_LIMIT_EXCEEDED` on allocation, unlike
`std::vector`, which opens a window between `emplaceKey` and `setMapped`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
Replace the reserves before `emplaceKey` with the pattern of `Aggregator`: a newly inserted key gets a null mapped
value, and any key with a null mapped value is given its group, which happens only after `push_back` (or
`emplace_back`) succeeds. If the allocation throws, which it can with `std::vector` too, the key keeps a null mapped
value and gets its group the next time it is seen, so a later chunk passed by `ISimpleTransform::work` cannot read
past the end of `group_counts` or `group_windows`.

Local A/B against the same code without the change on 100M rows: positive and negative `LIMIT BY` are within
noise (at most 4%).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
`WindowTransform` builds the argument column indices and blocks for `WindowArguments`, so they no longer need
`STYLE_CHECK_ALLOW_STD_CONTAINERS`. `WindowArguments` was the only user of std containers in
`src/WindowFunctions`, which is now linted for them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
…he check

It is generic over the container already, so taking the container type removes both
`STYLE_CHECK_ALLOW_STD_CONTAINERS`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
@nickitat

nickitat commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

@Algunenano do you want to take another look or should I merge?

@nickitat
nickitat added this pull request to the merge queue Nov 3, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 4, 2026
@nickitat
nickitat added this pull request to the merge queue Nov 4, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 4, 2026
@nickitat
nickitat enabled auto-merge November 4, 2026 12:24
…sforms

Take master's rewrite of window function arguments (`SlidingArguments`) and convert its
containers and `WindowArguments::last_used_block` to the `-WithMemoryTracking` counterparts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
@nickitat
nickitat added this pull request to the merge queue Nov 4, 2026
Merged via the queue into master with commit 67b794d Nov 5, 2026
186 checks passed
@nickitat
nickitat deleted the wmt_processors_transforms branch November 5, 2026 00:03
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
qiuyanjun888 pushed a commit to qiuyanjun888/ClickHouse that referenced this pull request Nov 13, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-not-for-changelog This PR should not be mentioned in the changelog 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