Skip to content

Memoize consecutive id lookups in ContextTimeSeriesTagsCollector::getGroupByID - #113580

Merged
vitlibar merged 1 commit into
masterfrom
timeseries-idtogroup-memoize
Aug 6, 2026
Merged

vitlibar merged 1 commit into
masterfrom
timeseries-idtogroup-memoize

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Aug 5, 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):

Speed up PromQL queries over TimeSeries tables: timeSeriesIdToGroup now reuses the previous row's group when consecutive rows carry the same series id, skipping the per-row id serialization and hash lookup.

Description

Every PromQL selector is transpiled to SELECT timeSeriesIdToGroup(id), timestamp, value FROM timeSeriesSelector(...), so getGroupByID runs once per sample. It serialized the id (default Tuple(UInt64, UUID), 24 bytes) into an arena and did a string-keyed hash lookup per row. Since the samples table is sorted by (id, timestamp), id columns arrive in long runs of equal values (typically thousands of rows per run); comparing with the previous row first makes the lookup O(runs) instead of O(rows).

Measured on a TimeSeries table with 62.5 billion samples (32 cores): a 30-day sum by(namespace)(rate(container_cpu_usage_seconds_total[5m])) query over 25,600 series drops from 39.9 s to 30.6 s cold (-23%); in a per-query CPU profile the getGroupByID + serializeValueIntoArena + Arena::allocContinue share (~19% of 1100 s total CPU) collapses. Query results are unchanged.

🤖 Generated with Claude Code

Version info

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

…GroupByID

Samples tables are sorted by (id, timestamp), so the id column reaching
timeSeriesIdToGroup arrives in long runs of equal values. Reusing the previous
row's group skips the per-row arena serialization and hash lookup: -23% wall
time on a 30-day sum(rate(...)) PromQL query over 25,600 series (62.5 billion
samples total).

Co-Authored-By: Claude Fable 5 <[email protected]>
@nikitamikhaylov nikitamikhaylov added promql comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... and removed promql labels Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c6c166]

Summary: ✅


AI Review

Summary

This PR speeds up ContextTimeSeriesTagsCollector::getGroupByID by reusing the previous group for consecutive equal IDs instead of serializing and hashing every row. That optimization is reasonable for the common Tuple(UInt64, UUID) case, but the current implementation changes the collector's identity semantics for accepted floating-point IDs, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Interpreters/ContextTimeSeriesTagsCollector.cpp:1022] groups_by_id is keyed by the serialized bytes of the ID, but the new memoization reuses the previous group based on compareAt. checkArgumentTypeForID still allows any comparable non-Nullable type, including Float32 / Float64 and composite IDs that contain them. FloatCompareHelper::compare treats all NaNs as equal and also collapses +0 and -0, while serializeValueIntoArena preserves the raw bits. Two consecutive IDs that compare equal but serialize differently will now incorrectly reuse the previous group instead of doing the real lookup, which can return the wrong group or suppress the expected Unknown identifier exception.
    Suggested fix: memoize the previous serialized key instead of the compareAt result, or explicitly reject ID types whose comparison semantics do not match their serialized-key identity.
Tests
  • ⚠️ Add a focused stateless regression that stores consecutive floating-point IDs whose serialized representations differ but compareAt returns 0 (for example 0.0 vs -0.0, or distinct NaN payloads) and verifies timeSeriesIdToGroup does not alias them.
Final Verdict

Changes requested: the optimization must preserve the serialized-key identity semantics promised by timeSeriesStoreTags and timeSeriesIdToGroup.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 18/19 (94.74%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 5, 2026
@nikitamikhaylov nikitamikhaylov changed the title Memoize consecutive id lookups in ContextTimeSeriesTagsCollector::getGroupByID Memoize consecutive id lookups in ContextTimeSeriesTagsCollector::getGroupByID Aug 5, 2026
{
const auto * it = groups_by_id.find(keys[i]);
if (i > 0 && prev_group != INVALID_GROUP
&& unwrapped.data->compareAt(i, i - 1, *unwrapped.data, /* nan_direction_hint = */ 1) == 0)

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.

groups_by_id is keyed by the serialized bytes of the identifier, but this fast path reuses the previous group based on compareAt. Those equivalence relations are not the same for every ID type that timeSeriesStoreTags and timeSeriesIdToGroup currently accept: checkArgumentTypeForID still allows any comparable non-Nullable type, including floating-point IDs, and FloatCompareHelper::compare returns 0 for any two NaNs and for +0 / -0, while serializeValueIntoArena preserves the raw bits.

That means two consecutive rows can now skip the real lookup and incorrectly inherit the previous row's group even though they serialize to different keys. In the current contract that can change the returned group or suppress the expected Unknown identifier exception. Please keep the memoization keyed on the serialized representation (for example by caching the previous serialized key) or narrow the accepted ID types accordingly.

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 20d5dd6d-b562-4bf2-a148-5b6392459efe
  • MIRAI run: 5ca40558-0f18-4c37-afa8-dac2a420245b
  • PR check IDs:
    • clickbench_1869905_1785975693
    • clickbench_1870090_1785975875
    • clickbench_1870193_1785975908
    • tpch_adapted_1_official_1870349_1785975961
    • tpch_adapted_1_official_1870478_1785976031
    • tpch_adapted_1_official_1870632_1785976127

@vitlibar vitlibar self-assigned this Aug 6, 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.

3 participants