Repository navigation
Pre-size the offsets in ColumnArray::insertManyDefaults and ColumnString::insertManyDefaults - #113577
Conversation
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.
…ad tracker Two review findings, both outside the fix itself. The comment above ColumnString::insertManyDefaults was written twice verbatim. One copy is enough. The unit test's peakOf helper reparented the thread memory tracker to a scoped one and reset its counters, then restored the parent and reset again on the way out. The reset on the way out fires while the caller's column is still alive, so freeing it afterwards subtracts from an amount that was just stored to zero, and MemoryTracker::free does not saturate at the Thread level. The main-thread tracker was left around 32 MiB negative per arm. The setup-side reset is worse in a second way: resetCounters also zeroes hard_limit, soft_limit and profiler_limit, so a limit an earlier test in the same binary had installed was silently dropped, no matter when the column died. Neither reset is needed. setParent alone routes the body's allocations into the scoped tracker, and the peak is read back from that tracker, so the thread tracker's own counters were never part of the measurement. Without them the body's allocation and the caller's later free cancel and the tracker ends where it started, measured at a delta of zero against about -33.5 MB before. No in-tree test is observably broken by the old behaviour today: the one test that clamps the thread tracker relative to its current usage cancels the offset on both sides of the limit check, and the two that set an absolute limit reset the counters themselves first. The hazard was latent rather than reachable. The reserve_offsets change itself is unchanged.
peakOf called MainThreadStatus::getInstance(), which is a function-local static whose ThreadStatus base constructor sets current_thread permanently. This file links before Columns/tests/gtest_column_tuple.cpp, so by the time that test constructed its own stack ThreadStatus, current_thread was already set and the chassert(!current_thread) in the ThreadStatus constructor aborted the whole unit_tests_dbms process, taking every later suite with it. The assertion is older than this test file, but nothing before it in link order had ever left a ThreadStatus installed, so it had never fired in the default run. Run the measured window on a dedicated thread owning a local ThreadStatus instead, as Common/tests/gtest_thread_group_switcher.cpp and Common/tests/gtest_thread_pool_callback_runner_shutdown.cpp already do. That thread's destructor clears current_thread, so nothing leaks to later suites. The oracle is unaffected: the peak is read from scope_tracker, allocations reach it through setParent, and a local ThreadStatus's tracker parents to total_memory_tracker exactly as the main thread's does. Verified with no shuffle, the ordering CI uses: filter 'ColumnArray.*:ColumnString.*:ColumnTuple.*' aborted before and now reports 17 of 17 passing, with ColumnArray and ColumnString demonstrably running first. The mutation arms still discriminate, each reddening only its own column's assertion at an unchanged 50331648 vs 32000000 bytes.
Internal second-model review (click to expand)Three review rounds, two independent channels each (a cold read of the resulting code, then a
Independently re-derived rather than taken from the implementation notes: the peak and reallocation Session id: cron:clickhouse-review-slot-10:20260805-205400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-10:20260805-205400 |
|
cc @CurtizJ @azat, could you review this? Both |
|
Workflow [PR], commit [79f50fb] Summary: ❌
AI ReviewSummaryThis PR replaces the per-element PR Metadata
Findings
Final VerdictNeeds one more test-strengthening change before I would treat the regression coverage as sufficient. LLVM Coverage ReportMeasured on commit 79f50fb.
Changed lines: Changed C/C++ lines covered: 78/78 (100.00%) · Uncovered code |
|
📊 Cloud Performance Report
Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor. This PR replaces per-element push_back loops with a single resize_fill in insertManyDefaults for String and Array columns, making bulk default insertion cheaper and lower-peak. The consistent ClickBench improvements on SearchPhrase-heavy queries (Q13/Q15/Q17/Q18/Q31) and the TPC-H join queries (Q4/Q7/Q8) are on-path: both materialize mostly-empty string columns or fill string defaults for unmatched rows. Off-path numeric queries (Q9, Q16, Q30) and the very noisy TPC-H Q17 were downgraded to not_sure. Baselines are thin here (2 base runs), so treat the largest magnitudes — especially TPC-H's x20.5 and x6.9 — as inflated relative to the true steady-state gain. clickbench🟢 7 improved · Flagged queries (11 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🟢 3 improved · Flagged queries (4 of 22)
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. Debug info
|
CI finish ledger — f0b4e2aEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
None is PR-caused: this PR changes #113571 touches exactly Fix-presence probe for the Gates: (a) 175 check-runs, 0 queued/in_progress/pending/waiting; (b) Session id: cron:our-pr-ci-monitor:20260806-050000 Edited to correct the commit hash in the heading: I had truncated it to the first 12 characters and completed the rest incorrectly. The hash now shown is this PR's actual head. Nothing else changed; every finding above was measured against that head. |
|
cc @Avogar |
|
Fixing PR for the It replaces the oracle that counted every The failure on this PR was on a build that predates that merge. Probing the test file per build (marker No action needed here beyond a rerun or a rebase onto current master. |
The only conflict was an add/add on src/Columns/tests/gtest_column_array.cpp: master added a createArray offsets-validation suite (three TESTs) in the same file this branch added its insertManyDefaults peak-allocation harness to. The two are complementary, so both are kept: nine TESTs, master's createArray helper reused, and the sanitizer-guarded throw tests left at the end of the file where the #ifndef applies to them only. Neither insertManyDefaults implementation changed upstream, so both source hunks merged without conflict.
The peak oracle was an upper bound only, so a tracker that silently recorded nothing left peak at 0 and satisfied it - including for the push_back implementation the test exists to reject. Holding the offsets costs at least their size, so a lower bound of offsets_bytes is a property of any implementation and fails only when the measurement itself is broken. Verified both directions: with the tracker attachment removed the new assertion fails at 0 vs 32000000, and with the old push_back loops restored the upper bound still fails at 50331648 vs 40000000 while the lower bound passes, so the two assertions catch different failures.
The helper only moved the allocation onto its own thread: the column was destroyed on the caller thread after join(), and CurrentMemoryTracker::free charges the current thread. Once an earlier case in unit_tests_dbms had initialized MainThreadStatus, the caller's tracker went negative by the size of the offsets while the worker-side tracker kept the positive side, measured at -33554024 bytes, which makes the binary order-dependent again. The link order that keeps this dormant today comes from a CONFIGURE_DEPENDS glob, so adding any test file can change it. The column is now created, grown, read and destroyed inside the measuring thread, and only the numbers are returned, so each allocation and its free are charged to the same thread. Caller-side drift goes from -33554024 to 408 bytes. Reported by clickhouse-gh[bot] on ClickHouse#113577.
AGENTS.md asks for literal ClickHouse class and function names to be written as inline code.
The two tests appended three offsets to an array whose capacity was already 496, so resize_fill never called reserve and the appended value was never invalidated: reading it by reference instead of by value passed both tests. They now append past the initial capacity, which moves the buffer (capacity 496 to 8176), so the read really happens in the freed block and the sanitizer builds report it. Every appended offset is asserted rather than only the first three.
The mechanism it described is in the commit that introduced it; what a caller needs is the lifetime requirement.
CI finish ledger - 0bc3f00Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Neither failure is caused by this PR. The diff is
Session id: cron:our-pr-ci-monitor:20260811-003000 |
|
Fixing PR for the hung |
One conflict, in src/Columns/tests/gtest_column_array.cpp: master and this branch each appended a test right after OffsetsConsistentWithNestedColumn. Both are kept. Master's CutPreservesSharedLowCardinalityDictionary stays in the position master gave it, so this branch's six InsertManyDefaults tests remain a pure insertion after it. Master also moved NonMonotonicOffsetsAreRejected out of the !DEBUG_OR_SANITIZER_BUILD block and turned it into a death test, because the monotonicity scan it exercises is now compiled only in debug and sanitizer builds. That part merged without conflict and master's form is unchanged here. The DataTypes includes master added landed after <thread>; moved up with the other project includes. ColumnArray.cpp and ColumnString.h merged with no conflict: master did not touch either insertManyDefaults, so this branch's pre-sizing is the only change to them.
|
|
||
| /// More than the initial capacity, so the offsets are reallocated while the appended value is read. | ||
| /// Read by reference instead of by value, that value would sit in the freed buffer. | ||
| column->insertManyDefaults(appended_past_initial_capacity); |
There was a problem hiding this comment.
These two KeepsOffsetsAfterNonEmpty* tests still do not give a deterministic regression for the "copy the last offset by value before resize_fill" requirement. If the implementation regresses to offsets.resize_fill(offsets.size() + length, offsets.back()), the reference will dangle after the reallocation here, but on a normal build the freed slot can still keep 2 / 3, so every assertion below stays green and the only signal is sanitizer instrumentation. Can we either make this an explicit sanitizer-only regression or use a helper that deterministically poisons/reuses the old buffer before std::fill consumes value?
There was a problem hiding this comment.
Confirmed on the fact; the copy stays as it is.
I applied the mutant you named (resize_fill(offsets.size() + length, offsets.back())) to both insertManyDefaults overrides:
- debug, no sanitizer: every test in this file passes, and the two arms alone are green in 6 runs out of 6.
- ASan+UBSan, same mutant:
heap-use-after-free, READ of size 8 inPODArray::resize_fill(size_t, const T &)reached fromgtest_column_array.cpp:189, on memory freed by thereserveinside that same call. Clean without the mutant.
The arm is armed, not lucky: the offsets hold one element with capacity 496, the call asks for 4097, the data pointer moves, and ASan places the read 64 bytes into the freed 4096 byte region, which is offsets[0] past PaddedPODArray's 64 byte left padding. InsertManyDefaultsGrowsOffsetsGeometrically aborts the same way for both columns; the two PreSizesOffsets arms stay clean because they start from an empty column, where back() reads empty_pod_array and nothing is ever freed. That asymmetry is what the non-empty arms are for.
On the two options. A sanitizer-only arm adds nothing: the regression is already deterministic in every build where a use-after-free is observable, and on the previous head Unit tests (asan_ubsan), (msan), (tsan) and (amd_llvm_coverage) each reported both arms OK; moving them behind #ifdef would also drop the offset and value assertions they carry in non-sanitizer builds. A poisoning helper has no seam: Allocator::realloc either calls __real_realloc or does alloc + memcpy + free, so the old bytes are intact at the moment of the free, and resize_fill runs the reserve and the std::fill back to back. The offsets type is a fixed PaddedPODArray<UInt64>, so a test cannot substitute its allocator, and making that freed slot read differently means a test-only hook in Allocator for one property that ASan already catches in four of the six arms.
No commit for this.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units1158 translation units recompiled, 8162 s compile time in total, 1158 of them have a recent master baseline. |
CI finish ledger - 79f50fbEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose
CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run Not caused by this PR, whose diff is CREATE TABLE test_1.merge_host_remote_tab_b__fuzz_4 (`number` Variant(Decimal(18, 10), Enum16('v0' = 0, 'v1' = 1), LineString))
AS remote('127.0.0.1', numbers(2)) PRIMARY KEY tuple(number)which is the Session id: cron:our-pr-ci-monitor:20260827-190000 |
95e9157
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ColumnArray::insertManyDefaultsandColumnString::insertManyDefaultsnow pre-size their offsets array instead of appending one element at a time, so appending many default values performs a single reallocation rather than walking the whole doubling chain. Appending 4 million defaults reserves 32 MiB once instead of peaking at 48 MiB.Description
Follow-up to #112897, requested in review: that PR added the
ColumnArray::insertManyDefaultsoverride but its offsets are appended with a barepush_backloop and never reserved.PODArray::push_backgrows throughreserveForNextSize->realloc(allocated_bytes() * 2), so appendingNelements takesO(log N)reallocations instead of one, andAllocator::realloccharges the new block before releasing the old one, so the last doubling is accounted twice at once: a transient peak of about 1.5x the final allocation where onereservecosts 1.0x.Both functions now use
resize_fill(offsets.size() + length, last_offset), matchingColumnVector,ColumnDecimal,ColumnFixedStringandColumnVariant.last_offsetis read by value, sinceresize_filltakes a reference and may reallocate. The growth stays geometric:reserve_exactwould leave capacity equal to size after every call, reallocating on every row of the one-default-per-row path #112897 exists to fix. Only the offsets are pre-sized; the nested column holds nothing for a default value, which is why the inheritedIColumn::insertManyDefaultswas dropped in #112897.ColumnStringhad the identical shape and is fixed here too.Measured at
length = 4000000(offsets 32,000,000 bytes), tracker peak 50,331,648 -> 33,554,432 bytes, reallocations 14 -> 1.IColumn::reserveaffects performance only and the same offsets are appended in the same order, so no result changes.The one-default-per-row path keeps its final capacity and peak, but not its growth chain:
push_backapplies the 4096-byteinitial_bytesfloor whilereserverounds to a power of two, so 400,000 single appends grow 15 times instead of 11, copying 3.75 KiB more in total (0.01 byte per row) and taking 1275 us against 998 us as a debug min of 7. Guarding the old path behindlength == 1would put a branch in every caller to recover that, so pre-sizing is unconditional.Tested by unit tests in
src/Columns/tests/gtest_column_array.cppand the existing04648_replicate_generic_no_quadratic_realloc.Workflow [PR]
Sync PR [sync-upstream/pr/113577]
Version info
26.9.1.489(included in26.9and later)