Skip to content

Add locality_hash to the TimeSeries samples table and use it in PromQL queries - #111697

Closed
nikitamikhaylov wants to merge 5 commits into
masterfrom
timeseries-samples-locality-hash
Closed

nikitamikhaylov wants to merge 5 commits into
masterfrom
timeseries-samples-locality-hash

Conversation

@nikitamikhaylov

Copy link
Copy Markdown
Member

Closes: #100906
Related: #111204

The samples inner table of a TimeSeries table now has a locality_hash UInt64 column (xxHash64(metric_name)) as the first column of its primary key (ORDER BY (locality_hash, id, timestamp)) and uses index_granularity = 32768, so samples of the same metric are stored close to each other. The tags inner table stores the same hash as a MATERIALIZED column, and the queries generated for evaluating PromQL selectors filter the samples table with (locality_hash, id) IN (SELECT locality_hash, timeSeriesStoreTags(...) FROM tags WHERE <matchers>), pruning granules by the primary key index. Both write paths (INSERT and Prometheus remote write) calculate the hash per time series, and the invariant is validated at CREATE time. Old tables lack the column; once #111204 is merged, TimeSeriesVersion::LATEST and MIN_SUPPORTED_BY_PROMQL will be bumped to 2 in a follow-up commit on this PR.

Changelog category (leave one):

  • Experimental Feature

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

The samples inner table of a TimeSeries table now stores a locality_hash column (xxHash64(metric_name)) as the first column of its primary key and uses index_granularity = 32768; the queries evaluating PromQL selectors use that column to prune granules.

🤖 Generated with Claude Code

…L queries

The samples inner table now has locality_hash UInt64 (= xxHash64(metric_name))
as the first column of its primary key, ORDER BY (locality_hash, id, timestamp),
so samples of the same metric are stored close to each other; the generated
engine also uses index_granularity = 32768. The tags inner table stores the
same hash as a MATERIALIZED column, so the queries generated for evaluating
PromQL selectors (and Prometheus remote read) read it instead of calculating
hashes: they filter the samples table with (locality_hash, id) IN
(SELECT locality_hash, timeSeriesStoreTags(...) FROM tags WHERE <matchers>),
letting the primary key index prune granules. Both write paths (TimeSeriesSink
and the Prometheus remote-write protocol) calculate the hash per time series
and replicate it per sample row; timeSeriesLocalityHash.h is the single source
of truth for the invariant.

The column is required and validated at CREATE time: UInt64 in both tables,
the tags column must be declared MATERIALIZED (or DEFAULT) xxHash64(metric_name)
(any other stored value would make queries silently return no data),
SummingMergeTree samples engines must keep the column in the sorting key, and
locality_hash is a reserved name for tags_to_columns. Older tables lack the
column; once the TimeSeries schema versioning is merged,
TimeSeriesVersion::LATEST and MIN_SUPPORTED_BY_PROMQL must be bumped to 2.

Depends on: #111204

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

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9d577b]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
04651_timeseries_recover_lost_replica FAIL cidb
04651_timeseries_recover_lost_replica FAIL cidb
04651_timeseries_recover_lost_replica FAIL cidb
04651_timeseries_recover_lost_replica FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, 1/3) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
04651_timeseries_recover_lost_replica FAIL cidb
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04627_timeseries_locality_hash FAIL cidb
04628_timeseries_locality_hash_compat FAIL cidb
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, sequential) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
01168_mutations_isolation_3 NOT_FAILED cidb
Stateless tests (amd_debug, sequential) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
Stateless tests (amd_tsan, sequential, 2/2) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
Stateless tests (amd_msan, WasmEdge, sequential, 2/2) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
Stateless tests (amd_tsan, s3 storage, sequential, 2/2) FAIL
04651_timeseries_recover_lost_replica FAIL cidb
Stateless tests (arm_binary, sequential) FAIL
04651_timeseries_recover_lost_replica FAIL cidb

AI Review

Summary

This PR adds optional locality_hash support to TimeSeries samples and tags tables and uses it to prune PromQL selector reads, with compatibility fallbacks for old tables that do not have the column. The selector fallback and both write-path fallbacks look correct in the current code, but the CREATE-time validation still does not enforce the claimed SummingMergeTree safety invariant, so users can still create schemas that silently corrupt or hide samples after background merges.

Findings

