Repository navigation
Use ::sort and HashMap in timeSeries*ToGrid aggregate functions - #110875
Conversation
Replace `std::sort` with `::sort` (pdqsort, strictly better on integer keys) in `AggregateFunctionTimeseriesSamples` and `AggregateFunctionTimeseriesBase`. Replace the `std::unordered_map` of buckets with `HashMap<UInt64, Bucket, DefaultHash<UInt64>, HashTableGrower<4>>`. `HashMap` relocates cells with `memcpy`, so buckets must be position independent: the trivially copyable `Summary` buckets qualify, and `AggregateFunctionTimeseriesSamples` declares `is_position_independent` (`absl::flat_hash_map` stores no pointers into itself; verified empirically by memcpy-relocating populated maps in both inline and heap modes). Any other bucket type falls back to `std::unordered_map` at compile time. PR: #106724 Co-Authored-By: Claude Fable 5 <[email protected]>
All existing `Bucket` types are position independent, so the fallback was dead code. A `static_assert` now enforces the property instead: a future non-memmove-able bucket type will fail the build with a clear message rather than silently degrade to a slower map. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [23c0fe5] Summary: ❌
AI ReviewSummaryThis PR switches the Findings
Tests
Final Verdict
|
|
📊 Cloud Performance Report ✅ AI verdict: This PR reworks the timeSeries*ToGrid aggregate functions' bucket storage (swapping the node-based map for an open-addressing HashMap and retuning the range-scan density threshold to 0.35). ClickBench Q4 and Q15 execute no time-series functions, so the -14.1% and -12.7% shifts flagged on them cannot come from this change; CPU time is flat on both, marking them as run-to-run timing variance rather than a real effect. Both were correctly kept as no-change within master's current variance band. No genuine regressions or improvements are attributable to this PR. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Performance tests show a significant performance degradation: This degradation was caused by changing the hash function: replacing |
| /// single-element storage (small object optimization) is computed from `this`, the rest is on the heap. | ||
| /// No standard trait expresses this (weaker than `std::is_trivially_copyable`) property, hence the | ||
| /// explicit declaration. | ||
| static constexpr bool is_position_independent = true; |
There was a problem hiding this comment.
I don't see a focused regression that proves this opt-in survives the exact operation HashMap performs here: growing State::buckets and memcpy-relocating populated buckets. The existing query coverage exercises the aggregate functions, but it does not make the inline single-element and heap-backed absl::flat_hash_map states a checked invariant. If Abseil changes that layout later, every outer-table growth here becomes silent UB.
Please add a targeted test that forces State::buckets to grow while one bucket stays in the inline mode and another spills to heap, then verifies merges/finalization or serialization still produce the right result.
The timeseries_to_grid_range_scan_vs_std_sort example still benchmarked the old UnorderedMapWithMemoryTracking + std::sort pair. Update it to the production container/sort pair (HashMap<UInt64, Bucket, TrivialHash, HashTableGrower<4>> + ::sort) and derive the threshold from the new numbers: the range scan wins at density 0.35 by ~6-8% and loses at 0.30 by ~9% (stable over three runs), so the threshold moves from 0.4 to 0.35. With TrivialHash open addressing a cell's position is determined by the key rather than the insertion order, so the old layout caveat (in index order vs scattered after a merge) no longer applies. #110875 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
| static constexpr double BUCKET_DENSITY_TO_ENABLE_RANGE_SCAN = 0.4; | ||
| /// collect-and-sort wins. The `timeseries_to_grid_range_scan_vs_std_sort` example measures the two strategies | ||
| /// over the production bucket map (`HashMap` with `TrivialHash`): the range scan still wins at density 0.35 | ||
| /// (by ~6-8%) and loses at 0.30 (~9%), so the threshold is 0.35. With `TrivialHash` open addressing a cell's |
There was a problem hiding this comment.
The new 0.35 cutoff is still being justified as if TrivialHash made the bucket layout independent of fill order, but HashMap still uses linear probing. Around the new threshold that assumption already breaks: reserve(BASE_GRID) gives a 16384-slot table, while density 0.35 draws keys from a ~22857-wide range, so keys such as 1 and 16385 still collide. Whichever one is inserted first keeps the home slot, which means both the probe profile of the range-scan path and the initial order fed into ::sort still depend on how the map was populated.
That matters here because merged aggregate states do not populate buckets in the example's bulk-build order; they insert in source-table iteration order. So the retuned benchmark can still under-tune BUCKET_DENSITY_TO_ENABLE_RANGE_SCAN for merge-heavy timeSeries*ToGrid workloads. Please benchmark a merge-filled dataset as well, or otherwise choose a threshold that covers both fill patterns instead of assuming TrivialHash removes the old layout caveat.
|
Below is the reason why I'm going to close this PR. UPD: we can just change the grower. |
The stock HashTableGrower quadruples the buffer below max_size_degree, leaving the bucket map at a load factor as low as ~0.125; with the whole Bucket stored in every cell this made timeSeries*ToGrid aggregation states take 2.2-2.8x the memory of the previous node-based map (peak memory of a 10k-series query with 1000 populated buckets per series: 657 MiB before the HashMap switch, 1564 MiB after). A grower that doubles instead keeps the same worst-case load factor (0.5) with at most half the slots, and brings the same query to 783 MiB (dense resample: 581 -> 627 MiB) with no measurable speed difference. Also hoist the map type into a shared TimeSeriesBucketsMap alias so the timeseries_to_grid_range_scan_vs_std_sort example always benchmarks the production container; the measured crossover is unchanged (0.35), since the example's 8000 populated buckets land in a 16384-slot table under both growth policies. #110875 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
| bucket.add(static_cast<UInt32>(static_cast<Int64>(k) * STEP), static_cast<Float64>((k * 7 + series * 3) % 101)); | ||
| buckets.emplace(k, std::move(bucket)); | ||
| const size_t k = buckets.has(candidate) ? i : candidate; | ||
| /// Insert as production does: `operator[]` default-constructs the bucket, then samples are added. |
There was a problem hiding this comment.
This still is not the production fill path. buildDataset pre-sizes the whole TimeSeriesBucketsMap before any inserts, so the benchmark inserts directly into a 16384-slot table. Real State::buckets start at 16 slots and grow through repeated resize() calls, and HashTable::resize reinserts cells in current buffer order. With linear probing that changes the final layout even for the same key sequence: for example, keys 1 and 5 land as [1, 5] if you insert them into a size-4 table directly, but as [5, 1] if you insert into size 2 and then grow to 4.
Because both the range-scan probe profile and the presortedness fed into ::sort depend on that final layout, the example still is not measuring the finalize path used by ordinary add-built states. Please either let the example grow exactly as production does, or benchmark both pre-sized and incrementally-grown states before using it to justify BUCKET_DENSITY_TO_ENABLE_RANGE_SCAN = 0.35.
|
Btw |
|
@groeneai investigate the failures and provide fixes as separate PRs. |
|
@nikitamikhaylov Both are pre-existing chronic trunk failures, not caused by this PR's
The |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/30 (100.00%) · Uncovered code |
|
@groeneai help investigate the test failures. |
|
@nikitamikhaylov On the merged head
The two failures on earlier shas were also pre-existing trunk bugs, already fixed on master:
Both fixes are now in master ancestry ( |
| for (const auto & [timestamp, value] : buffer) | ||
| temp_buffer.emplace_back(timestamp, value); | ||
| std::sort(temp_buffer.begin(), temp_buffer.end()); | ||
| ::sort(temp_buffer.begin(), temp_buffer.end()); |
There was a problem hiding this comment.
@nikitamikhaylov Just quickly asking if we have an internal implementation of sort faster than the C++ standard library one
The timeseries_to_grid_range_scan_vs_std_sort example still benchmarked the old UnorderedMapWithMemoryTracking + std::sort pair. Update it to the production container/sort pair (HashMap<UInt64, Bucket, TrivialHash, HashTableGrower<4>> + ::sort) and derive the threshold from the new numbers: the range scan wins at density 0.35 by ~6-8% and loses at 0.30 by ~9% (stable over three runs), so the threshold moves from 0.4 to 0.35. With TrivialHash open addressing a cell's position is determined by the key rather than the insertion order, so the old layout caveat (in index order vs scattered after a merge) no longer applies. ClickHouse#110875 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
The stock HashTableGrower quadruples the buffer below max_size_degree, leaving the bucket map at a load factor as low as ~0.125; with the whole Bucket stored in every cell this made timeSeries*ToGrid aggregation states take 2.2-2.8x the memory of the previous node-based map (peak memory of a 10k-series query with 1000 populated buckets per series: 657 MiB before the HashMap switch, 1564 MiB after). A grower that doubles instead keeps the same worst-case load factor (0.5) with at most half the slots, and brings the same query to 783 MiB (dense resample: 581 -> 627 MiB) with no measurable speed difference. Also hoist the map type into a shared TimeSeriesBucketsMap alias so the timeseries_to_grid_range_scan_vs_std_sort example always benchmarks the production container; the measured crossover is unchanged (0.35), since the example's 8000 populated buckets land in a 16384-slot table under both growth policies. ClickHouse#110875 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
…ts-hashmap-sort Use `::sort` and `HashMap` in `timeSeries*ToGrid` aggregate functions
Follow-up to #106724, applying the review suggestions that did not make it into the merge.
std::sortwith::sort(pdqsort, strictly better on integer keys) inAggregateFunctionTimeseriesSamplesand in the sparse path ofAggregateFunctionTimeseriesBase::doInsertResultInto.std::unordered_mapof buckets withHashMap<UInt64, Bucket, DefaultHash<UInt64>, HashTableGrower<4>>.HashMaprelocates cells withmemcpyon resize, so buckets must be position independent (memmove-able): theSummarybuckets are trivially copyable, andAggregateFunctionTimeseriesSamplesdeclaresis_position_independent—absl::flat_hash_mapstores no pointers into itself (the address of its inline single-element storage is computed fromthis, the rest is on the heap); verified empirically bymemcpy-relocating populated maps in both inline and heap modes. Astatic_assertenforces the property for any future bucket type.The serialized aggregate-state format is unchanged (same count-prefixed index/bucket pairs; entry order is not significant for deserialization).
Related: #106724
Huge speedup observed:
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Use
pdqsortand ClickHouseHashMapinstead ofstd::sortandstd::unordered_mapin thetimeSeries*ToGridaggregate functions.Version info
26.7.1.1210(included in26.7and later)