Skip to content

Use ::sort and HashMap in timeSeries*ToGrid aggregate functions - #110875

Merged
nikitamikhaylov merged 5 commits into
masterfrom
timeseries-buckets-hashmap-sort
Jul 20, 2026
Merged

nikitamikhaylov merged 5 commits into
masterfrom
timeseries-buckets-hashmap-sort

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #106724, applying the review suggestions that did not make it into the merge.

  • Replace std::sort with ::sort (pdqsort, strictly better on integer keys) in AggregateFunctionTimeseriesSamples and in the sparse path of AggregateFunctionTimeseriesBase::doInsertResultInto.
  • Replace the std::unordered_map of buckets with HashMap<UInt64, Bucket, DefaultHash<UInt64>, HashTableGrower<4>>. HashMap relocates cells with memcpy on resize, so buckets must be position independent (memmove-able): the Summary buckets are trivially copyable, and AggregateFunctionTimeseriesSamples declares is_position_independent — absl::flat_hash_map stores no pointers into itself (the address of its inline single-element storage is computed from this, the rest is on the heap); verified empirically by memcpy-relocating populated maps in both inline and heap modes. A static_assert enforces 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:

image

Changelog category (leave one):

  • Performance Improvement

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

Use pdqsort and ClickHouse HashMap instead of std::sort and std::unordered_map in the timeSeries*ToGrid aggregate functions.

Version info

  • Merged into: 26.7.1.1210 (included in 26.7 and later)

nikitamikhaylov and others added 2 commits July 17, 2026 16:10
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [23c0fe5]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
UndefinedBehaviorSanitizer: undefined behavior (STID: 1003-358c) FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR switches the timeSeries*ToGrid bucket map from UnorderedMapWithMemoryTracking to HashMap, replaces the sparse finalize-path sort with ::sort, retunes BUCKET_DENSITY_TO_ENABLE_RANGE_SCAN to 0.35, and adds a doubling grower to reduce the memory hit from the container swap. The remaining problems are both in the evidence for that new 0.35 cutoff: the current benchmark still assumes away layout differences that production states actually hit, and the new absl::flat_hash_map relocation contract still has no focused regression proving it survives HashMap growth.

Findings

⚠️ Majors

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesBase.h:449] The new 0.35 cutoff is still justified as if TrivialHash removed fill-order sensitivity, but HashMap still uses linear probing. Colliding keys near the threshold still keep whichever key reached the home slot first, so merge-built states can end up with a different probe profile and different presortedness for ::sort than the benchmarked dataset. That means use_range_scan can still flip to the slower finalize path on real merged timeSeries*ToGrid states. Suggested fix: benchmark a merge-filled dataset too, or choose the threshold from the worst case across both build paths instead of assuming TrivialHash makes them equivalent.
  • [src/AggregateFunctions/examples/timeseries_to_grid_range_scan_vs_std_sort.cpp:101] The retuning example still pre-sizes TimeSeriesBucketsMap before any inserts, so it bypasses the resize/rehash history of ordinary add-built states. HashTable::resize reinserts cells in current buffer order, so the final layout can differ even for the same key sequence; a two-key trace (1, 5) already ends with [1,5] in a pre-sized table but [5,1] after growing 2 -> 4. That makes the current benchmark unrepresentative even before merges enter the picture. Suggested fix: let the example grow the map exactly as production does, or benchmark both pre-sized and incrementally-grown states before using it to justify 0.35.
Tests
  • ⚠️ There is still no focused regression that proves AggregateFunctionTimeseriesSamples::is_position_independent survives the exact operation HashMap performs here: growing State::buckets and memcpy-relocating populated buckets. Please add a small test that forces one bucket to stay in the inline single-element absl::flat_hash_map mode, another to spill to heap, then grows the outer TimeSeriesBucketsMap and verifies merge/finalization or serialize/deserialize still produce the correct result.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 17, 2026
@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Jul 17, 2026
@nikitamikhaylov
nikitamikhaylov requested a review from vitlibar July 17, 2026 14:29
@vitlibar vitlibar self-assigned this Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

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
  • StressHouse run: 3301dbc6-e98f-4cfe-9568-e32c333d0519
  • MIRAI run: c558c326-3c81-4603-aac9-e5e59d7783da
  • PR check IDs:
    • clickbench_234634_1784395105
    • clickbench_234647_1784395105
    • clickbench_234654_1784395105
    • tpch_adapted_1_official_234660_1784395105
    • tpch_adapted_1_official_234672_1784395105
    • tpch_adapted_1_official_234684_1784395105

@vitlibar

Copy link
Copy Markdown
Member

Performance tests show a significant performance degradation:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/110875/7d0e039ac38d80e9f348ac50b6db1edc531d4fe1/performance_comparison_amd_release_master_head_2_6/report.html

This degradation was caused by changing the hash function: replacing std::unordered_map with HashMap also replaced std::hash<UInt64> (which is computed as identity) with DefaultHash<UInt64> (which is computed as intHash64 and slower). It seems we can use TrivialHash instead of DefaultHash<UInt64> to solve the performance degradation.

/// 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;

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.

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

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.

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.

@nikitamikhaylov

nikitamikhaylov commented Jul 18, 2026 •

Copy link
Copy Markdown
Member Author

Below is the reason why I'm going to close this PR. UPD: we can just change the grower.

