Skip to content

Fix quadratic reallocation in ColumnArray::replicateGeneric - #112897

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-replicate-generic-quadratic-realloc
Aug 4, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-replicate-generic-quadratic-realloc

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

Fixed quadratic reallocation when replicating an Array whose elements hold JSON values in shared data, for example a constant Array(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 reaches ColumnArray::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 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.

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. 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. And peak memory is unchanged from before the fix, so reserve keeps 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.

shape before after
[map('a',1)::JSON] 2.88s 0.51s 5.6x
[tuple(map('a',1)::JSON, 1)] 2.85s 0.50s 5.7x
[map('a',1)::JSON::Nullable(JSON)] 2.81s 0.51s 5.5x
[map('k', map('a',1)::JSON)] 3.02s 0.68s 4.4x
[map('a',1)::JSON::Dynamic] 3.02s 0.67s 4.5x
[map('a',1)::JSON::Variant(UInt64, JSON)] 2.98s 0.63s 4.7x
[[map('a',1)::JSON]] 2.93s 0.62s 4.7x
[[[map('a',1)::JSON]]] 2.98s 0.63s 4.7x

Shapes holding no Object are 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

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

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
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
round is clean: an independent cold review of the resulting code found no defect, and a
second-model pass over both the full diff and the round-6 delta returned no findings.

The rounds that mattered, and what they changed:

⚠️ Round 5 caught a real over-reservation and I rewrote the fix around it. An earlier
revision handed a count of the immediately nested level's elements to the polymorphic
IColumn::reserve. That passes n down unchanged, so for a type carrying a declared byte
width, a declared set of sub-columns, or one more container level, a count of values became
a byte request multiplied all the way down: a constant holding an empty
Array(FixedString(256)) replicated to 400000 rows asked for 97.66 MiB (256 * 400000
exactly) for a result that holds no FixedString at all. Since IColumn::reserve is
documented to affect performance only, that could fail a query the old code accepted, which
is not allowed. Computing an exact count one level deeper does not close it — it only moves
the amplification boundary down, and the recursion is unbounded. So the landed version
reserves only quantities whose byte cost is fixed per element, which in practice means
offset arrays. Three statements in the regression test now stand guard on that property
with max_memory_usage = 50000000; a mutant that restores the blanket reserve fails them
with Code 241.

⚠️ Round 6 corrected a comment that gave the wrong reason for a right decision. The arm
that reserves an Object nested column's shared data justified itself by claiming no
fan-out below it. That is false as written: the chain reaches ColumnTuple::reserve and
from there two ColumnString::reserve, and only one of the three offset arrays counts the
quantity being passed — the other two index shared data's paths and values, so they count
path-value pairs, a different quantity that is frequently zero. The decision is still
correct, for a stronger reason that is now what the comment says: shared data always has
the fixed, non-user-influenced type Array(Tuple(String, String)), so the whole chain is
8-byte offset arrays with no declared width anywhere, and it can never turn a count into a
request large enough to fail a query. Giving the two pair-counting arrays capacity is
deliberate and bounded at 8 bytes per element each, because leaving them unreserved does
not leave them alone: ColumnArray does not override insertManyDefaults, so
IColumn::insertManyDefaults re-runs reserve(size() + length) on the whole shared data
column once per row and the per-row reserve_exact pathology comes back. Peak memory on
that shape measured below master's.

💡 A residual gap one level down is disclosed, not hidden. A nested Array with inner
length above one, and a Dynamic holding an Array(JSON), are deliberately not sped up:
ColumnArray::reserve sizes a nested column as if arrays held one element at most, and
ColumnDynamic::reserve forwards to ColumnVariant::reserve, which sizes only
discriminators and offsets. No remedy confined to replicateGeneric exists for either, so
they are a separate root cause, tracked separately, and named in the test comments. One
test statement runs at a reduced row count for exactly this reason.

💡 Benchmark figures were moved out of the test file. Exact run times and allocation
counts rot in-tree, so they live in the PR description. What the test keeps is what a reader
cannot re-derive: why the guard is max_execution_time rather than an assertion on runtime,
that the limit does not bound wall clock (the reallocation loop is inside one replicate
call and the limit is only checked between blocks), why one statement is smaller, and which
shapes are deliberately not sped up.

Validation on the final text: 50/50 randomized runs all passed; whole-file output is
byte-identical to the reference; the timeout oracle was measured in both directions on an
ASan build (unfixed Code 159 after 1010 s against 0.96 s fixed, a ~1050x separation with
the 60 s limit roughly 17x clear of each side); every carrier of the invariant was
enumerated independently and no unfixed sibling exists.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two independent deterministic oracles. (1) Counting Allocator::realloc calls inside one ColumnArray::replicateGeneric invocation under gdb gives exactly 3N + O(1) on the unfixed binary, at every N and every run, for SELECT any(c), count() FROM (SELECT materialize(1) AS k, [map('a', 1)::JSON] AS c FROM numbers(N)) GROUP BY k. (2) For the over-allocation half, [CAST([], 'Array(FixedString(256))')] replicated to 400000 rows under max_memory_usage = 50000000 fails with Code: 241, attempt to allocate chunk of 97.66 MiB = 256 * 400000 bytes exactly. Neither is a probabilistic flake.
b Root cause explained? Two related defects at one site. (1) replicateGeneric inserted row by row with no reservation: for an Object nested column each single-row insert reaches ColumnObject::insertFromSharedDataAndFillRemainingDynamicPaths(..., length = 1) -> IColumn::insertManyDefaults(1), which starts with reserve(size() + 1), routed to ColumnArray::reserve -> ColumnTuple::reserve -> ColumnString::reserve -> PODArray::reserve_exact, which allocates exactly n with no geometric headroom, so capacity equals size and the next row reallocates again. The reallocation count is linear in the row count; the total bytes copied is quadratic. (2) Reserving from a count of the immediately nested level's elements is only sound for quantities whose byte cost is fixed per element: IColumn::reserve is polymorphic and passes n down unchanged, so for a type carrying a declared byte width, a declared set of sub-columns or a further container level it becomes a byte count multiplied all the way down. Computing an exact count one level deeper does not close that, it only moves the boundary one level down, and the recursion is unbounded.
c Fix matches root cause? Yes. Pre-sizing happens once, at the only site that knows the final sizes before the loop, and it is restricted to quantities that cannot be multiplied downwards: the result's own offsets, a nested Array/Map's offsets, and a nested Object's shared data (bounded by construction, since shared data always has the fixed type Array(Tuple(String, String)) per DataTypeObject::getTypeOfSharedData). Everything else is deliberately left unreserved, which is exactly what the code did before the change, so IColumn::reserve's documented performance-only contract holds. No widened bound, no no-random-* blanket tag, no defensive check at the reallocation site.
d Test intent preserved / new tests added? No existing test weakened. New regression test 04648_replicate_generic_no_quadratic_realloc: 14 statements = 8 scale statements (max_execution_time = 60), 3 over-allocation statements (max_memory_usage = 50000000), 3 value statements; 18 reference lines. I verified per statement under gdb that the scale statements really enter replicateGeneric, so none is vacuous, and each pins replicated values rather than only liveness. The three over-allocation statements are individually live: reverting the whole reservation block fails all three; a variant that computes an exact count one level deeper fails only the Array(Array(FixedString(256))) one; a variant that widens the Object arm back to the polymorphic reserve fails only the JSON(a Array(FixedString(256))) one. The nested-Array scale statement is labelled a value and no-crash non-regression row and runs at 20000 rather than 400000 rows, because the fix deliberately does not flatten that shape and at 400000 rows it would run for many minutes on a sanitizer build, past the file's own limit and the runner's per-test timeout; its comment gives the reason (the exact figures live in the PR description rather than in-tree, where they would rot). The wrapper statements' comment names which shapes stay linear (LowCardinality, a Dynamic holding an Array(JSON)), so the test claims no coverage the fix does not deliver. Cost of the whole file: 8.6 to 9.4 s on ASan, about 1 s on debug; the slowest single statement under eight concurrent copies pinned to nine cores is 3.50 s against the flaky check's 180 s per-execution budget, so no long tag is needed. 50 randomized runs of the file on the current binary (Build ID 7d52739798cc46ab85ce5dd23762505d6657de56): 50 passed, 0 failed, 0 skipped. Re-run after the round-r6 comment trim, so the green run is on the final test text.
e Both directions demonstrated? Yes, against a pristine master binary whose ColumnArray.cpp is byte-identical to origin/master (verified by diff) and the fixed binary (debug Build ID 1ad96f7112f6ffa2, ASan d0abc3335db07913). Reallocations inside one replicateGeneric, array length 1: 3015 / 6019 / 12023 at N = 1000 / 2000 / 4000 before, 17 / 20 / 23 after (constant across a 4x range). Array length 3: 3051 / 6061 / 12071 before, 53 / 62 / 71 after. Over-allocation direction: the three shapes above all succeed on the fix and all fail with Code: 241 when the reservation block is reverted; and for the shapes that already exceed the limit on master the fix now requests a smaller chunk than master does (32.00 / 32.50 / 32.00 MiB against 33.25 / 33.75 / 32.50 MiB). Four mutation rebuilds confirm each arm is load-bearing, including that deleting the Object arm sends the reported shape straight back to master's 12020 reallocations. Output is byte-identical in both builds, as expected for a reservation-only change. Re-verified independently on 2026-08-01 on freshly rebuilt binaries, with the served buildId() asserted equal to each binary's readelf -n Build ID before every verdict: the three over-allocation statements return rc=0 on the fix and rc=241 on a build of the previous revision's ColumnArray.cpp (whose message reads attempt to allocate chunk of 97.66 MiB, i.e. 256 x 400000 bytes exactly), and the whole test file is [ OK ] on the fix and [ FAIL ] on that build.
f Fix is general across code paths? Yes. Fixed at the source (replicateGeneric), not guarded at the reallocation site. All sibling replicate paths were read and are already correct: replicateNumber reserves both capacities separately and is the pattern this mirrors, replicateString / replicateConst pre-size in bulk, replicateNullable / replicateTuple delegate into ColumnArray::replicate. Every reserve override in src/Columns was enumerated and classified by whether it multiplies n downwards (Array, Map, Object, Tuple, Nullable, QBit, Lazy, FixedString) or not (String, Vector, Decimal, Variant, Dynamic, LowCardinality), and the dispatch is built from that classification rather than from a list of shapes that happened to be tried. ColumnLowCardinality's per-row reallocations were measured and are geometric, so it is linear and not a carrier.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured rather than assumed, on 15 shapes: Array(JSON), Array(Array(JSON)), Array(Tuple(JSON, UInt8)), Array(Dynamic), Array(Variant(UInt64, String)), Array(Map(String, UInt8)), Array(LowCardinality(String)), plus the over-allocation family Array(FixedString), Array(Array(FixedString)), Array(Array(Array(FixedString))), Array(Nullable(FixedString)), Array(LowCardinality(FixedString)), Map(String, Array(FixedString)), Tuple(Array(FixedString)), JSON(a FixedString) / JSON(a Array(FixedString)) / JSON(a Map(String, FixedString)), empty and populated, and Dynamic-wrapped. Nullable is also covered transitively through replicateNullable. Array lengths 1 and 3 both exercised for the fix and every mutation, so the offsets term and the nested term are checked independently. Boundaries: the 0 == col_size early return is untouched and the new block sits after it, and replicate already returns cloneEmpty() for empty or all-zero offsets, so replicate_offsets.back() is never read on an empty vector. The weighted element count is exact for the level it sizes.
h Backward compatible? Yes, trivially. No setting, no default, no serialization format and no wire protocol is touched, so no SettingsChangesHistory.cpp entry is required and no experimental gate applies. IColumn::reserve is documented as affecting performance only, not correctness, which is why changing reservations cannot change a result for any type; the byte-identical output in (e) confirms it. The change strictly widens what the code accepts: every query that succeeded before still succeeds, and three shapes that the previous revision could fail on the memory limit now succeed.
i Invariants and contracts preserved? Yes. The new block only calls reserve / reserve_exact on a freshly cloneEmpty()-ed result before any insert, so sizes are unchanged and only capacities move: the ColumnArray invariant data->size() == offsets.back() is untouched. No new lock, no new exception path (the pre-pass is arithmetic over offsets that the existing size check has already validated, and that check still runs first), and the early-return path is unchanged. Peak memory stays bounded by the result the code was going to allocate anyway and AllocatorWithMemoryTracking still applies; measured peak RSS at 6M rows is 571452 KB against master's 510100 KB, 1.12x, and no reservation can now exceed a fixed number of bytes per element.

Session id: cron:clickhouse-impl-slot-46:20260801-072000

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

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.

Comment thread src/Columns/ColumnArray.cpp Outdated

res_concrete.getOffsets().reserve_exact(replicate_offsets.back());

/// Only quantities whose byte cost is fixed per element, and is not multiplied by a declared

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.

@groeneai trim all these comments to 3 lines each

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [640e100]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
ThreadSanitizer: data race (STID: 3977-4818) FAIL cidb IGNORED

AI Review

Summary

The PR replaces the problematic inherited IColumn::insertManyDefaults path for ColumnArray with an offsets-only override, which removes the repeated exact-reserve cascade that made Array(JSON) replication quadratic through shared_data->insertManyDefaults(1). I re-read the current code, the added stateless regression, the full prior thread history, and the current CI discussion. The earlier bot findings were against superseded revisions and no longer apply; I did not find a new correctness, memory-contract, or coverage issue in the landed insertManyDefaults-based fix.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 1, 2026
Comment thread src/Columns/ColumnArray.cpp Resolved
Comment thread src/Columns/ColumnArray.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 1 query(s) regressed out of 37 analysed

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)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 23 regression 78 167 ×2.1 slower <0.0001 PR only adds a ColumnArray realloc fix for constant array arguments; Q23's SELECT-with-LIKE scan over non-array columns can't exercise it, and the baseline was very noisy. The verdict is locked, but re-run to confirm.

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: 178fc576-e915-4731-b5b4-2393973c27cb
  • MIRAI run: 91655214-ff00-4a7a-8e3d-a648bd5026c5
  • PR check IDs:
    • clickbench_1292191_1785620015
    • clickbench_1292197_1785620015
    • clickbench_1292208_1785620015
    • tpch_adapted_1_official_1292221_1785620015
    • tpch_adapted_1_official_1292247_1785620015
    • tpch_adapted_1_official_1292261_1785620016

