Skip to content

Pre-size the offsets in ColumnArray::insertManyDefaults and ColumnString::insertManyDefaults - #113577

Merged
Avogar merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/reserve-offsets-insert-many-defaults
Sep 1, 2026
Merged

Avogar merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/reserve-offsets-insert-many-defaults

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 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):

ColumnArray::insertManyDefaults and ColumnString::insertManyDefaults now 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::insertManyDefaults override but 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 N elements takes O(log N) reallocations instead of one, and Allocator::realloc charges 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 one reserve costs 1.0x.

Both functions now use resize_fill(offsets.size() + length, last_offset), matching ColumnVector, ColumnDecimal, ColumnFixedString and ColumnVariant. last_offset is read by value, since resize_fill takes a reference and may reallocate. The growth stays geometric: reserve_exact would 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 inherited IColumn::insertManyDefaults was dropped in #112897. ColumnString had 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::reserve affects 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_back applies the 4096-byte initial_bytes floor while reserve rounds 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 behind length == 1 would 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.cpp and the existing 04648_replicate_generic_no_quadratic_realloc.


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

Version info

  • Merged into: 26.9.1.489 (included in 26.9 and later)

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.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Three review rounds, two independent channels each (a cold read of the resulting code, then a
second-model pass). This round both channels came back clean on the code; the findings were in my own
validation write-up and are corrected above.

# Finding Verdict
💡 The validation table said length of "0, 1, 3, 400000 and 4000000" was exercised. Censused every call in the new test file: the lengths are 1, 3 and 4,000,000. 400,000 is the repeat count of the one-default-per-row arms, not a length, and no arm passes 0. ❌ Corrected. length = 0 is a no-op in both versions (resize_fill returns early when n <= old_size, PODArray.h:433-439).
💡 The same table described 1.5729x and 1.0486x as ratios "to the final allocation". They are ratios to offsets_bytes (32,000,000); the final allocation is the same 33,554,432 in both arms, which is precisely why the assertion reads the peak rather than the capacity. ❌ Corrected.
⚠️ Earlier round: src/Columns/ColumnString.h carried one comment line twice, verbatim. ✅ Fixed.
⚠️ Earlier round: the test helper reset the thread memory tracker while the measured column was still alive, leaving that tracker about 32 MiB negative per arm; resetCounters also clears the hard, soft and profiler limits. ✅ Fixed by dropping both resetCounters calls. The peak is read from a scoped child tracker, so nothing is lost.
⚠️ Earlier round: the helper called MainThreadStatus::getInstance(), which sets current_thread permanently. src/Columns/tests/gtest_column_tuple.cpp later constructs a stack ThreadStatus on the same thread, whose constructor opens chassert(!current_thread), so adding this file made an existing assertion fire and abort unit_tests_dbms in the default (unshuffled, unfiltered) run. The assertion is a pre-existing fragility; this PR would have been the first change to make it fire. ✅ Fixed. The measured window now runs on a dedicated thread owning a local ThreadStatus, matching gtest_thread_group_switcher.cpp:26-31 and gtest_thread_pool_callback_runner_shutdown.cpp:127-132, whose comments name the same hazard. current_thread is thread_local, so nothing is left behind.
⚠️ Second-model claim that a reserve_exact variant would pass all the new tests. ❌ Disagreed, with evidence. For PaddedPODArray<UInt64>, reserve_exact(n) leaves capacity() == n exactly, so after 400,000 calls of insertManyDefaults(1) the geometric arm's EXPECT_GT(capacity(), 400000) is false and the arm fails. That variant was also built twice and reddened its own arm each time.

Independently re-derived rather than taken from the implementation notes: the peak and reallocation
figures (a PaddedPODArray<UInt64> model built from PODArray.h and Allocator.cpp reproduces
50,331,648 -> 33,554,432 and 14 -> 1 exactly); the census of every insertManyDefaults override in
src/Columns/ by balanced-body parse, including that ColumnReplicated pre-sizes one level down in
ColumnIndex::insertManyIndexes and ColumnSparse has no array to grow; the by-value read of
back() against the reallocation hazard documented at ColumnArray.cpp:412-413; that the sole
capacity consumer feeding a decision is a reserve hint at ColumnObject.cpp:466, where a smaller
value cannot be incorrect; and that each of the four built mutants is caught by exactly one arm, with
the size and nested-size controls asserted before the peak expectation so a low peak cannot pass
vacuously.

