Skip to content

Replace the per-bucket hash map in timeSeries*ToGrid with a sorted-append sample array - #113681

Merged
nikitamikhaylov merged 7 commits into
masterfrom
timeseries-sorted-samples
Aug 13, 2026
Merged

nikitamikhaylov merged 7 commits into
masterfrom
timeseries-sorted-samples

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Replaced the per-bucket hash map inside the timeSeries*ToGrid aggregate 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*ToGrid functions kept each bucket's samples in an absl::flat_hash_map<timestamp, value>: every add() 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 a sorted flag — 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. forEachSample now 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 old std::max argument 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, -Merge of unsorted in-memory states, interleaved parts, two-level merges, serialized-state merges through remote('127.0.0.{1,2}', ...), an AggregatingMergeTree roundtrip, 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

  • Merged into: 26.8.1.1371 (included in 26.8 and later)

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b45c7a2]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6673) FAIL cidb IGNORED
Stress test (arm_tsan) FAIL
Logical error: Digest does not match (STID: 5007-4ae8) FAIL cidb IGNORED

AI Review

Summary

This PR replaces the per-bucket hash map in the timeSeries*ToGrid sample state with a lazily normalized sample array to speed the common in-order path. The ordered-path optimization itself looks reasonable, but the current version still changes duplicate-NaN semantics relative to the old code while claiming fingerprint-identical results, and it also introduces a real memory regression on supported unsorted array inputs once a bucket loses sortedness.

Findings

❌ Blockers

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesSamples.h:185-214] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/113681#discussion_r3729533199] getMax makes a real value always beat a NaN at the same timestamp, and [tests/queries/0_stateless/04815_timeseries_to_grid_sorted_samples.sql:44] now asserts that behavior. The old state logic used std::max(existing, incoming), so [nan, 5] stayed nan while [5, nan] stayed 5; that order-sensitive stale-marker behavior is exactly what the PR description’s “fingerprint-identical” and mixed-version claims rely on. As written, the patch is no longer a pure performance refactor: duplicate-timestamp Prometheus stale markers produce different query results, and new nodes can disagree with old nodes on the same serialized state.
    Suggested fix: preserve first-arrival order within equal-timestamp runs (stable tie-breaker or stored sequence number) so the refactor keeps the old result semantics, or explicitly treat this as a backward-incompatible behavior change with compat handling and updated PR metadata/tests.

⚠️ Majors

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesSamples.h:39-49] Once sorted flips to false, add only deduplicates the current tail. Supported array inputs are fed element-by-element in original order by [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesBase.h:767], so a row like [t1, t2, t1, t2, ...] that lands in one bucket now retains every sample until finalize/merge, whereas the old hash map held two timestamps. That regresses bucket memory from O(unique timestamps) to O(total samples) on shuffled / duplicate-heavy inputs and can turn previously safe array workloads into aggregation-memory blowups.
    Suggested fix: once a bucket becomes unsorted, add an eager normalization / growth cap (or another online dedup path) so duplicate-heavy disorder cannot accumulate unbounded raw samples until finalization.
Tests
  • ⚠️ The new coverage proves result equality on small shuffled examples, but it does not exercise the regression surfaces above: there is no focused compatibility test for serialized duplicate-NaN states across versions / orderings, and no stress test or benchmark for duplicate-heavy unsorted array inputs where bucket memory now scales with total samples rather than unique timestamps.
Final Verdict

