Skip to content

Optimize and simplify timeSeries*ToGrid() aggregation functions - #106724

Merged
nikitamikhaylov merged 7 commits into
ClickHouse:masterfrom
vitlibar:timeseries-window-aligned-buckets
Jul 17, 2026
Merged

nikitamikhaylov merged 7 commits into
ClickHouse:masterfrom
vitlibar:timeseries-window-aligned-buckets

Conversation

@vitlibar

@vitlibar vitlibar commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

timeSeries*ToGrid() aggregation functions:

  • were optimized and simplified;
  • adding new functions is now much easier;
  • buckets are now aligned to both step and window (that will allow to store just aggregation data and not all the samples for functions like first_over_time, max_over_time);
  • final aggregation is now much faster when window>>step because we don't recompute it from scratch for every grid point anymore and we use two-stack approach instead;
  • the format version was bumped because the layout of buckets changed (these timeSeries* aggregation functions are experimental so not having migration code seems ok)

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6236e7d]

Summary: ✅


AI Review

Summary

This PR rewrites the timeSeries*ToGrid finalize path around window-aligned buckets and sliding per-bucket summaries. The refactor is directionally good, but two issues still stand out in the current code: the regression-based functions still lose DateTime64(9) precision on long grids, and aggregate-state deserialization still reserves attacker-controlled sizes before validating them.

PR Metadata
  • Changelog category should be Experimental Feature, not Not for changelog: this PR changes the user-visible behavior and serialized state format of experimental SQL functions.
  • With Experimental Feature, a changelog entry is required. The current bullet list is too implementation-heavy for CHANGELOG.md. Suggested replacement:
    timeSeries*ToGrid experimental aggregate functions are faster for large window / step ratios and now align buckets to both step and window, which changes their serialized state format.
Findings
  • ❌ Blockers
    • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesLinearRegression.h:56-59,99-113,197-213] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/106724#discussion_r3373900207] The new regression path still centers x on Base::start_timestamp, not on the active bucket/window. That avoids the old raw-sum cancellation, but it still collapses sub-ULP DateTime64(9) differences on long grids and returns wrong results for valid inputs. A concrete valid repro is start=0, end=1600000000000000000, step=100000000000 (16,000,001 grid points, still below MAX_GRID_SIZE), with samples at end-2, end-1, end and values 0,1,2: the current Welford path sees x ~= 1.6e18 for all three points, so m2_x becomes 0 and timeSeriesDerivToGrid returns NULL instead of slope 1. Suggested fix: keep per-bucket/per-window timestamps in a local coordinate system, for example offsets from the bucket/window anchor merged with a stable parallel-variance formula, and add a focused DateTime64(9) regression test with the grid start far from the active window.
  • ⚠️ Majors
    • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesBase.h:231-237; src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesSamples.h:68-70] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/106724#discussion_r3406381022, https://github.com/ClickHouse/ClickHouse/pull/106724#discussion_r3493401135] Both deserializers still call reserve on untrusted counts before any byte-length or practical upper-bound check. For huge-window grids a malformed aggregate state can set buckets_size == bucket_count and force data(place)->buckets.reserve(...); each bucket then does the same with sample_count. That turns ...Merge or on-disk state loading into an avoidable OOM/DoS path instead of a controlled INCORRECT_DATA exception. Suggested fix: bound buckets_size and sample_count by remaining serialized bytes, or another hard limit derived from the format, before reserving.
Tests
  • ⚠️ Add a focused stateless regression for the long-grid DateTime64(9) precision case above. The current tests cover split-window geometry, memoization, and two-stack selection, but not a grid whose start is far enough from the active window to reintroduce floating-point collapse.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    1. Re-center linear-regression timestamps on the active bucket/window so long-grid DateTime64(9) queries cannot collapse distinct samples into m2_x == 0.
    2. Bound serialized buckets_size and sample_count before calling reserve, so malformed aggregate states fail with INCORRECT_DATA instead of allocating arbitrarily large maps.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 8, 2026
@vitlibar
vitlibar requested a review from Copilot June 8, 2026 14:11