Session id: cron:clickhouse-review-slot-10:20260805-205400

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and not timing based. taskset -c 0-7 ./build/src/unit_tests_dbms --gtest_filter='ColumnArray.InsertManyDefaults*:ColumnString.InsertManyDefaults*' reports a tracker peak of 50,331,648 bytes on the unfixed binary and 33,554,432 on the fixed one, every run. Both are exact powers of two chosen by PODArray, so there is no timing or allocator dependence.
b Root cause explained? A known-count bulk append grown one element at a time. PODArray::push_back grows via reserveForNextSize -> realloc(allocated_bytes() * 2) (PODArray.h:186-197), so appending N offsets performs O(log N) reallocations instead of one, and Allocator::realloc calls CurrentMemoryTracker::alloc(new) at Allocator.cpp:180 before free(old) at :187, so the last doubling is charged twice at once.
c Fix matches root cause? Pre-sizes the array that actually grows, with resize_fill, which is what ColumnVector.h:95, ColumnDecimal.h:74, ColumnFixedString.h:122 and ColumnVariant.cpp:743 already do. No defensive check, no widened bound, no disabled randomization. The nested column is deliberately still not reserved, which is the point of the insertManyDefaults override added in #112897.
d Test intent preserved / new tests added? 04648_replicate_generic_no_quadratic_realloc is unchanged and passes 10 randomized runs. Six new arms added in src/Columns/tests/gtest_column_array.cpp: a peak assertion, a content assertion after a non-empty prefix, and a geometric-growth assertion, for each of the two columns. Nothing weakened.
e Both directions demonstrated? Yes, on two built binaries. At length = 4000000 the offsets hold 32,000,000 bytes of elements: unfixed peak 50,331,648 (1.5729x that) vs fixed 33,554,432 (1.0486x); reallocations 14 vs 1. The final allocation is the same 33,554,432 in both arms, which is why the assertion reads the peak and not the capacity. Predicted independently from PODArray.h/Allocator.cpp semantics before either binary existed, and the measured values matched the prediction exactly.
f Fix is general across code paths? Yes, established by census rather than by inspection: every insertManyDefaults override in src/Columns/ was parsed and its balanced body checked for a push_back loop with no pre-sizing. ColumnArray and ColumnString were the only two with that shape, and after this change no override in the tree has it. The rest already pre-size (ColumnVector, ColumnDecimal, ColumnFixedString, ColumnVariant via resize_fill; ColumnSparse via _size += length; ColumnReplicated via insertManyIndexes) or delegate to a sub-column (ColumnObject, ColumnDynamic). Columns with no override inherit IColumn::insertManyDefaults, which does reserve.
g Fix generalizes across inputs (params/datatypes/wrappers)? length of 1, 3 and 4000000 exercised, the last two on an empty column and the length = 3 cases on a non-empty prefix; the length = 1 cases repeat the call 400000 times, which is the one-default-per-row shape. back() on an empty array is covered by PaddedPODArray's zero-initialized -1th element, and length = 0 is a no-op in both versions (resize_fill returns early when n <= old_size). The type-wrapper matrix comes from the existing 04648, which drives this function through nested Array, Map, Tuple, Nullable, Dynamic, Variant and LowCardinality payloads.
h Backward compatible? (maintainer-approved exception only) Nothing to do. The diff is two source files, +8/-9: no setting, no serialization format, no experimental gate, zero lines in SettingsChangesHistory.cpp, zero serialization files touched. IColumn::reserve is documented at IColumn.h:623-625 as affecting "performance only (not correctness)".
i Invariants and contracts preserved? Both versions append length copies of getOffsets().back(). resize_fill(n, value) fills [t_end(), t_end() + n - old_size) and sets c_end to n elements, which is the same bytes the loop wrote in the same positions, and neither version touches data/chars. So size(), getOffsets()[i], sizeAt, offsetAt and the nested data are unchanged. The observables that do change are capacity() and allocatedBytes(), both smaller or equal; the only in-tree consumer that feeds a decision is ColumnObject.cpp:466 reserve(shared_data->capacity()), a performance hint where a smaller value cannot be incorrect, and no operator==, hash or cache-key site reads either.