❌ Blockers

  • [src/Storages/TimeSeries/normalizeTimeSeriesDefinition.cpp:767-798] The SummingMergeTree validator still accepts unsafe samples layouts because it only checks whether locality_hash appears somewhere in ORDER BY / PRIMARY KEY, and it skips itself entirely whenever the engine has any arguments. That means ReplicatedSummingMergeTree('/zk', '{replica}') ORDER BY (id, timestamp) still slips through because replication parameters are mistaken for an explicit columns_to_sum list, and SummingMergeTree((value)) ORDER BY (locality_hash, id) still slips through even though merges will collapse distinct timestamps into one row. Both cases violate the PR’s contract that CREATE-time validation prevents merge-time corruption. Suggested fix: validate the full merge identity for SummingMergeTree-family samples tables (locality_hash, id, and timestamp all need to be preserved by the sorting key), and distinguish replicated/shared engine parameters from a real columns_to_sum argument instead of treating any argument list as safe.

  • [src/Storages/TimeSeries/normalizeTimeSeriesDefinition.cpp:1147-1177] The same SummingMergeTree guard is only applied to inline inner samples engines. CREATE TABLE ... ENGINE = TimeSeries SAMPLES ext_samples over an external SummingMergeTree table still only checks column types, so an external samples target with ORDER BY (id, timestamp) or any other unsafe key is accepted even though background merges will later corrupt locality_hash or collapse distinct samples. Suggested fix: inspect the resolved engine of external samples targets and apply the same validator there.

Final Verdict

❌ Changes requested. The compatibility fixes for old tables look good, but the SummingMergeTree validation still leaves merge-time data corruption paths open for both inline and external samples tables.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 23, 2026
return;

/// An explicit list of columns to sum is the user's choice, e.g. SummingMergeTree((value)).
if (storage.engine->arguments && !storage.engine->arguments->children.empty())

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.

This return is too broad for the SummingMergeTree family. ReplicatedSummingMergeTree('/zk', '{replica}') (and similar replicated/shared variants) always has non-empty engine->arguments even when the user did not provide an explicit columns-to-sum list, so ORDER BY (id, timestamp) slips through here. The first background merge will then sum locality_hash and selectors will silently miss those rows. Please distinguish replication parameters from the optional summing-columns argument instead of treating any arg list as safe.