Copilot AI left a comment

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.

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 AggregateFunctionTimeseriesBase bucketing/indexing to account for window alignment (including window % step split buckets) and centralized result materialization over the grid.
  • Introduced AggregateFunctionTimeseriesSamples as shared per-bucket sample storage with reusable (sorted/unsorted) aggregation policies.
  • Refactored multiple timeSeries*ToGrid implementations (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.

Copilot AI left a comment

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@vitlibar
vitlibar force-pushed the timeseries-window-aligned-buckets branch from 045e444 to 7984d74 Compare June 8, 2026 21:31
@vitlibar
vitlibar requested a review from Copilot June 8, 2026 21:31

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

@vitlibar
vitlibar force-pushed the timeseries-window-aligned-buckets branch from 7984d74 to 9470462 Compare June 8, 2026 23:24
@vitlibar
vitlibar requested a review from Copilot June 8, 2026 23:25

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 2 comments.

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

@vitlibar
vitlibar force-pushed the timeseries-window-aligned-buckets branch from 483735c to bd09a06 Compare June 9, 2026 10:22
@vitlibar
vitlibar requested a review from Copilot June 9, 2026 10:22

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.

@vitlibar
vitlibar marked this pull request as ready for review June 29, 2026 21:08
@vitlibar

Copy link
Copy Markdown
Member Author

@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))

@vitlibar vitlibar Jun 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

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.

@vitlibar vitlibar Jul 16, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

@vitlibar vitlibar Jun 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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)

@vitlibar vitlibar Jun 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai help investigate all the tests failures.

@groeneai

Copy link
Copy Markdown
Collaborator

@nikitamikhaylov Investigated. On the last complete CI run (commit 1c71e4a) there were 4 reds, none in the TimeSeries aggregate code this PR touches. Breakdown:

  • Hung check, possible deadlock (Stress test amd_tsan + arm_tsan): chronic trunk deadlock family, 1909 hits / 701 PRs / 343 on master in 30d. Not caused by this diff. Tracked by Log live local thread pools at GlobalThreadPool shutdown #105905 (open) / Limit and cancel in-flight queries in the server-side AST fuzzer #108212 (merged).
  • AST fuzzer Inconsistent AST formatting (STID 1941-1bfa): generic parser/formatter roundtrip bucket, 127 hits / 92 PRs / 4 on master in 30d. The failing query here is a plain EXPLAIN over three UInt64 literals, unrelated to timeSeries*ToGrid. Chronic trunk bug.
  • 01550_create_map_type (Stateless amd_tsan, s3, parallel): flaky, 10 hits / 9 PRs / 1 on master in 30d. Map type test, unrelated to this diff.

The PR's own timeSeries tests (03254 / 03573 / 04319 / 03595) failed only on early June commits and pass now after the .reference updates in this branch. So nothing on the latest run is caused by the refactor. A fresh run on the current head 07baaf4 is in progress; I'll flag any new red that maps back to the diff.

@nikitamikhaylov

nikitamikhaylov commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

@vitlibar I was reflecting on the case when window>>step and I think this is non-realistic. The default "window" is 5 mins while the step can be much larger when I navigate the dashboards in Grafana as it's defined as time_range / max_data_points.

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.

@nikitamikhaylov

Copy link
Copy Markdown
Member

Just for a reference:

❯ Starting which range we can say that a window is much larger than step using the default window size and 1000 max data points?

It goes the opposite direction from "starting which range" — with a fixed 1000-point budget the step grows with the range, so the default 5-minute window dominates the step only for ranges below a threshold, not above one.
The arithmetic: step = range / 1000, window = 300 s, so window / step = 300 × 1000 / range(s) = 300,000 / range(s).

┌───────────────────────────────────────┬────────────────────────────────────┐
│          Ratio window : step          │           Range boundary           │
├───────────────────────────────────────┼────────────────────────────────────┤
│ 10× ("much larger")                   │ range ≤ 300,000 s / 10 ≈ 8.3 hours │
├───────────────────────────────────────┼────────────────────────────────────┤
│ 4× (the PromQL rule-of-thumb minimum) │ range ≤ ~21 hours                  │
├───────────────────────────────────────┼────────────────────────────────────┤
│ 1× (parity)                           │ range ≈ 300,000 s ≈ 3.5 days       │
├───────────────────────────────────────┼────────────────────────────────────┤
│ step exceeds window (gappy regime)    │ range > ~3.5 days                  │
└───────────────────────────────────────┴────────────────────────────────────┘

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.

@vitlibar

Copy link
Copy Markdown
Member Author

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;

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.

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

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.

Suggested change
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(),

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.

Suggested change
std::sort(ordered_buckets.begin(), ordered_buckets.end(),
::sort(ordered_buckets.begin(), ordered_buckets.end(),

@nikitamikhaylov

Copy link
Copy Markdown
Member

^^ I will do this in a separate PR.

@nikitamikhaylov nikitamikhaylov self-assigned this Jul 17, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 17, 2026
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]>
Merged via the queue into ClickHouse:master with commit 6c10ce5 Jul 17, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 686/720 (95.28%) · Uncovered code

Full report · Diff report

Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Jul 20, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…aligned-buckets

Optimize and simplify timeSeries*ToGrid() aggregation functions
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
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-not-for-changelog This PR should not be mentioned in the changelog 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.

6 participants