Session id: cron:clickhouse-review-slot-10:20260805-205400

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @azat, could you review this? Both insertManyDefaults overrides appended offsets one at a time, so a bulk call walked the whole doubling chain and Allocator::realloc charged the new block before releasing the old one, peaking at about 1.5x the final allocation; they now pre-size the offsets with resize_fill, geometrically so the one-default-per-row path stays amortized.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79f50fb]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: 'Inconsistent AST formatting: the query: (STID: 1941-26fa) FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR replaces the per-element push_back loops in ColumnArray::insertManyDefaults and ColumnString::insertManyDefaults with a single resize_fill, which does remove the avoidable reallocation chain and the production code itself looks correct. I found one remaining concern in the new regression coverage: the non-empty-prefix tests still do not deterministically prove the required by-value copy when they run without sanitizer instrumentation.

PR Metadata

Changelog category is correct: this is a real Performance Improvement. A changelog entry is required, but the current text is still implementation-centric and does not explain the user-visible impact as clearly as it could. Suggested replacement: Improves peak memory usage when ClickHouse appends large numbers of default values to Array and String columns by avoiding repeated offset reallocations.

Findings
  • ⚠️ [src/Columns/tests/gtest_column_array.cpp:189] InsertManyDefaultsKeepsOffsetsAfterNonEmptyArrays (and the analogous string test below) still only proves the dangling-reference bug when sanitizer instrumentation traps it. A regression to resize_fill(..., offsets.back()) can keep reading the old 2 / 3 out of freed memory on normal builds, so every value assertion stays green and the by-value contract remains unproven on the default unit_tests_dbms path. Suggested fix: either make this an explicit sanitizer-only regression, or drive the same case through a helper that deterministically poisons or reuses the old offsets buffer before std::fill consumes the captured value.
Final Verdict

Needs one more test-strengthening change before I would treat the regression coverage as sufficient.

LLVM Coverage Report

Measured on commit 79f50fb.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 10 query(s) improved out of 35 analysed

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 · ⚠️ 4 inconclusive