Memory: 2.2–2.8× worse than before the container swap

I compared peak memory (10k series, single-sample buckets, identical results on both binaries) between the latest master binary (old UnorderedMapWithMemoryTracking) and this branch:

┌───────────────────────────────────────────────────┬─────────┬──────────┬────────┬──────┐
│                     workload                      │ master  │  branch  │ memory │ time │
├───────────────────────────────────────────────────┼─────────┼──────────┼────────┼──────┤
│ timeSeriesRateToGrid, dense (1000 buckets/series) │ 657 MiB │ 1564 MiB │ 2.4×   │ −35% │
├───────────────────────────────────────────────────┼─────────┼──────────┼────────┼──────┤
│ timeSeriesRateToGrid, sparse (200/1000)           │ 139 MiB │ 393 MiB  │ 2.8×   │ −22% │
├───────────────────────────────────────────────────┼─────────┼──────────┼────────┼──────┤
│ timeSeriesResampleToGridWithStaleness, dense      │ 581 MiB │ 1252 MiB │ 2.2×   │ −40% │
├───────────────────────────────────────────────────┼─────────┼──────────┼────────┼──────┤
│ timeSeriesResampleToGridWithStaleness, sparse     │ 123 MiB │ 315 MiB  │ 2.6×   │ −6%  │
└───────────────────────────────────────────────────┴─────────┴──────────┴────────┴──────┘

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.

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.

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.

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

Btw

Yes, the HashMap switch makes sense — changing only the sort would give up essentially the entire speedup. I built and measured the third variant (old UnorderedMapWithMemoryTracking storage, ::sort kept everywhere) to isolate the two changes:

┌─────────────────────────────────────────────────────┬─────────────────────┬──────────────────────────────┐
│                       variant                       │ memory (dense rate) │ time vs master, same session │
├─────────────────────────────────────────────────────┼─────────────────────┼──────────────────────────────┤
│ master (old map + std::sort)                        │ 657 MiB             │ baseline                     │
├─────────────────────────────────────────────────────┼─────────────────────┼──────────────────────────────┤
│ old map + ::sort (sort-only)                        │ 657 MiB (identical) │ ±6% — within noise           │
├─────────────────────────────────────────────────────┼─────────────────────┼──────────────────────────────┤
│ HashMap + ::sort + doubling grower (current branch) │ 783 MiB (+19%)      │ −15% to −33%                 │
└─────────────────────────────────────────────────────┴─────────────────────┴──────────────────────────────┘

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai investigate the failures and provide fixes as separate PRs.

@groeneai

Copy link
Copy Markdown
Collaborator

@nikitamikhaylov Both are pre-existing chronic trunk failures, not caused by this PR's ::sort/HashMap change, and both are already fixed on master by merged PRs. No separate fix PR is needed here: a rebase / merge from master picks both up (this branch's head 23c0fe5 is behind master and predates both merges).

  • Stress test (amd_asan_ubsan) UBSan (STID 1003-358c), -nan is outside the range of representable values of type 'long' at contrib/sz3/include/SZ3/quantizer/LinearQuantizer.hpp:45: a NaN/Inf float-to-int64 cast in the SZ3 codec quantizer. Fixed by Fix undefined float-to-int cast on NaN in the SZ3 codec quantizer #110762 (merged 2026-07-18 16:22Z). master is clean of this UBSan after the merge. report
  • Stress test (amd_debug / amd_tsan) signal 8 (STID 4141-5867 / 4141-584d) in chrono::duration_cast: a zero-length quota interval divides by zero in EnabledQuota::Interval::getEndOfInterval. Chronic across trunk (129 hits / 81 PRs + 5 on master since 07-16). Fixed by Disable zero-length interval quotas #110846 (merged 2026-07-18 10:07Z); 0 master hits after that merge. report

The Stateless tests (amd_debug, parallel) "Too many test failures" on the earlier 7b8f023 was that run's own job-level abort (71 tests failing together, no common cause), not a real regression, and it is gone on the current head.

@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

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

Full report · Diff report

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai help investigate the test failures.

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 20, 2026
Merged via the queue into master with commit 3782a13 Jul 20, 2026
177 of 179 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the timeseries-buckets-hashmap-sort branch July 20, 2026 12:30
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

@nikitamikhaylov On the merged head 23c0fe5 there is exactly one red check, and it is a pre-existing contrib bug unrelated to the aggregate-function diff:

The two failures on earlier shas were also pre-existing trunk bugs, already fixed on master:

  • signal-8 SIGFPE in Stress test (amd_debug/amd_tsan) (STID 4141-5867/584d): zero-length-interval quota div-by-zero, fixed by Disable zero-length interval quotas #110846 (merged 07-18 10:07Z; 04603_quota_zero_interval).
  • Stateless tests (amd_debug, parallel) "Too many test failures" (~65 tests, sha 7b8f023): that run's own job abort, gone on the current head.

Both fixes are now in master ancestry (behind_by:0 vs the merge commit), so no CI failure traces to this PR's diff. Nothing actionable remains here.

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());

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.

@nikitamikhaylov Just quickly asking if we have an internal implementation of sort faster than the C++ standard library one

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ts-hashmap-sort

Use `::sort` and `HashMap` in `timeSeries*ToGrid` aggregate functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... 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