Repository navigation
Fix quadratic reallocation in ColumnArray::replicateGeneric - #112897
PedroTadim merged 1 commit into
Conversation
Internal second-model review (6 fix rounds, final round clean)This change went through six independent review rounds before I opened the PR. The final The rounds that mattered, and what they changed:
💡 A residual gap one level down is disclosed, not hidden. A nested 💡 Benchmark figures were moved out of the test file. Exact run times and allocation Validation on the final text: 50/50 randomized runs all passed; whole-file output is |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-46:20260801-072000 |
|
cc @Avogar @antonio2368, could you review this? ColumnArray::replicateGeneric appended row by row with no pre-size, so for an Object nested column each insert reached IColumn::insertManyDefaults(1) -> reserve(size()+1) -> PODArray::reserve_exact, which allocates the exact request, leaving capacity equal to size and reallocating on every row; the fix pre-sizes once and reserves only offset arrays, since IColumn::reserve passes n down unchanged and must never fail a query on the memory limit. |
|
|
||
| res_concrete.getOffsets().reserve_exact(replicate_offsets.back()); | ||
|
|
||
| /// Only quantities whose byte cost is fixed per element, and is not multiplied by a declared |
There was a problem hiding this comment.
Done in e1822d9. Every block this PR adds is now 3 lines or fewer: 8/11/13 in ColumnArray.cpp and 25/7/6/7 in the test file, down to 3 each.
I applied it to the test file too, not just the file you commented on, since that was the worse offender.
What each block still states is the part that is not re-derivable at the call site: that the outer and nested capacities are reserved separately because ColumnArray::reserve sizes the nested column as if arrays held one element at most; that unreserved inserts land in PODArray::reserve_exact, so capacity equals size and every row reallocates; that only offset arrays may be reserved, since IColumn::reserve passes n down unchanged and affects performance only; that Object shared data is safe because its type is fixed at Array(Tuple(String, String)); and that max_execution_time does not bound wall clock. The rest was reasoning the PR description already carries or a reader can re-derive, so it moved there rather than being dropped.
Comments only, and mechanically so: the comment-stripped text of both files hashes identically before and after, and the test still matches its unchanged .reference.
|
Workflow [PR], commit [640e100] Summary: ❌
AI ReviewSummaryThe PR replaces the problematic inherited Final Verdict✅ No new findings. |
|
📊 Cloud Performance Report
One query is flagged: clickbench Q23 shows a ×2.1 slower shift, large and consistent enough that the verdict is locked. However, this PR only adds a narrow ColumnArray::insertManyDefaults optimization (a quadratic-realloc fix that only fires for constant array-typed arguments), and Q23 is a SELECT-with-LIKE scan over non-array columns that never reaches that path, so the change cannot plausibly cause a regression there. The baseline measurements were also very noisy, so the delta reads more like measurement variance than a real PR effect. Recommend re-running Q23 before treating it as a genuine regression. clickbench🔴 1 regressed Flagged queries (1 of 43)
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
|
A constant Array(JSON) argument to an aggregate reaches ColumnArray::replicateGeneric, where building the result copied a number of bytes that grew quadratically with the row count. At 3.2M rows one such query took 2.9s; it now takes 0.5s. The cost originates in ColumnArray::insertManyDefaults, which was inherited from IColumn. That opens with reserve(size() + length), and ColumnArray::reserve passes the count down to the nested column unchanged. A default array is empty, so the nested column gets sized for elements it never receives, and the reservation is exact, leaving capacity equal to size. ColumnObject::insertRangeFrom calls shared_data->insertManyDefaults(1) once per replicated row when the value lives in shared data, so that exact reservation was re-applied per row and every row reallocated. Override it to append the offsets directly instead. They then grow geometrically through PODArray::push_back, so repeated calls stay amortized and no nested data is reserved at all. ColumnString already overrides its own insertManyDefaults with the same shape. Fixing it at this level rather than by pre-sizing in replicateGeneric keeps two properties. Coverage does not depend on recognizing wrapper types, because the fix sits below all of them: measured at 3.2M rows, Map values 4.4x, Dynamic 4.5x, Variant 4.7x and nested Array 4.7x, alongside bare 5.6x, Tuple 5.7x and Nullable 5.5x. And peak memory is unchanged from before the fix, so reserve keeps affecting performance only, with no query failing a memory limit it previously satisfied. The regression test asserts the wrapper shapes by value and pins the memory parity. On a pre-fix ASan build the file took 985.90s and hit TIMEOUT_EXCEEDED; it now takes 8.31s, so a re-regression fails the job.
a24028e to
640e100
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code |
CI finish ledger - 640e100Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260802-020000 |
|
@Avogar the PR despite being simple, I am not sure if it is doing the right solution. Can you give a quick look? It should be fast |
812b949
| auto last_offset = getOffsets().back(); | ||
| for (size_t i = 0; i < length; ++i) | ||
| getOffsets().push_back(last_offset); |
There was a problem hiding this comment.
@groeneai Where is the reserve for offsets before appending values?
There was a problem hiding this comment.
You are right, it is missing, and I checked it is safe to add here.
To be clear about what was removed under review earlier: that was getSharedDataColumn().reserve(n) in replicateGeneric, which cascaded into ColumnTuple::reserve and two ColumnString::reserve and sized nested data for elements a default array never holds. getOffsets().reserve(...) touches only the offsets PODArray, so it has no such cascade, and I confirmed it does not bring the memory-limit regression back.
I built two binaries differing only in this function and bisected the minimum passing max_memory_usage, which is deterministic and does not depend on timing.
Unchanged on the two shapes that motivated removing the earlier reserve, at 400000 rows:
| shape | merged | with offsets reserve |
|---|---|---|
[CAST('{}', 'JSON(max_dynamic_paths=0)')] |
10.551 MB | 10.551 MB |
[map('a', 1)::JSON] |
19.490 MB | 19.490 MB |
Lower on the one call site that passes a large length in a single call, DataTypeObject.cpp:592 (insertManyDefaults(object_column.size() - 1), reached from distinctJSONPaths):
| rows | merged | with offsets reserve | saved |
|---|---|---|---|
| 4000000 | 51.09 MB | 35.55 MB | 15.54 MB |
| 8000000 | 113.28 MB | 82.19 MB | 31.09 MB |
| 16000000 | 206.64 MB | 145.70 MB | 60.94 MB |
The 16000000 row figures reproduced exactly on a second independent pass. The saving is the transient of the last doubling: geometric growth holds the old and new buffers at once, about 1.5x the final power-of-two allocation, where one reserve allocates it once. That predicts P/2, i.e. 16.78, 33.55 and 67.11 MB against 15.54, 31.09 and 60.94 measured.
It also costs the per-row caller nothing, since PODArray::reserve is if (n > capacity()) and that caller already has the capacity.
I did not spot it because I was reasoning about the per-row insertManyDefaults(1) carrier from the incident, where amortized growth is enough, and I did not look at the bulk call site. The sibling overrides agree with you: ColumnVector, ColumnDecimal, ColumnFixedString and ColumnVariant all size the destination up front via resize_fill, and IDataType::insertManyDefaultsInto reserves as well. ColumnString::insertManyDefaults is the only one shaped like this, and it has the same gap.
Wall clock could not settle this, for the record: an isolated measurement gave 0.60s against 0.16s at 16000000 rows, but on a loaded machine the medians overlapped, so I am quoting peak memory rather than time.
I will open a follow-up PR adding the reserve and link it here.
There was a problem hiding this comment.
Opened as #113577. It adds getOffsets().resize_fill(size + length, last_offset) to both
ColumnArray::insertManyDefaults and ColumnString::insertManyDefaults, so the offsets are sized once
instead of walking the doubling chain.
resize_fill rather than the literal getOffsets().reserve(...) only because it is what the sibling
overrides you pointed me at already use (ColumnVector.h, ColumnDecimal.h, ColumnFixedString.h,
ColumnVariant.cpp); the allocation is identical either way. It is deliberately the geometric
reserve and not reserve_exact, since reserve_exact would leave capacity equal to size after every
call and reallocate on every row of the one-default-per-row path.
New unit tests in src/Columns/tests/gtest_column_array.cpp assert the tracker peak (50,331,648 ->
33,554,432 bytes at length = 4000000, reallocations 14 -> 1) and that the growth stays geometric, so
a later reserve_exact regression fails a test rather than passing silently.
Follow-up to ClickHouse#112897, requested in review on the shipped override: its offsets are appended with a bare push_back loop and never reserved. PODArray::push_back grows through reserveForNextSize -> realloc(allocated_bytes() * 2), so appending a known count of N elements performs O(log N) reallocations instead of one. Allocator::realloc calls CurrentMemoryTracker::alloc(new_size) before CurrentMemoryTracker::free(old_size), so the last doubling is charged old+new simultaneously: a transient peak of about 1.5x the final allocation where a single reserve costs 1.0x. Both functions now use resize_fill(offsets.size() + length, last_offset), which is reserve(n) plus the same appended values with the loop removed, and matches how ColumnVector, ColumnDecimal, ColumnFixedString and ColumnVariant already implement insertManyDefaults. last_offset is read by value before the call because resize_fill takes a const reference and may reallocate, the hazard ColumnArray::insertDefault documents in its NOTE 2. The reserve is deliberately geometric. reserve_exact would leave capacity equal to size after every call, so the one-default-per-row path that ClickHouse#112897 exists to fix would reallocate on every row: modelled at 400000 reallocations against 15, and 610398 MiB of realloc copying against 4 MiB. Only the offsets are pre-sized; the nested column is still untouched, which is why the inherited IColumn::insertManyDefaults was dropped in ClickHouse#112897. ColumnString had the identical shape and is fixed here too, so no insertManyDefaults override in src/Columns/ appends without pre-sizing any more. Measured on Debug builds at length = 4000000, offsets 32000000 bytes: tracker peak 50331648 -> 33554432 bytes, reallocations 14 -> 1. Both figures were first predicted from PODArray and Allocator semantics and then reproduced exactly on the binaries. The per-row path keeps an identical final size and peak. A capacity() assertion cannot detect this change: both versions produce the identical offsets capacity for every length >= 500, so the new tests assert the peak under a scoped MemoryTracker, plus that growth stays geometric. Verified with four mutants, each reverting one half of the change, each reddening exactly one assertion and no other.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed quadratic reallocation when replicating an
Arraywhose elements holdJSONvalues in shared data, for example a constantArray(JSON)passed to an aggregate function. Such queries copied a number of bytes that grew quadratically with the row count.Description
A constant
Array(JSON)argument to an aggregate reachesColumnArray::replicateGeneric, where building the result copied a quadratically growing number of bytes. At 3.2M rows such a query took 2.9s; it now takes 0.5s.The cost originates in
ColumnArray::insertManyDefaults, which was inherited fromIColumn. That opens withreserve(size() + length), andColumnArray::reservepasses the count down to the nested column unchanged. A default array is empty, so the nested column gets sized for elements it never receives, and the reservation is exact, leaving capacity equal to size.ColumnObject::insertRangeFromcallsshared_data->insertManyDefaults(1)once per replicated row when the value lives in shared data, so that exact reservation was re-applied per row and every row reallocated.The fix overrides it to append the offsets directly. They then grow geometrically through
PODArray::push_back, so repeated calls stay amortized and no nested data is reserved at all.ColumnStringalready overrides its owninsertManyDefaultswith the same shape.Fixing it at this level rather than by pre-sizing in
replicateGenerickeeps two properties. Coverage does not depend on recognizing wrapper types, because the fix sits below all of them. And peak memory is unchanged from before the fix, soreservekeeps affecting performance only and no query fails a memory limit it previously satisfied.The regression test asserts the wrapper shapes by value and pins the memory parity. On a pre-fix ASan build the file took 985.90s and hit
TIMEOUT_EXCEEDED; it now takes 8.31s, so a re-regression fails the job.Measured speedup by wrapper shape
Debug build, 3.2M rows, one thread, against a pre-fix master build.
[map('a',1)::JSON][tuple(map('a',1)::JSON, 1)][map('a',1)::JSON::Nullable(JSON)][map('k', map('a',1)::JSON)][map('a',1)::JSON::Dynamic][map('a',1)::JSON::Variant(UInt64, JSON)][[map('a',1)::JSON]][[[map('a',1)::JSON]]]Shapes holding no
Objectare unaffected:[toLowCardinality('x')]1.60s/1.59s,[1,2,3]0.13s/0.14s,[map('a',1)]0.39s/0.38s,[CAST([], 'Array(FixedString(256))')]0.26s/0.25s.Peak memory on
[CAST('{}', 'JSON(max_dynamic_paths=0)')]at 400k rows, three runs per cell, is identical before and after: both fail at 12/13/14MB and both pass from 15MB.Version info
26.8.1.751(included in26.8and later)