Comment thread src/Columns/ColumnArray.cpp Resolved
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.
@groeneai
groeneai force-pushed the groeneai/fix-replicate-generic-quadratic-realloc branch from a24028e to 640e100 Compare August 1, 2026 18:43
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 640e100

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
Stress test (amd_tsan) / ThreadSanitizer: data race (STID: 3977-4818) pre-existing trunk race, not caused by this PR: the racing frames are DataTypeAggregateFunction::setVersion / updateVersionFromRevision / setVersionToAggregateFunctions, which this diff does not touch (it changes ColumnArray::replicateGeneric only). 30-day breadth is 5 occurrences spread over 4 unrelated PRs plus one master run #110997 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Finish Workflow succeeded and all 174 check-runs completed. #110997 names this exact STID as its
motivating failure and rewrites the in-place mutable version write those frames perform, so it is
the causal owner rather than a coincidental same-area change.

Session id: cron:our-pr-ci-monitor:20260802-020000

@PedroTadim

Copy link
Copy Markdown
Member

@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

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit 812b949 Aug 4, 2026
178 of 180 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 Aug 4, 2026
Comment on lines +424 to +426
auto last_offset = getOffsets().back();
for (size_t i = 0; i < length; ++i)
getOffsets().push_back(last_offset);

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.

@groeneai Where is the reserve for offsets before appending values?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 1, 2026
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.
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.

4 participants