Skip to content

Add schema versioning to the TimeSeries engine and a version guard to the PromQL layer - #111204

Merged
vitlibar merged 3 commits into
masterfrom
timeseries-schema-versioning
Sep 5, 2026
Merged

vitlibar merged 3 commits into
masterfrom
timeseries-schema-versioning

Conversation

@nikitamikhaylov

@nikitamikhaylov nikitamikhaylov commented Jul 21, 2026 •

Copy link
Copy Markdown
Member

The TimeSeries table engine and the PromQL execution layer are under active development: the set of the target tables and their structure will change. Instead of supporting every historical schema in the PromQL layer, each TimeSeries table now stores an explicit schema version in the new version engine setting, stamped into the CREATE query when the table is created and persisted in the table metadata. The PromQL layer declares the minimum version it supports (TimeSeriesVersion::MIN_SUPPORTED_BY_PROMQL); queries over older tables are rejected with an error asking to re-create the TimeSeries table and copy the data with an INSERT-SELECT query from the old table into the new one. Tables newer than the server (possible after a downgrade) can still be attached and dropped, but reads, writes (INSERT, Prometheus remote write) and ALTER are rejected with an error asking to upgrade ClickHouse.

Changelog category (leave one):

  • Improvement

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

TimeSeries tables now store an explicit schema version in the version engine setting. The PromQL execution layer supports only a declared range of versions and rejects queries over tables outside that range with an instructive error.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/111204]

Version info

  • Merged into: 26.9.1.788 (included in 26.9 and later)

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

clickhouse-gh Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f9c515d]

Summary: ✅


AI Review

Summary