Flagged queries (11 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 4 improvement 277 190 -31.4% <0.0001 cpu: Large, consistent drop, but AVG(UserID) is pure numeric and doesn't exercise the changed String/Array default-insertion path; the thin 2-run baseline likely drives it. History is noisy.
🟢 5 improvement 368 250 -31.9% <0.0001 cpu: COUNT(DISTINCT UserID) is numeric and doesn't use the changed String/Array default path; the large delta reflects the thin 2-run baseline more than this change.
🟢 13 improvement 422 342 -18.9% <0.0001 memory: GROUP BY SearchPhrase materializes a mostly-empty (sparse) String column, so cheaper bulk default insertion plausibly explains this improvement.
🟢 15 improvement 223 164 -26.5% <0.0001 memory: Keys on SearchPhrase, a mostly-empty String column whose sparse materialization calls the improved default-insertion path; the improvement is on-path and consistent.
🟢 17 improvement 541 241 ×2.2 faster <0.0001 memory: UserID+SearchPhrase grouping materializes the mostly-empty SearchPhrase String column; cheaper bulk default insertion plausibly drives this large improvement.
🟢 18 improvement 1226 1068 -12.9% <0.0001 memory: Also groups on the mostly-empty SearchPhrase String column, so lower-cost default materialization is a plausible cause of this improvement.
🟢 31 improvement 362 310 -14.4% <0.0001 memory: Filters on SearchPhrase<>'', reading the sparse mostly-empty String column whose materialization uses the improved default path; on-path improvement.
⚠️ 9 not_sure 340 381 +12.1% <0.0001 cpu: Numeric GROUP BY on RegionID doesn't touch the String/Array default-insertion change; this +12% shift is off-path run-to-run variance on a thin baseline.
⚠️ 16 not_sure 760 600 -21.1% <0.0001 cpu: GROUP BY UserID is numeric and doesn't exercise the String/Array default path; this improvement is off-path variance on a thin 2-run baseline.
⚠️ 30 not_sure 266 235 -11.7% <0.0001 cpu: This is 90 numeric SUMs of ResolutionWidth; no String/Array defaults are inserted, so the improvement is off-path variance on a thin baseline.
⚠️ 32 not_sure 1287 1383 +7.5% 0.0003 memory: Borderline with mixed signals and noisy measurements; it reads the sparse SearchPhrase column, so any real effect would come from the default-insertion change.

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 · ⚠️ 1 inconclusive

Flagged queries (4 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 4 improvement 1044 51 ×20.5 faster <0.0001 memory: Semi-join with string grouping fills default values in bulk; the change lowers that cost, though the 2-run baseline inflates the reported x20.5 above the true steady-state gain.
🟢 7 improvement 554 80 ×6.9 faster <0.0001 memory: Multi-table join fills string defaults for unmatched rows; cheaper bulk default insertion is on-path, but the thin baseline exaggerates the x6.9 figure.
🟢 8 improvement 163 88 -46.0% <0.0001 memory: Join query filling string defaults; the improvement is on-path, though the 2-run baseline likely overstates the -46% magnitude.
⚠️ 17 not_sure 65 104 +60.0% <0.0001 Source measurements are extremely noisy on this fast query and the delta is only ~39 ms; the +60% regression is within run-to-run variance, not a change effect.

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
  • StressHouse run: fd58c15c-bc74-4803-bf32-ae3c6000e71f
  • MIRAI run: ab9310e2-58f7-4f7c-a0c5-ccb4a7a46619
  • PR check IDs:
    • clickbench_59187_1787862780
    • clickbench_59316_1787862825
    • clickbench_59485_1787862930
    • tpch_adapted_1_official_59642_1787863040
    • tpch_adapted_1_official_59715_1787863043
    • tpch_adapted_1_official_59874_1787863059

@groeneai

groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f0b4e2a

Every failure below has an owner: a fixing PR (ours 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
Integration tests (amd_msan, 4/8) / test_tcp_handler_connection_limits::test_query_count_limit the test's oracle reads a process-wide query counter that other queries on the same server also advance, so it fails when anything else runs concurrently. Breadth 30 d: 6 master fails / 5206 master ok / 60 PR fails across 57 distinct PRs. a fix task is created (investigating at full effort — fixing PR link to follow on this PR)
Integration tests (amd_msan, 3/8) / test_keeper_dynamic_log_level::test_adjust_log_level flaky Keeper log-level test. Breadth 30 d: 2 master fails / 5205 master ok / 11 PR fails across 11 distinct PRs. #113571 (external, open)
Build (arm_release) / Post Hooks infra: build_profile_hook.py fails closed when the build-profile telemetry INSERT into the shared CI logs cluster is rejected. Not gating: the Build (arm_release) check-run itself is green. #113409 (external, merged 2026-08-06T00:05:00Z) — arrives with the next master merge

None is PR-caused: this PR changes ColumnArray / ColumnString insertManyDefaults offset
pre-sizing, and neither the TCP handler's connection limits, Keeper's dynamic log level, nor the CI
build-profile hook is reachable from that diff. The cloud performance report on this head also reads
no_change across 37 queries.

#113571 touches exactly tests/integration/test_keeper_dynamic_log_level/test.py, which is the
failing test file, so the causal link is direct rather than same-area coincidence.

Fix-presence probe for the Post Hooks owner, by content rather than commit distance: this head's
ci/jobs/scripts/log_cluster.py is 11916 bytes with no data.seek(0) and one retries= site,
against 12698 bytes with data.seek(0) and four on current master (positive control master,
negative control the merge parent). Master's own Post Hooks reds fell from 4 per hour at 01:00Z to
0 by 05:00Z today, so the fix works and the next master merge picks it up.

Gates: (a) 175 check-runs, 0 queued/in_progress/pending/waiting; (b) Finish Workflow and
Config Workflow both success; (c) last completion 04:57:24Z, >20 min buffer; (d) every failure
above has an owner.

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.

@PedroTadim

Copy link
Copy Markdown
Member

cc @Avogar

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_tcp_handler_connection_limits/test.py::test_query_count_limit row on my CI finish ledger: #113530 (merged 2026-08-06T00:24:35Z).

It replaces the oracle that counted every Done processing connection. line with one that counts only connections closed because a limit was reached (Closing connection due to limits: queries=), so the startup readiness probe and a reconnecting client no longer pollute the count.

The failure on this PR was on a build that predates that merge. Probing the test file per build (marker get_limit_closed_count, with a control string present in both the pre- and post-fix versions scored on every probe): of 28 recent msan runs, the 14 whose build contains the fix are 14 OK / 0 FAIL, and every failure sits on a build without it. On msan flavours the rate went from 63 FAIL / 197 OK before the merge to 0 FAIL / 219 OK after it.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0bc3f00

Every failure below has an owner: a fixing PR (ours 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 (arm_asan_ubsan, s3) / Sanitizer (STID: 1367-26c6) LeakSanitizer, indirect-only leak; per-block census puts it in the materialized-CTE self-cycle family (50 PRs + 4 master rows in 2 days) #113397 (external, open)
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found cancelled DROP TABLE prometheus never returns from waitTableFinallyDropped; DROP DATABASE ... SYNC victims convoy behind the DDL guard a fix task is moved to pending (investigating at full effort - fixing PR link to follow here)
Stress test (arm_release) / Hung check failed, possible deadlock found same root: cancelled TimeSeries DROP stuck 3464s, victims at 3300s/2918s in getDDLGuard a fix task is moved to pending (investigating at full effort - fixing PR link to follow here)
Stress test (arm_tsan) / Hung check failed, possible deadlock found same root: cancelled TimeSeries DROP stuck 2952s, victims at 2840s/2389s in getDDLGuard a fix task is moved to pending (investigating at full effort - fixing PR link to follow here)

Neither failure is caused by this PR. The diff is src/Columns/ColumnArray.cpp,
src/Columns/ColumnString.h and src/Columns/tests/gtest_column_array.cpp; the leak stack is
entirely in analyzer constant folding (createColumnConst / ConstantNode) and the hung-check
roots are StorageTimeSeries drop teardown. Both signatures fire across dozens of unrelated PRs
and on master in the same window.

Build (arm_release) / Post Hooks is not listed: the check itself concluded SUCCESS and the row
is build-profile telemetry (LogCluster query failed with code 500), not a test failure.

Session id: cron:our-pr-ci-monitor:20260811-003000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the hung DROP TABLE of a TimeSeries table (waitTableFinallyDropped): #114302 (external, open).

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

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.

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 in PODArray::resize_fill(size_t, const T &) reached from gtest_column_array.cpp:189, on memory freed by the reserve inside 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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79f50fb3a with master b8cd25afc (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
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.27 MiB -3.06 MiB (-0.43%)

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 units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79f50fb

Every failure below has an owner: a fixing PR (ours 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_debug) / STID 1941-26fa, Inconsistent AST formatting on CREATE TABLE ... AS remote(...) PRIMARY KEY tuple(number) trunk defect, not caused by this PR #116645 (ours, open)

CI is fully finished at this head: 175 unique check runs, 0 incomplete, one parent workflow run
(33077600375), and Config Workflow, Style check and Finish Workflow all success. The praktika
report has 177 nodes, 0 DROPPED. CIDB returns 309,044 rows at this commit, of which exactly the one
failure above is ownable, so the classification is a measurement and not an empty read.

Not caused by this PR, whose diff is ColumnArray.cpp, ColumnString.h and a gtest, with no parser
or formatter code. The failing statement 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 CREATE TABLE ... AS <table function> round-trip class #116645 fixes; that PR names this
exact STID in its description. Over 30 days the signature measures 152 rows across 109 distinct PRs
with 3 true-master hits, and a fabricated-phrase control returns 0, so it is a wide trunk defect
rather than anything specific to this branch.

Session id: cron:our-pr-ci-monitor:20260827-190000

@Avogar Avogar self-assigned this Sep 1, 2026
@Avogar
Avogar added this pull request to the merge queue Sep 1, 2026
Merged via the queue into ClickHouse:master with commit 95e9157 Sep 1, 2026
178 of 180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

5 participants