Request changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 91/99 (91.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 6, 2026
@nikitamikhaylov nikitamikhaylov changed the title Replace the per-bucket hash map in timeSeries*ToGrid with a sorted-append sample array Replace the per-bucket hash map in timeSeries*ToGrid with a sorted-append sample array Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b45c7a25c with master bb1bd3074 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2e330af4c; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.05 MiB 689.03 MiB -3.02 MiB (-0.44%)

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 sizes

6 object files changed (-115.59 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTi… 4.77 MiB 4.67 MiB -106.51 KiB (-2.18%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

9 translation units recompiled, 40 s compile time in total, 9 of them have a recent master baseline.

Job report

nikitamikhaylov and others added 2 commits August 7, 2026 11:23
…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]>
@nikitamikhaylov
nikitamikhaylov force-pushed the timeseries-sorted-samples branch from 4490ff9 to 2c4f705 Compare August 7, 2026 09:23
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 470 -15.4% <0.0001 This PR only rewrites the timeSeries*ToGrid aggregate sample storage; ClickBench Q17 runs none of that code, so the -15.4% is run-to-run variance, not a real PR effect.

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
  • StressHouse run: 09a0ea76-9c71-4192-8046-0f5ed726e509
  • MIRAI run: 9c6863e5-7b3f-4130-a5b0-df76e047e79e
  • PR check IDs:
    • clickbench_982575_1786580964
    • clickbench_982717_1786580980
    • clickbench_982818_1786580990
    • tpch_adapted_1_official_983034_1786581072
    • tpch_adapted_1_official_983152_1786581078
    • tpch_adapted_1_official_983283_1786581181

@vitlibar vitlibar self-assigned this Aug 7, 2026
nikitamikhaylov and others added 2 commits August 7, 2026 15:29
… 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);

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.

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`.

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 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::forEachSample guaranteeing 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.

@vitlibar

Copy link
Copy Markdown
Member

@groeneai Investigate CI failures

@groeneai

Copy link
Copy Markdown
Collaborator

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. Stress test (amd_msan) - materialized-CTE gate (STID 2467-2c2d)

AST fuzzer query. No frame from this diff anywhere in the stack:

MemorySource::generate (ReadFromMemoryStorageStep.cpp:87) <- FutureSetFromSubquery::buildSetInplace <- VirtualColumnUtils::buildSetsForDagImpl <- ReadFromSystemColumns::applyFilters <- nested QueryPlan::optimize <- ReadFromMerge::createChildrenPlans <- ReadFromMerge::applyFilters.

Fuzzed shape, from the server log: WITH t AS MATERIALIZED (SELECT number AS c FROM numbers(50)) SELECT count() FROM dist_04043 WHERE (x IN (SELECT c FROM merge(currentDatabase(), '^t$') ...)) OR (x IN (SELECT c FROM t ...)).

Fixing PR: #113558 (open, @ alexey-milovidov). createChildrenPlans optimizes each Merge child on its own while resolveMaterializingCTEs claims the CTE globally, so the first child wins and every sibling's gate degenerates to a gate-less step; #113558 strips the claim from every child before optimization. I A/B tested that on 2026-08-10 against exactly this system.columns child entry path: 5/5 aborts on master, 5/5 clean on #113558.

It is absent from this build, so the failure is expected here: removeDelayedMaterializingCTEsStepFor has 0 hits in StorageMerge.cpp at 8d9dae85 (control: 1 hit at #113558's head). Re-running after it merges should clear this.

Breadth over 30 days: 86 rows across 69 distinct pull requests and 9 true-master runs, in 14 different checks. One of those rows is this PR. Tracking issue #113184.

2. Stress test (arm_asan_ubsan) - LeakSanitizer (STID 2064-22d0)

The fleet-wide all-indirect retain cycle of issue #113954: 629 leak blocks, 0 direct, 189962 bytes in 1429 allocations.

The part that needs stating plainly, since this PR is in the timeseries aggregate path: 6 of the 629 blocks do carry a timeseries frame, and they are still not from your diff. They name AggregateFunctionTimeseriesToGridSparse and AggregateFunctionTimeseriesBase::createResultType, while the four headers this PR changes (...Changes.h, ...ExtrapolatedValue.h, ...LinearRegression.h, ...Samples.h) appear in 0 blocks. Their allocation site is AggregateFunctionFactory::getImpl <- QueryAnalyzer::resolveFunction, i.e. the aggregate is constructed normally during analysis and then retained as payload of an abandoned query context. Nothing in those blocks is an allocation your change performs.

The control that settles it: that same AggregateFunctionTimeseriesToGridSparse frame appears in LeakSanitizer reports on 119 unrelated pull requests and 14 true-master runs in the last 14 days, first seen 2026-08-10 08:22. Master does not contain this PR.

Owner: the only in-flight change touching this cycle's edge is #113397 (open), and it is absent from every build I have measured, so no CI row tests it yet. On three post-fix true-master shas I measured that my merged #113953 (the DDL half of this family) is present and the leak still fires, so #113397 alone is not proven sufficient. I am investigating the query-path cycle at full effort and will link the fix PR on #113954.

last.second = getMax(last.second, value);
return;
}
sorted = false;

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.

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.

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai find (or implement) and link PRs with the fixes for the stress tests.

@groeneai

Copy link
Copy Markdown
Collaborator

Neither red is caused by this PR; both are chronic trunk signatures, and both have fixing PRs.

The run itself is sound: praktika result_pr.json at b45c7a25cd32e9f0cb9ea297f61016df06eea4e4 shows 159 OK / 15 skipped (all with a stated reason) / 2 FAIL and 0 dropped jobs, so the two reds are the whole story.

1. Stress test (arm_debug) - Sizes of nested column and null map of Nullable column are not equal after deserialization -> fixing PRs #112484 and #106988 (mine, both open)

Stack: SerializationNullable::deserializeBinaryBulkWithMultipleStreams (SerializationNullable.cpp:178) <- MergeTreeIndexGranuleSet::deserializeBinary (MergeTreeIndexSet.cpp:129) <- MergeTreeIndexReader::read <- MergeTreeDataSelectExecutor::filterMarksUsingIndex. Zero frames from your diff, which is confined to four AggregateFunctions/TimeSeries/*.h headers plus tests.

Mechanism: a set skip index granule is decoded with the types the current metadata declares, while the bytes on disk were written under the pre-ALTER types. #112484 makes getDeserializedFormat() non-virtual and gates it on a new isPartTypeCompatible(), reporting the index as not materialized in parts whose recorded types no longer match; MergeTreeIndexSet inherits that base implementation, and all four read-path call sites go through it. #106988 covers the ALTER MODIFY COLUMN window on the replicated queue side.

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: d5880fd61206 (2026-08-13 13:59, arm_asan_ubsan s3), 068ec6d2ae62 (2026-08-13 07:16, arm_debug), 5abf3cd74e8c (2026-08-12 19:55, arm_release). Master cannot contain your branch, so it is not yours.

Per-build presence rather than commit distance: isPartTypeCompatible and getPhysicalFormat are both 0 hits in MergeTreeIndices.h at your head, and 1 hit at #112484's head. So your build predates the fix and the failure is expected there; a re-run after those merge should clear it.

2. Stress test (arm_tsan) - Digest does not match -> fixing PR #113794 (mine, open)

This one has a named root cause and it is a test-isolation defect, not an engine bug.

From clickhouse-server.err.log: at 23:33:29.640 and 23:33:34.331, database test_7, DETACH TABLE is not allowed for Replicated databases (Code 80) from 04545_attach_projection_part_offset_setting_disabled.sh. That test rewrites a table's metadata file with sed after the DETACH; the DETACH return code was not checked, so the sed ran against a still-attached table, and test_7 was a Replicated database because a peer test re-engined the shared --database. The digest then diverges from the on-disk bytes: Digest of local metadata (1953903275430257105) is not equal to in-memory digest (11489513990679429930), and the next DDL aborts at assertDigestWithProbability (DatabaseReplicated.cpp:1303) via commitCreateTable (:2644). The aborting query is that test's own CREATE TABLE test_7.t_04545_flip_co ... PROJECTION p (...).

#113794 makes the refused DETACH fail the test instead of letting the sed run, for that file and three siblings. Breadth for this bucket over 30 days: 5 rows, 5 distinct PRs, 0 master rows - PR-side stress lane only, and the carriers are unrelated.

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 (commitAlterTable, dropTable, and two more create-path buckets) that #113794 does not cover. For this particular red the 04545 chain above is the mechanism, so #113794 is the one to link.

Reports:

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@groeneai check this implementation and the one in the original PR: #80590 Did it also use vectors? Is the current PR better anyhow? The original implementation got rewritten to use hashtables because the real data can be sparse and thus these functions consume lots of memory.

@groeneai

Copy link
Copy Markdown
Collaborator

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: absl::flat_hash_map<TimestampType, ValueType> samples (AggregateFunctionTimeseriesExtrapolatedValue.h:44 at d4521a5, unchanged at the d0326a1 merge). Its outer bucket container was std::unordered_map<size_t, Bucket>. The only vectors there are transient: a sort scratch in doInsertResultInto (ExtrapolatedValue.h:232) and a std::deque sliding window.

2. Then the sparse-data rationale is about a different container than this PR touches. The dense-array implementation was tsToGrid, which #80590 replaced: it sized its state as values_offset + sizeof(ValueType) * bucket_count (AggregateFunctionTimeseriesToGrid.h:60) and constructed every slot in create() regardless of population, so a 10001-point grid paid for 10001 grid points whether or not samples landed in them. #80590 deleted it (c8a96ae, which came with that PR) in favour of the sparse map of buckets. That is the sparse concern, and it is about the outer container, keyed by grid point.

This PR does not touch it. The outer map is still TimeSeriesBucketsMap<Bucket> = HashMap<UInt64, Bucket, TrivialHash, ...> (AggregateFunctionTimeseriesBase.h:53), and AggregateFunctionTimeseriesBase.h is not in the diff, byte-identical to master at head b45c7a2. Only the inner per-bucket container changes, and it is keyed by nothing: it holds the samples that actually arrived. Sparse grids stay sparse.

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 AggregateFunctionTimeseriesSamples from each branch (master and b45c7a2, add/merge/forEachSample verbatim, Int64/Float64), bytes per bucket including the state:

samples in bucket master (hash map) this PR (sorted array)
1 24 24
2 104 56
4 168 88
8 304 152
64 2208 1048
1024 34848 16408

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. add compares only against buffer.back(), so it collapses a duplicate only when it arrives next to its twin. Otherwise every repeat appends and nothing collapses until sort(). Same measurement harness, k distinct timestamps each arriving 40 times:

bucket contents master this PR ratio
k=4, 40 copies, adjacent 248 128 0.52x
k=2, 40 copies, interleaved 104 3360 32x
k=4, 40 copies, interleaved 248 6688 27x
k=10, 40 copies, interleaved 448 14624 33x
k=4, 3 copies, interleaved 248 480 1.9x
k=4, 2 copies, interleaved 248 288 1.16x

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 ORDER BY (id, timestamp) the scan delivers duplicates adjacently and the dedup does fire: on a 12-part table with multiplicity 40 I measured 38001 adjacent duplicate pairs out of 40000 rows per series and only 1 descending step, so that shape is fine. The interleaved shape needs a table whose sort key does not order timestamps within a series, e.g. ORDER BY id; there I measured 0 adjacent duplicates and 53 descending steps per series over 40000 rows. That is a supported table definition, so the regression is reachable, but it needs both duplicate timestamps and a sort key that scatters them, and the factor is bounded by the duplicate multiplicity rather than by row count.

If you want it closed rather than argued away, the minimal change keeps the array and bounds the disorder: in add, once buffer.size() exceeds a small multiple of the distinct count observed at the last sort(), sort and deduplicate in place. Footprint then stays proportional to distinct timestamps in every arrival order, and the wins in the first table are unaffected. I can push that here with a test for the interleaved shape if you would like it in this PR.

Two things I checked while reading and consider correct: getMax makes duplicate resolution NaN-aware and order-independent, and deserialize sorts after reading because older peers serialize in hash-map order.

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit a55ac98 Aug 13, 2026
177 of 180 checks passed
@nikitamikhaylov
nikitamikhaylov deleted the timeseries-sorted-samples branch August 13, 2026 21:58
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
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