Repository navigation
Replace the per-bucket hash map in timeSeries*ToGrid with a sorted-append sample array - #113681
Conversation
|
Workflow [PR], commit [b45c7a2] Summary: ❌
AI ReviewSummaryThis PR replaces the per-bucket hash map in the Findings❌ Blockers
Tests
Final VerdictRequest changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 91/99 (91.92%) · Uncovered code |
timeSeries*ToGrid with a sorted-append sample array
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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. Object file sizes6 object files changed (-115.59 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units9 translation units recompiled, 40 s compile time in total, 9 of them have a recent master baseline. |
6b7fec1 to
4490ff9
Compare
…pend sample array The timeSeries*ToGrid aggregate functions stored each bucket's samples in an absl::flat_hash_map keyed by timestamp. On heavy PromQL-style range queries the per-sample emplace plus the per-bucket copy-and-sort at finalization cost ~10-12% of query CPU, while samples arrive in ascending timestamp order nearly always (measured 1 out-of-order add in ~1.5 billion on a 32-thread read). Store a flat memory-tracked vector of (timestamp, value) pairs instead: add() is an O(1) append with in-place max for an equal timestamp; a rare out-of-order sample only clears a `sorted` flag and the buffer is sorted and max-deduplicated lazily, before the samples are read. merge() is a linear merge of two sorted runs with a plain-append fast path for disjoint time ranges. The wire format (count + pairs) is unchanged and deserialize() accepts pairs in any order, so mixed-version peers interoperate; forEachSample now guarantees ascending order, which lets the rate/delta/changes aggregators drop their per-bucket sort buffer. Co-Authored-By: Claude Fable 5 <[email protected]>
…e for #112360 The merged deriv scale fix changes timeSeriesDerivToGrid output from per-tick to per-second on DateTime64(3) timestamps (x1000); one deriv line in the reference updates accordingly, all other outputs are unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
4490ff9 to
2c4f705
Compare
|
📊 Cloud Performance Report ✅ AI verdict: This change is scoped entirely to the timeSeries*ToGrid aggregate functions (swapping the per-bucket hash-map sample store for a sorted flat array) plus their tests. ClickBench Q17 exercises none of that code path, so the flagged -15.4% improvement on Q17 cannot plausibly come from this diff and is treated as run-to-run variance (downgraded to not sure). No ClickBench or TPC-H query touches the modified code, so no genuine performance impact is expected on these benchmarks. clickbenchFlagged queries (1 of 43)
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🟢 No significant changes Debug info
|
… semantics The unstable sort could reorder an equal-timestamp run before the left-to-right std::max fold, flipping which value survives a duplicate-timestamp tie between a NaN (a Prometheus stale marker) and a number compared to the former hash map's std::max(existing, incoming). A stable sort keeps the run in arrival order, so the fold resolves duplicates exactly like the hash map did: the larger value wins, the first arrival wins against a NaN. Extend the regression test with duplicate-NaN cases on the lazy normalization path (out-of-order adds), the in-memory -Merge path, and serialization through an AggregatingMergeTree roundtrip, in both arrival orders. Addresses the AI review: #113681 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the hand-rolled linear merge of two sorted sample arrays with std::merge (stable, so on an equal timestamp this state's sample precedes the argument's) followed by the deduplication fold, now shared with sortAndDeduplicate as deduplicateSorted. The timestamp-only comparator becomes the named lessByTimestamp, used by both the sort and the merge. Co-Authored-By: Claude Fable 5 <[email protected]>
| auto & last = buffer.back(); | ||
| if (timestamp == last.first) | ||
| { | ||
| last.second = std::max(last.second, value); |
There was a problem hiding this comment.
It's better to check for NaNs here and if the timestamps are equals then keep the maximal non-NaN value. It'll allow to use an ordinary sort, not a stable sort.
I'll do the changes
Most buckets of the dense grid workloads hold exactly one sample. The plain vector allocated heap storage per bucket, where the hash map it replaced used its inline single-element storage - the dense queries of the timeseries_to_grid_aggregation_functions perf test measured 22-47% slower. An inline capacity of 1 makes single-sample buckets allocation-free again, while larger buckets spill to heap storage counted by `AllocatorWithMemoryTracking`.
There was a problem hiding this comment.
Pull request overview
This PR optimizes the timeSeries*ToGrid aggregate functions by replacing per-bucket sample storage from a hash map keyed by timestamp to a flat (timestamp, value) sample array with lazy normalization, aiming to reduce per-sample overhead and avoid per-bucket copy+sort work at finalization.
Changes:
- Refactors per-bucket sample storage to an append-friendly array with lazy sort+dedup and a merge optimized for common disjoint-range cases.
- Updates order-dependent aggregators to rely on
Samples::forEachSampleguaranteeing ascending iteration, removing per-aggregator sort buffers. - Adds a new stateless regression test for out-of-order inputs / duplicates / mixed merge paths, and extends performance coverage with an ingestion-heavy workload.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/queries/0_stateless/04815_timeseries_to_grid_sorted_samples.sql | New stateless test covering disorder, duplicate timestamps (incl. NaN), and multiple merge/serialization paths. |
| tests/queries/0_stateless/04815_timeseries_to_grid_sorted_samples.reference | Expected output for the new stateless test. |
| tests/performance/timeseries_to_grid_aggregation_functions.xml | Adds an ingestion-heavy dataset and queries to stress Samples::add/iteration behavior. |
| src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesSamples.h | Implements sorted-append sample buffer, lazy normalization, and linear merge of sorted runs. |
| src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesLinearRegression.h | Adjusts comment to reflect updated sample iteration semantics. |
| src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesExtrapolatedValue.h | Switches to forEachSample (now ordered) and removes reusable sort buffer. |
| src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesChanges.h | Switches to forEachSample (now ordered) and removes reusable sort buffer. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
@groeneai Investigate CI failures |
|
Both reds are pre-existing trunk failures, not caused by this PR. The run has real coverage (158 OK, 15 skipped, 0 dropped jobs), so these two are the whole story. 1.
|
…ries-sorted-samples
| last.second = getMax(last.second, value); | ||
| return; | ||
| } | ||
| sorted = false; |
There was a problem hiding this comment.
Once a bucket has gone out of order, this path no longer deduplicates earlier timestamps until a later sort() / merge() / serialize(). That is fine for the scalar MergeTree path the PR benchmarks, but AggregateFunctionTimeseriesBase also supports array arguments and feeds them element-by-element in user order. A single row like [t1, t2, t1, t2, ...] in one bucket now retains every sample here, where the previous hash map kept just two keys. That changes per-state memory from O(unique timestamps) to O(total samples) on shuffled / duplicate-heavy arrays and can turn previously safe queries into memory-limit failures.
Please cap unsorted-buffer growth once sorted is cleared (eager normalize, thresholded sort() / dedup, or another online dedup path for the array / unsorted surfaces) before merging this.
|
@groeneai find (or implement) and link PRs with the fixes for the stress tests. |
|
Neither red is caused by this PR; both are chronic trunk signatures, and both have fixing PRs. The run itself is sound: praktika 1. Stack: Mechanism: a Breadth over 30 days on the message text (not the STID token): 317 rows, 221 distinct PRs, 21 true-master rows, 15 distinct sub-STIDs, across 12 Stress flavours. This PR contributes exactly 1 of the 317. Most recent master hits: Per-build presence rather than commit distance: 2. This one has a named root cause and it is a test-isolation defect, not an engine bug. From #113794 makes the refused DETACH fail the test instead of letting the One caveat I will not paper over: #113009 (also mine, open) only improves the diagnostic for this family; it does not fix a divergence, and the digest assertion has four other commit sites ( Reports:
|
|
I read both implementations and measured the sparse case. Short answers first; the third one does turn up a case where this PR is worse. 1. Did #80590 use vectors? No. The per-bucket samples container was a hash map from its first commit: 2. Then the sparse-data rationale is about a different container than this PR touches. The dense-array implementation was This PR does not touch it. The outer map is still 3. Is it better, and does sparse input regress? For sparsity in the sense that matters here (few samples per populated bucket), it is better, not worse. Measured with a counting allocator wrapped around the real
At one sample per bucket both are 24 bytes with no heap allocation, and the array is never worse. Merge peak is 1.6x to 2.5x lower because disjoint partial states append instead of rehashing, and the iteration path loses an allocation (master copies each bucket into a scratch vector and sorts it per bucket). The case where it is worse: duplicate timestamps that do not arrive adjacently.
Crossover is at about 3 interleaved repeats, and it then grows linearly in the repeat count while master stays flat at the distinct-timestamp count. A correctness control on the same interleaved input confirms both produce identical deduped samples, so this is purely footprint. On reachability I want to be precise, because it decides whether this matters. With If you want it closed rather than argued away, the minimal change keeps the array and bounds the disorder: in Two things I checked while reading and consider correct: |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Replaced the per-bucket hash map inside the
timeSeries*ToGridaggregate functions with a flat sorted array of samples: sample ingestion becomes an O(1) append for in-order inputs (the overwhelmingly common case) and the per-bucket copy-and-sort at finalization is gone.Description
The
timeSeries*ToGridfunctions kept each bucket's samples in anabsl::flat_hash_map<timestamp, value>: everyadd()paid a hash-map emplace, and the order-dependent functions (rate,increase,delta,changes,resets) copied and sorted every bucket at finalization. Yet the input is almost perfectly ordered — samples come from MergeTree tables sorted by(id, timestamp); an instrumented probe on a 32-thread read of a 62.5-billion-sample table counted 1 out-of-order add in 1,474,559,998.The bucket is now a flat, memory-tracked vector of
(timestamp, value)pairs: O(1) append while timestamps ascend, in-place max on an equal timestamp, and a rare out-of-order add just clears asortedflag — normalization (sort + max-dedup) runs lazily, only for buckets that actually saw disorder.merge()is a linear merge of sorted runs with an append fast path for disjoint time ranges.forEachSamplenow guarantees ascending order, so the copy-and-sort buffers are deleted from the rate/delta/changes aggregators.The wire format and
FORMAT_VERSIONs are unchanged;deserialize()assumes no order of incoming pairs (old peers send hash-map iteration order), so mixed-version clusters interoperate — verified in both directions. Duplicate timestamps keep the larger value with the oldstd::maxargument order.Measured on the 62.5-billion-sample table: a 30-day
sum by(...)(rate(...))over 25,600 series drops ~6% of total query CPU (1106 s -> 1037 s); wall time and peak memory move little (the scan dominates the critical path, and raw sample storage dominates the state either way). The structural point is what this enables: the sorted buffer is the prerequisite for O(1) per-segment summaries in the rate family (follow-up), which is where the ~44 GiB state peaks of such queries actually go away. All query results are fingerprint-identical.Tests: a new stateless test (shuffled and duplicate-timestamp inputs in both orders, NaN at duplicated timestamps,
-Mergeof unsorted in-memory states, interleaved parts, two-level merges, serialized-state merges throughremote('127.0.0.{1,2}', ...), anAggregatingMergeTreeroundtrip, a fixed state literal in old-peer wire order); all 40 existing timeseries/PromQL stateless tests pass byte-identically; the perf test gains an ingestion-heavy scenario (50M rows, 10k series).🤖 Generated with Claude Code
Version info
26.8.1.1371(included in26.8and later)