This PR adds explicit version pinning to TimeSeries, splits schema guards by SELECT/write/PromQL, and allows attaching future-version tables so they can be inspected or dropped. The contract is still incomplete: one new ON CLUSTER path keeps a schema-affecting default unpinned, and several previously reported schema-race issues remain in the PromQL and remote-write paths despite being resolved in GitHub.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:3484-3488] prepareOnClusterQuery now pins version for old distributed_ddl_entry_format_version workers, but it still leaves recent_samples_ttl_seconds to be normalized independently on each host. normalizeTimeSeriesDefinition later freezes that default into metadata too, so a mixed-version cluster using the old DDL entry format can still create different TimeSeries layouts and TTLs from the same CREATE ... ON CLUSTER once the default changes. Suggested fix: fully normalize TimeSeries creates on the initiator for the old entry format, or at least pin recent_samples_ttl_seconds here alongside version.
  • [src/Storages/StoragePrometheusQuery.cpp:191-195, src/Storages/StorageTimeSeriesSelector.cpp:820-864, src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp:184-205] [dismissed by author -- https://github.com/Add schema versioning to the TimeSeries engine and a version guard to the PromQL layer #111204#discussion_r3621452851, https://github.com/Add schema versioning to the TimeSeries engine and a version guard to the PromQL layer #111204#discussion_r3660788497, https://github.com/Add schema versioning to the TimeSeries engine and a version guard to the PromQL layer #111204#discussion_r3621452856] The PromQL paths still validate only the version after re-resolving the table, while SQL generation continues to use parse-time or constructor-time types and time bounds. A DETACH/edit/ATTACH that keeps the table version but changes time_series or id types can therefore build casts and timestamp predicates for the old layout against the new table. Suggested fix: after re-resolving the current TimeSeries storage, refresh the current metadata-derived types and recompute any parsed bounds before building SQL.
  • [src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:301-326] [dismissed by author -- https://github.com/Add schema versioning to the TimeSeries engine and a version guard to the PromQL layer #111204#discussion_r3927626508] The remote-write guard still runs only in the constructor. write then derives the insert block from the cached storage object and metadata, so a DETACH/ATTACH or DROP/ATTACH between validation and write can target a different current table with stale column types. Suggested fix: re-resolve the storage in write, rerun checkTimeSeriesVersionIsWritable, and rebuild metadata from that fresh storage before creating the block.

⚠️ Majors

  • [src/Storages/TimeSeries/normalizeTimeSeriesDefinition.cpp:1324-1399, tests/queries/0_stateless/04612_timeseries_version_setting.sql:40-46] [dismissed by author -- https://github.com/Add schema versioning to the TimeSeries engine and a version guard to the PromQL layer #111204#discussion_r3927626502] Fresh CREATE TABLE ... ENGINE = TimeSeries SETTINGS version = 0 is explicitly accepted, but inner-column and engine generation is still always the latest layout. That means version no longer uniquely identifies the schema, so a future bump of MIN_WRITABLE or MIN_SUPPORTED_BY_PROMQL will also strand tables this server created with the current layout. Suggested fix: either reject non-latest explicit versions on fresh CREATE, or make schema generation genuinely version-aware.
Tests
  • ⚠️ Add a focused CREATE ... ON CLUSTER regression with distributed_ddl_entry_format_version < 3 proving that every schema-affecting TimeSeries default is frozen on the initiator, not re-derived on workers.
  • ⚠️ Add a focused race-style test, or a smaller unit around configuration refresh, for the PromQL and remote-write entry points that reattaches the table with different time_series or id types between configuration and execution.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: pin all schema-affecting TimeSeries defaults consistently for old ON CLUSTER DDL formats, and refresh current storage metadata in the PromQL and remote-write execution paths instead of reusing parse-time or constructor-time schema state.

LLVM Coverage Report

Measured on commit f9c515d.

Metric Baseline Current Δ
Lines 88.70% 88.80% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 214/243 (88.07%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 21, 2026
@mintlify

mintlify Bot commented Jul 21, 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 21, 2026, 10:47 AM

Comment thread src/Storages/StoragePrometheusQuery.cpp Resolved
@nikitamikhaylov

Copy link
Copy Markdown
Member Author

@vitlibar this one is ready for review. I have other PRs depending on this one, so please review this first.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.40% 86.30% +5.90%
Functions 91.40% 92.00% +0.60%
Branches 72.30% 78.40% +6.10%

Changed lines: Changed C/C++ lines covered: 165/179 (92.18%) · Uncovered code

Full report · Diff report

nikitamikhaylov added a commit that referenced this pull request Jul 29, 2026
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Dear @vitlibar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@vitlibar vitlibar self-assigned this Sep 2, 2026
@vitlibar

vitlibar commented Sep 2, 2026

Copy link
Copy Markdown
Member

I'll finish this PR

@vitlibar
vitlibar force-pushed the timeseries-schema-versioning branch from de1c178 to 82643b9 Compare September 3, 2026 08:22
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f9c515dfe with master d1adb9f9f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

52 object files changed (+344.61 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/AggregationPushdown.cpp.o new 278.38 KiB +278.38 KiB
src/CMakeFiles/dbms.dir/Storages/TimeSeries/TimeSeriesVersion.cpp.o new 33.66 KiB +33.66 KiB

716 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

346 translation units recompiled, 2812 s compile time in total, 343 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/Optimizations/Cascades/Rules/AggregationPushdown.cpp: 7.6 s

Job report

@vitlibar

vitlibar commented Sep 3, 2026

Copy link
Copy Markdown
Member

I reworked the TimeSeries schema versioning, changes:

  • Tables created before the version setting existed are considered as version 0: a definition without the setting is upgraded to version = 0 on ATTACH, and the prealpha and no-recent-samples upgrades run only for version 0. TimeSeriesVersion::INITIAL is removed.

  • The minimum version is split by operation: MIN_SUPPORTED (SELECT and replaying a CREATE TABLE on another node), MIN_WRITABLE (INSERT and remote write) and MIN_SUPPORTED_BY_PROMQL, all 0 for now.

  • The checks also guard TRUNCATE, OPTIMIZE, BACKUP and RESTORE.

  • A table with an unsupported version (for example after a downgrade) is attached without normalizing its definition: only the identifiers of the target tables are read, so it can be inspected and dropped while every operation over it is rejected. Low-level accessors such as timeSeriesSamples keep working.

  • For ON CLUSTER queries with an old DDL entry format the initiator pins its latest version, so hosts running different releases create the table with the same version. Queries with an AS clause take the version from the other table.

@vitlibar
vitlibar force-pushed the timeseries-schema-versioning branch from 84bfd37 to 88a3ed4 Compare September 4, 2026 08:59
@vitlibar
vitlibar force-pushed the timeseries-schema-versioning branch from cf66c32 to 7ea1f5e Compare September 4, 2026 16:41
@vitlibar
vitlibar added this pull request to the merge queue Sep 5, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 5, 2026
nikitamikhaylov and others added 3 commits September 5, 2026 10:55
… the PromQL layer

The TimeSeries table engine and the PromQL execution layer are under active
development: the set of the target tables and their structure will change.
Instead of supporting every historical schema in the PromQL layer, each
TimeSeries table now stores an explicit schema version, and the PromQL layer
declares the minimum version it supports.

- New TimeSeries engine setting `version` (default 1, pinned forever to the
  pre-versioning schema). `normalizeTimeSeriesDefinition` stamps
  `version = TimeSeriesVersion::LATEST` into the CREATE query AST at CREATE
  time, so the version persists in the table metadata, in the DDL log of
  Replicated databases, and in backups. `SECONDARY_CREATE` keeps the
  initiator's value; a version newer than the latest known one is always
  rejected, and a primary CREATE requires the latest version. The setting
  cannot be changed by `ALTER`.

- The PromQL layer (the `prometheusQuery`, `prometheusQueryRange` and
  `timeSeriesSelector` table functions, the `promql` dialect, and the
  Prometheus HTTP query API) checks that the version of the table is within
  [`TimeSeriesVersion::MIN_SUPPORTED_BY_PROMQL`, `TimeSeriesVersion::LATEST`]
  and otherwise throws `INCOMPATIBLE_SCHEMA` with an error asking to
  re-create the TimeSeries table and copy the data with an INSERT-SELECT
  query from the old table into the new one (or to upgrade ClickHouse when
  the table is newer than the server).

- `StorageTimeSeries` now keeps the settings from the create query in the
  in-memory metadata, so `ALTER TABLE ... MODIFY SETTING` no longer drops
  unrelated settings (including the version pin) from the stored table
  definition.

Co-Authored-By: Claude Fable 5 <[email protected]>
Fixes found by an adversarial review of the previous commit:

- RESTORE: `compareRestoredTableDef` now treats a definition stamped with the
  initial version and a definition without the `version` setting as the same
  definition, so a backup made before versioning was introduced can be
  restored into a re-created (stamped) table and vice versa.

- ON CLUSTER: hosts executing a distributed DDL entry run with mode `CREATE`
  (only Replicated databases use `SECONDARY_CREATE`), so the strict
  "new tables must have the latest version" check now exempts replays
  detected via `is_ddl_or_on_cluster_internal`, mirroring
  `already_normalized_on_initiator` in `InterpreterCreateQuery`. Without this
  a rolling upgrade would break `CREATE ... ON CLUSTER` after a version bump.

- Fail close on writes and alters: `INSERT`, the Prometheus remote-write
  protocol, and `ALTER` now reject a table whose version is newer than the
  latest version known to the server - an older server must not modify data
  which only a newer server understands. Reads were already rejected.

- `ALTER ... RESET SETTING` which removes the last override is now persisted:
  the rebuilt SETTINGS clause pins the `version` setting to stay non-empty,
  because `applyMetadataChangesToCreateQuery` does not replace the stored
  clause with an empty list and the reset would silently revert on restart.

- Duplicate entries in a stored SETTINGS clause are collapsed (last one wins)
  when copied into the metadata, so ALTER no longer resolves settings to a
  stale duplicate.

- `version = 0` is now rejected at CREATE and at replays of prepared queries,
  and the CREATE-time rejection explains the case when the version was copied
  by the `AS other_table` clause (where "omit the setting" is not actionable).

- The Prometheus HTTP query API reports the version-guard rejection as
  HTTP 500 with `errorType` "internal" instead of 400 "bad_data", so clients
  don't attribute it to the PromQL expression.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vitlibar
vitlibar force-pushed the timeseries-schema-versioning branch from 7ea1f5e to f9c515d Compare September 5, 2026 09:01
/// With an old DDL entry format the query is shipped un-normalized, so hosts running different releases
/// of ClickHouse would pin different latest versions. Pin the initiator's one here, like the UUIDs above.
/// A query with an AS clause is left alone: the hosts take the settings, including the version, from the other table.
if (create.is_time_series_table && create.as_table.empty() && !hasExplicitTimeSeriesSettingVersion(create))

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.

version is not the only TimeSeries default that later gets frozen into metadata. normalizeTimeSeriesDefinition also pins recent_samples_ttl_seconds when it is omitted, but this helper only runs when version itself is missing. With distributed_ddl_entry_format_version < NORMALIZE_CREATE_ON_INITIATOR_VERSION, a mixed-version CREATE ... ON CLUSTER that specifies version but omits recent_samples_ttl_seconds will still let each worker freeze its own default TTL, so the same DDL can produce different RECENT SAMPLES retention and layout across hosts.

Please either fully normalize TimeSeries CREATE queries on the initiator for the old entry format, or pin recent_samples_ttl_seconds here alongside version.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master d1adb9f9f

Metric Baseline Current Δ
Score 81.82% 81.82% +0.00%
Passed 441 441 +0
Failed 3 3 +0
Unsupported 95 95 +0

Note: score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@vitlibar
vitlibar added this pull request to the merge queue Sep 5, 2026
Merged via the queue into master with commit 3855066 Sep 5, 2026
344 of 345 checks passed
@vitlibar
vitlibar deleted the timeseries-schema-versioning branch September 5, 2026 15:05
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026

This branch was successfully deployed

1 active deployment
staging - docs — f9c515df Deployed Sep 5, 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-improvement Pull request with some product 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