Repository navigation
Optimize and simplify timeSeries*ToGrid() aggregation functions - #106724
nikitamikhaylov merged 7 commits into
Conversation
|
Workflow [PR], commit [6236e7d] Summary: ✅
AI ReviewSummaryThis PR rewrites the PR Metadata
Findings
Tests
Final Verdict
|
There was a problem hiding this comment.
Pull request overview
This PR refactors the timeSeries*ToGrid() aggregate-function family to use a unified base implementation that aligns internal buckets to both the grid step and the window, and moves per-function result computation into a finalizeAggregation() hook with per-bucket AggregationData.
Changes:
- Reworked
AggregateFunctionTimeseriesBasebucketing/indexing to account forwindowalignment (includingwindow % stepsplit buckets) and centralized result materialization over the grid. - Introduced
AggregateFunctionTimeseriesSamplesas shared per-bucket sample storage with reusable (sorted/unsorted) aggregation policies. - Refactored multiple
timeSeries*ToGridimplementations (sparse resample, rate/delta, instant rate/delta, changes/resets, linear regression) to use the new base aggregation model.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesBase.h |
New grid/bucket sizing and bucket-index mapping aligned to step+window; centralized result building via per-bucket aggregation and finalizeAggregation(). |
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesSamples.h |
New shared per-bucket sample storage with Aggregator and SortedAggregator policies. |
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesToGridSparse.h |
Switched sparse resample to AggregationData + finalizeAggregation() and “direct-merge” bucket policy. |
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesLinearRegression.h |
Refactored linear regression to aggregate sums in AggregationData and compute results in finalizeAggregation(). |
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesInstantValue.h |
Refactored instant rate/delta to AggregationData + finalizeAggregation() and “direct-merge” bucket policy. |
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesExtrapolatedValue.h |
Refactored rate/delta to sorted per-bucket aggregation + per-window finalize. |
src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesChanges.h |
Refactored changes/resets to sorted per-bucket aggregation + per-window finalize. |
045e444 to
7984d74
Compare
7984d74 to
9470462
Compare
483735c to
bd09a06
Compare
|
@davenger Can you please take a look? |
| , window_remainder(windowRemainder(step, window)) | ||
| , buckets_per_step(bucketsPerStep(window_remainder)) | ||
| , buckets_per_window(bucketsPerWindow(step, window, window_remainder)) | ||
| , buckets_per_first_window(bucketsPerFirstWindow(start_timestamp_, step, window_remainder, buckets_per_step, buckets_per_window)) |
There was a problem hiding this comment.
The first main point of this PR is that buckets are allocated now not only on step margin but also on window margin, so for example if window = 1.5 steps then buckets are allocated like this:
start_time - 1.5 * step
start_time - step
start_time - 0.5 * step
start_time
start_time + 0.5 * step
start_time + step
start_time + 1.5 * step
start_time + 2 * step
start_time + 2.5 * step
start_time + 3 * step
start_time + 3.5 * step
start_time + 4 * step
...
end_time
The idea is to make any window to be always an integer number of buckets, so we can use per-buckets aggregations for many timeseries to-grid aggregation functions.
There was a problem hiding this comment.
The idea is to make any window to be always an integer number of buckets
I'm worrying the number of buckets will grow too much. The example window = 1.5 steps is trivial, but what if window = 1.9 steps? Then we need to allocate the 19 buckets per window if I understand correctly. What if then window = 1.999999999999999999 steps due to rounding? Then looks like we have a disaster.
There was a problem hiding this comment.
If window = 1.9 step, then buckets will be allocated like this:
start_time - 1.9 * step
start_time - step
start_time - 0.9 * step
start_time
start_time + 0.1 * step
start_time + step
start_time + 1.1 * step
start_time + 2 * step
start_time + 2.1 * step
start_time + 3 * step
start_time + 3.1 * step
start_time + 4 * step
...
end_time
Actually window % step is used to set such boundaries between buckets. The idea of such buckets is that start_time + i * step - window is always on a bucket boundary for any i = 0,1,2,3,4...
Such buckets have different widths, but it seems OK since only populated buckets are stored, because we don't waste memory for buckets without any data.
window = 1.999999999999999999 due to rounding error is impossible. All timestamp arithmetic is performed with integers or DateTime64/Decimal64. So we never lose anything due to rounding here.
There was a problem hiding this comment.
Such buckets have different widths
Thanks, this is what I misunderstood.
| }; | ||
|
|
||
| /// Insert the result into the column | ||
| void doInsertResultInto(AggregateDataPtr __restrict place, IColumn & to) const |
There was a problem hiding this comment.
Another idea of this PR is to move the most of the non-trivial logic to the base class AggregateFunctionTimeseriesBase and keep mostly traits in the derived classes.
| /// - if `stack_size == 0`: recompute - keep the in-window values in a deque and recalculate their sum per each grid point, | ||
| /// this algorithm is faster when the window holds only few buckets | ||
| template <typename TimestampType, typename SummaryType> | ||
| class AggregateFunctionTimeseriesSlidingSum |
There was a problem hiding this comment.
This new class is designed to handle in the generalized form how per-bucket aggregation data gets summed to become per-step aggregation data. The main difficulty here is that it's possible that a window contains many buckets:
window = 5 steps
bucket #0: (start_time - 5 * step .. start_time - 4 * step]
bucket #1: (start_time - 4 * step .. start_time - 3 * step]
bucket #2: (start_time - 3 * step .. start_time - 2 * step]
bucket #3: (start_time - 2 * step .. start_time - step ]
bucket #4: (start_time - step .. start_time ]
bucket #5: (start_time .. start_time + step ]
bucket #6: (start_time + step .. start_time + 2 * step]
bucket #7: (start_time + 2 * step .. start_time + 3 * step]
bucket #8: (start_time + 3 * step .. start_time + 4 * step]
bucket #9: (start_time + 4 * step .. start_time + 5 * step]
Final results:
t = start_time - result is sum of buckets 0..4
t = start_time + step - result is sum of buckets 1..5
t = start_time + 2 * step - result is sum of buckets 2..6
t = start_time + 3 * step - result is sum of buckets 3..7
t = start_time + 4 * step - result is sum of buckets 4..8
t = start_time + 5 * step - result is sum of buckets 5..9
This is where we need these sliding sums.
There are 3 modes - for each step we can either merge one new bucket and "unmerge" one old bucket. Or we can recompute the sum for each step. Or use the special two-stacks approach.
| /// index up in the hash map is cheaper than sorting; otherwise collect the populated buckets and sort them once. | ||
| const bool use_range_scan = (buckets.size() != 0) | ||
| && (static_cast<double>(buckets.size()) >= static_cast<double>(bucket_count) * BUCKET_DENSITY_TO_ENABLE_RANGE_SCAN); | ||
| if (use_range_scan) |
There was a problem hiding this comment.
A smaller improvement here - since we collect buckets in unordered map, they come unsorted. But for the sliding sum we need them sorted. So we can either sort them with std::sort, or use the "range_scan" - i.e. just put them in the right places in a loop (which is faster that std::sort for dense buckets). Before this PR the range scan was always used, which isn't good for sparse buckets.
|
@groeneai help investigate all the tests failures. |
…ries-window-aligned-buckets
|
@nikitamikhaylov Investigated. On the last complete CI run (commit
The PR's own timeSeries tests (03254 / 03573 / 04319 / 03595) failed only on early June commits and pass now after the |
|
@vitlibar I was reflecting on the case when The typical max data points setting in Grafana defaults to 100 or automatically scales to the pixel width of your dashboard panel (often around 1000 to 1500). Link.In case of 30 days window and 1000 data points the step would be 2,592 seconds ≈ 43.2 minutes. While the change still makes sense I think we must optimize directly the opposite use-case. |
|
Just for a reference: In range < 8 hours the window is >= 10x larger than step under the default Grafana's max_data_points. But within this range the queries are already fast just because there is not much data there. |
Yes, probably they're already fast, but if we can make them faster, why not? |
| struct State | ||
| { | ||
| /// Maps bucket index to the set of all timestamps and values | ||
| UnorderedMapWithMemoryTracking<size_t, Bucket> buckets; |
There was a problem hiding this comment.
| UnorderedMapWithMemoryTracking<size_t, Bucket> buckets; | |
| HashMap<UInt64, Bucket, DefaultHash<UInt64>, HashTableGrower<4>> buckets; |
The only thing is that the Bucket must stay memmove-able. We can check whether this is true.
| temp_buffer.reserve(buffer.size()); | ||
| for (const auto & [timestamp, value] : buffer) | ||
| temp_buffer.emplace_back(timestamp, value); | ||
| std::sort(temp_buffer.begin(), temp_buffer.end()); |
There was a problem hiding this comment.
| std::sort(temp_buffer.begin(), temp_buffer.end()); | |
| ::sort(temp_buffer.begin(), temp_buffer.end()); |
pdqsort will be used then and it's strictly better on integer keys.
| ordered_buckets.reserve(buckets.size()); | ||
| for (const auto & [bucket_index, bucket] : buckets) | ||
| ordered_buckets.emplace_back(bucket_index, &bucket); | ||
| std::sort(ordered_buckets.begin(), ordered_buckets.end(), |
There was a problem hiding this comment.
| std::sort(ordered_buckets.begin(), ordered_buckets.end(), | |
| ::sort(ordered_buckets.begin(), ordered_buckets.end(), |
|
^^ I will do this in a separate PR. |
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: ClickHouse#106724 Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 686/720 (95.28%) · Uncovered code |
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: ClickHouse#106724 Co-Authored-By: Claude Fable 5 <[email protected]>
…aligned-buckets Optimize and simplify timeSeries*ToGrid() aggregation functions
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: ClickHouse#106724 Co-Authored-By: Claude Fable 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
timeSeries*ToGrid()aggregation functions:first_over_time,max_over_time);window>>stepbecause we don't recompute it from scratch for every grid point anymore and we use two-stack approach instead;timeSeries*aggregation functions are experimental so not having migration code seems ok)Version info
26.7.1.1097(included in26.7and later)