if (kind == ViewTarget::Samples)
{
if (auto * samples_engine = create_query.getTargetInnerEngine(kind))
checkSamplesEngineWontSumLocalityHash(*samples_engine, table_id);

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.

We only enforce the SummingMergeTree / locality_hash invariant for inline inner samples engines. SAMPLES ext_samples still goes through the external-target branch above, where we only check column types. That means CREATE TABLE ... ENGINE = TimeSeries SAMPLES ext_samples backed by SummingMergeTree ORDER BY (id, timestamp) is accepted even though merges will later sum locality_hash and make PromQL selectors miss data. The PR description says this invariant is validated at CREATE time, so external samples targets need the same engine check.

@mintlify

mintlify Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 23, 2026, 11:12 PM

nikitamikhaylov added a commit that referenced this pull request Jul 24, 2026
The auto-created `timestamp` and `value` samples columns now carry
`CODEC(DoubleDelta, ZSTD(1))` and `CODEC(Gorilla, ZSTD(1))`, so the
`extract` pattern `\(([^)]*)\)` truncated the `SAMPLES INNER COLUMNS`
block at the first closing parenthesis inside the codec. Anchor the
extraction at `) SAMPLES INNER ENGINE` instead and update the reference.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111697&sha=ec9704295fe958b3049ff9e841cf248d8a907345&name_0=PR&name_1=Fast%20test
PR: #111697

Co-Authored-By: Claude Fable 5 <[email protected]>
/// `SummingMergeTree` sums every numeric column outside the sorting key when it collapses rows,
/// which would corrupt the `locality_hash` column during merges and silently hide the affected
/// samples from PromQL queries. Reject such engines unless `locality_hash` is part of the
/// sorting key or the columns to sum are given explicitly.

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.

SummingMergeTree correctness here is stricter than "keep locality_hash out of the summed columns". The samples table still has to preserve the full sample identity across merges. For example, SAMPLES INNER ENGINE = SummingMergeTree ORDER BY (locality_hash, id) passes this check today, but the first background merge will collapse every timestamp for a series into one row; ORDER BY (locality_hash, timestamp) does the same across different ids. An explicit columns_to_sum list does not rescue those cases because the incomplete sorting key still groups distinct samples together. This validator needs to require id and timestamp in the sorting key as well, not only locality_hash.

@nikitamikhaylov

Copy link
Copy Markdown
Member Author

Moved the two follow-up performance commits out of this PR so it stays focused on locality_hash: the Prometheus API parallelization is now #112108 and the samples-column codecs are #112110 (both rebased onto master).

@nikitamikhaylov
nikitamikhaylov force-pushed the timeseries-samples-locality-hash branch from a74d317 to dab0bd6 Compare July 27, 2026 14:12
nikitamikhaylov added a commit that referenced this pull request Jul 27, 2026
The auto-created `timestamp` and `value` samples columns now carry
`CODEC(DoubleDelta, ZSTD(1))` and `CODEC(Gorilla, ZSTD(1))`, so the
`extract` pattern `\(([^)]*)\)` truncated the `SAMPLES INNER COLUMNS`
block at the first closing parenthesis inside the codec. Anchor the
extraction at `) SAMPLES INNER ENGINE` instead and update the reference.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111697&sha=ec9704295fe958b3049ff9e841cf248d8a907345&name_0=PR&name_1=Fast%20test
PR: #111697

Co-Authored-By: Claude Fable 5 <[email protected]>
nikitamikhaylov and others added 3 commits July 29, 2026 14:34
…eSeries tables

The test test_prometheus_protocols/test_upgrade_from_prealpha.py failed in
#111697 because tables created by
older versions of ClickHouse don't have the `locality_hash` column while the
read and write paths assumed it exists. The original plan was to reject such
tables via the TimeSeries schema versioning (PR #111204); that dependency is
dropped in favor of presence-based compatibility:

- `StorageTimeSeriesSelector` generates the `(locality_hash, id) IN (...)`
  condition only when both the samples and the tags target tables have the
  column, otherwise it falls back to the previous `id IN (...)` filter;
- `TimeSeriesSink` and the Prometheus remote-write protocol fill the column
  only if the samples table has it;
- `checkTargetTable` validates the column (`UInt64` type, and the
  `MATERIALIZED xxHash64(metric_name)` expression in the tags table) only
  when the column is present.

Newly created `TimeSeries` tables still always get the column because
`normalizeInnerTableColumns` adds it to the inner tables at CREATE time.
The new test `04628_timeseries_locality_hash_compat` covers tables without
the column and the mixed cases (only samples / only tags have it).

Co-Authored-By: Claude Fable 5 <[email protected]>
The samples inner table of a newly created TimeSeries table now also has
the `locality_hash` column, so the test added on master in
#112110 lists one more column.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vitlibar

Copy link
Copy Markdown
Member
  1. It seems it's better to rename locality_hash to just locality (without _hash).

  2. locality is similar to id because it's also a hash of some tags. So it seems better to handle it in a similar way. id allows customization, so we can allow customization for locality as well. It makes sense since some users may want to add specific tags to it, for example, 'job' or 'instance'. Also it's good for consistency with id. The idea is to allow a random expression in DEFAULT for the locality column (not just xxHash64), and add time-series setting locality_generator (empty by default - means using the default expression xxHash64(metric_name)).

  3. Also locality can be filled like id is filled: i.e. the default expression first calculated for the "tags" table and then copied to the "samples" table via insertManyFrom()

  4. locality can be added to ORDER BY of the "tags" table, just for correctness:

ORDER BY tuple(metric_name, locality, id)
  1. index_granularity = 32768 looks like a magical constant, better to pass it via time series settings

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 275/281 (97.86%) · Uncovered code

Full report · Diff report

@vitlibar

vitlibar commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

I think if we allow multi-component identifiers (#112799) it will get us actually the same idea of storing samples of the same metrics closer to each others without any compatibility issues. Also multi-component identifiers seems to be a good idea anyway, so I implemented them.

@vitlibar

vitlibar commented Aug 3, 2026

Copy link
Copy Markdown
Member

I moved switching default granularity for the samples inner table to 32768 to a separate PR #113075

This branch was successfully deployed

1 active deployment
staging - docs — b9d577b2 Deployed Aug 1, 2026 by mintlify[bot]
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-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(ts-engine): establish structured series IDs for increased density in primary key

3 participants