Skip to content

TimeSeries: Split the tags table into new tags table without min_time, max_time and new time ranges table - #121924

Merged
vitlibar merged 12 commits into
ClickHouse:masterfrom
vitlibar:timeseries-split-tags-table
Oct 14, 2026
Merged

vitlibar merged 12 commits into
ClickHouse:masterfrom
vitlibar:timeseries-split-tags-table

Conversation

@vitlibar

@vitlibar vitlibar commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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

Split the tags table into new tags table without columns min_time, max_time and new time ranges table.


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

Version info

  • Merged into: 26.10.1.2420-master (included in 26.10 and later)

@vitlibar vitlibar added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Sep 24, 2026
@vitlibar
vitlibar force-pushed the timeseries-split-tags-table branch from 9cb4fab to 7bb7437 Compare September 24, 2026 12:18
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e11e2bc]

Summary: ✅


AI Review

Summary

Adds an optional TIME RANGES target to version 8 TimeSeries tables, moving timestamp bounds out of tags and joining them during selection. ❌ Block: five previously reported concerns still hold at commit e11e2bc68ee310ed3d8ec7006e9f62e391b2ec99, including an authorization bypass and selectors that reject or hide valid samples. No additional inline findings were identified.

Findings

❌ Blockers

  • src/TableFunctions/TableFunctionTimeSeries.cpp:166: timeSeriesTimeRanges exposes protected storage without table authorization. parseArguments resolves the source and target, structure resolution exposes columns, and execution returns the real target storage. The select planners and InterpreterInsertQuery delegate table-function authorization to an implementation that checks no table privileges. A user with CREATE TEMPORARY TABLE but no source/target grants can read and insert through this function; DESCRIBE also discloses metadata. Check privileges before resolving protected objects and authorize reads and inserts separately. The existing target-function siblings share this gap.

  • src/Storages/TimeSeries/TimeSeriesIDRange.cpp:186: Inferred bounds omit conversion to the physical id type. With id_type = 'Tuple(String, UInt64)' and id_generator = 'tuple(sipHash64(metric_name), sipHash64(tags))', inserts convert the numeric prefix to String, but selector bounds retain UInt64. The time-ranges join compares incompatible types and raises NO_COMMON_TYPE; catching the optional probe's exception does not protect the main query. Cast the substituted prefix to its declared component type before constructing either predicate.

  • src/Storages/TimeSeries/TimeSeriesIDRange.cpp:171: Nullable prefixes silently discard valid series. Range inference accepts Tuple(Nullable(UInt64), UInt64). A generator such as tuple(if(metric_name = 'm', NULL, sipHash64(metric_name)), sipHash64(tags)) produces a NULL prefix for m. Both inferred range comparisons and the outside-range escape then evaluate to NULL, removing matching series that the existing id-set path can select. Exclude nullable prefixes from inference or implement null-safe predicates.

  • src/Storages/TimeSeries/normalizeTimeSeriesDefinitionImpl.cpp:2231: An implicitly created empty time-ranges target hides existing external samples. [dismissed by author -- https://github.com/TimeSeries: Split the tags table into new tags table without min_time, max_time and new time ranges table #121924#discussion_r4205742219] The author deferred this to a follow-up, but a new table pointing to populated external samples/tags still loses those samples during pruning; direct external writes also leave bounds incomplete. Disable implicit range pruning for external samples unless consistent bounds are supplied. Verify this with recent samples disabled to isolate the new behavior.

⚠️ Majors

Tests
  • ⚠️ Add focused stateless coverage for denied read, structure, and insert access through timeSeriesTimeRanges, plus successful operations with the required grants.
  • ⚠️ Add selector regressions for converted and nullable id prefixes, visibility of pre-existing external samples with recent_samples_ttl_seconds = 0, and rejection of swapped aggregate functions. The current tests do not exercise these boundaries.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so the identified paths were traced statically without executing reproductions. Focused tests against the PR binary would close this gap.
  • ⚠️ Targeted integration jobs failed during test selection because CIDB was unavailable, leaving those runs without test evidence. A successful rerun would close this gap.
Final Verdict

❌ Block. Add table-function authorization, preserve physical types and nullable semantics in inferred ranges, preserve external-sample visibility, and reject incorrect aggregate wrappers. Cover these boundaries with focused stateless tests.

Comment thread src/Parsers/CreateQueryUUIDs.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e11e2bc68ee310ed3d8ec7006e9f62e391b2ec99 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

@vitlibar
vitlibar force-pushed the timeseries-split-tags-table branch 2 times, most recently from 980adc4 to b0d041c Compare October 2, 2026 18:00
@vitlibar
vitlibar marked this pull request as ready for review October 3, 2026 08:49
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

This PR adds the TimeSeries TIME RANGES target and moves the setting-value conversion helpers into their own file. None of that runs during ClickBench or TPC-H SELECT execution. ClickBench Q20 shows -42.3% with CPU time roughly halved. Its delta is large and consistent enough that the verdict is locked, but nothing in the diff explains it, so treat it as a likely difference between the base and the PR head and check it against an exact-base baseline before crediting this PR. ClickBench Q31 (+19.1%, flat CPU) stays suppressed because it sits inside master's normal variance band, which matches the diff.

clickbench

🟢 1 improved · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 127 -42.3% <0.0001 cpu: -42.3% with CPU time roughly halved, so the drop is backed by real work. This diff only touches TimeSeries DDL parsing and setting conversion, not the scan or string-matching path, so the gain is probably a difference between the base and the PR head.
⚠️ 31 not_sure 257 306 +19.1% <0.0001 aggregation: +19.1% falls inside master's current variance band and CPU time is flat. No code this query runs is changed, so the suppression stands.

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: 9609289c-5bd7-41e9-b9f2-55d62799ad8b
  • MIRAI run: 46dde5c8-e11b-463b-aa9e-f45a1b6f32e1
  • PR check IDs:
    • clickbench_84186_1791938287
    • clickbench_84288_1791938291
    • clickbench_84403_1791938297
    • tpch_adapted_1_official_84523_1791938343
    • tpch_adapted_1_official_84666_1791938370
    • tpch_adapted_1_official_84689_1791938371

@vitlibar

vitlibar commented Oct 5, 2026

Copy link
Copy Markdown
Member Author

@groeneai Analyze CI failures

@kirillshokhin kirillshokhin self-assigned this Oct 5, 2026
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

Both failures are unrelated to this PR. Both come from the master this run was built against.

  1. Build (amd_fuzzers): linking clickhouse_fuzzer fails with relocation R_X86_64_PC32 out of range in libclang_rt_asan.a(sanitizer_stackdepot.cpp.o). This is the master-wide overflow fixed by Leave the SanitizerCoverage PC table out of the fuzzer build #123738 (merged 2026-10-04 01:14 UTC), and Build (amd_fuzzers) has been green on master since then. This run is a re-run (attempt 2), so it built the original merge commit e6aa677 again (this head merged into master 04249b5 from 2026-10-03 17:29 UTC). That CMakeLists.txt does not have the fix yet.

  2. Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant: the view reads the table nested instead of the WITH alias (view 10 instead of 100). Since Make LLVM coverage opt-in in pull requests, run the same configurations on arm_binary #122853 moved the DBReplicated jobs to arm_binary with randomized settings, this test has failed in 205 runs of this job across 188 PRs, and it passes in the amd_llvm_coverage DBReplicated job. Revert "Make LLVM coverage opt-in in pull requests, run the same configurations on arm_binary" #123789 reverted Make LLVM coverage opt-in in pull requests, run the same configurations on arm_binary #122853 on master, and Revert "Revert "Make LLVM coverage opt-in in pull requests, run the same configurations on arm_binary"" #123790 re-lands it together with the fix in ApplyWithSubqueryVisitor. This PR does not touch WITH alias handling.

Re-running will not help, because a re-run reuses the same merge commit. Merging master, or any new push, picks up #123738 and the revert, and that should clear both.

probe_select_ids->setExpression(ASTSelectQuery::Expression::TABLES, makeTablesInSelectQuery(make_intrusive<ASTTableIdentifier>(tags_table_id)));
probe_select_ids->setExpression(ASTSelectQuery::Expression::WHERE, std::move(probe_where));
}
ASTPtr probe_select_ids_query = applyTimeRangeFilterToSelectIDsQuery(

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.

AFAIU, we get the query like this: SELECT 1 FROM (SELECT id FROM time_ranges WHERE <range> AND id IN (SELECT id FROM tags WHERE <counterexample>)) LIMIT 1. LIMIT 1 never reaches the counterexample set building query, so we pay for building a set of all the counterexamples ever written, which may be costly for narrow queries.

Would it make sense to build the following shape:

SELECT 1
FROM (SELECT id FROM tags WHERE metric_name = '<metric_name>' AND NOT (<other matchers>)) AS t
INNER JOIN (SELECT id FROM time_ranges WHERE <window> AND <metric's id range>) AS r ON t.id = r.id
LIMIT 1
SETTINGS join_algorithm = 'full_sorting_merge', optimize_read_in_order = 1
  1. It stops after the first counterexample found. We need to pin join_algorithm and optimize_read_in_order to make it happen, though.
  2. The memory needed is bounded.
  3. We have to read both sides in full if there's no counterexample, but in this case the optimization is applicable, so it compensates. Moreover, I expect that whole-metric optimization is not the most common case.
  4. If there's no counterexample we still have to check that there are no ids from the non-canonical generator:
SELECT 1 FROM time_ranges
WHERE max_time >= <start> AND min_time <= <end>
  AND id IN (SELECT id FROM tags WHERE metric_name = '<metric_name>' AND tupleElement(id, 1) != sipHash64('<metric_name>'))
LIMIT 1

In my local benchmarks two sequential queries are faster than a single query with UNION ALL or embedding the "old-generator" check into the JOIN arms.

The same shape could also be used for the main select query, also avoiding building the whole unfiltered ids set and storing it with timeSeriesStoreTags. The overhead is significant when the metric churn is real, i.e. when there are a lot of rows rejected by the timeframe. There's a VictoriaMetrics' benchmark[Link] that considers the following pattern typical for k8s workloads: 1% of targets relabelled every 10 mins, so each target is relabelled every 1000 mins. In 30 days at this churn rate we have (active + retired) / active = ~44, so for 25k active series we get 1.1m series total and unfiltered set includes all of them.
In my local benchmarks the JOIN shape loses to the current shape only if the whole-metric optimization is applicable and the selector has matchers other than the metric name.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea! I updated the PR with implementation of it, with some small differences: I used LEFT JOIN instead of INNER JOIN (because id generator is allowed to be changed)

@kirillshokhin kirillshokhin 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.

I'm also fine with merging this PR as is, but I'd expect a performance regression in the ClockBench.
I plan to add a new column to the time_ranges table in #122051 and to rework the way tags are collected, so we can benchmark and optimize once it's merged and the selector has its more-or-less final shape.

/// The time ranges target is on by default and disabled by an explicit `store_time_ranges = 0` (tables of earlier versions have no such target).
const bool time_ranges_enabled = settings.isTimeRangesTargetEnabled();

if (!time_ranges_enabled)

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.

If an empty time_ranges table is generated and not-empty external samples table is supplied, we will hide the existing series in timeSeriesSelector if the whole metric optimization is not applicable, and always in makeSelectIDsQuery. Thus the same series will be present in one selector and disappear in another. Any direct write to the external samples table will also break the consistency. Does it make sense to enable internal time_ranges table only for internal samples table? For external samples table we could disable the time_ranges by default and reject queries with explicit inner table or store_time_ranges = 1.
Same is also true for the recent_samples table for queries fitting into the TTL window.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it makes sense, we can disable time ranges and recent samples external tables by default, in case they are not declared explicitly. But probably in another PR, since changing recent samples is not related to this PR

@vitlibar

Copy link
Copy Markdown
Member Author

@kirillshokhin I think we can merge it, and then I'll address your comments in a follow-up PR

@vitlibar
vitlibar added this pull request to the merge queue Oct 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 12, 2026
@vitlibar
vitlibar force-pushed the timeseries-split-tags-table branch from 6c85350 to 8741613 Compare October 13, 2026 14:52
@vitlibar
vitlibar force-pushed the timeseries-split-tags-table branch from 8741613 to e11e2bc Compare October 13, 2026 20:43
```
)DOCS_MD", .category = FunctionDocumentation::Category::TableFunction}, SecretArgumentsSpec{});

factory.registerFunction<TableFunctionTimeSeriesTarget<ViewTarget::TimeRanges>>(

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.

[P1] Check table privileges before exposing the time-ranges target

This registration inherits an authorization gap in TableFunctionTimeSeriesTarget: parseArguments resolves the source and target without a table privilege check, getActualTableStructure returns its columns, and executeImpl returns the real target storage. Both select planners deliberately skip authorization for table-function nodes because they expect ITableFunction::execute to check it, but that method only checks source-engine/temporary-table privileges here. InterpreterInsertQuery likewise skips the target INSERT check for INSERT INTO FUNCTION.

Consequently, a user with CREATE TEMPORARY TABLE but no grants on either table can read the protected target through SELECT * FROM timeSeriesTimeRanges(secret.ts) and insert arbitrary rows through INSERT INTO FUNCTION timeSeriesTimeRanges(secret.ts); DESCRIBE also exposes its structure. Please check the relevant table privileges before exposing the source/target and cover the read, structure, and insert entrypoints with negative access tests. The existing target-function siblings share this gap, so reusing their implementation does not supply authorization.

{
TimeSeriesIDRange range;
/// Substitute the metric name for the `metric_name` column, for example sipHash64(metric_name) -> sipHash64('my_metric').
range.first_component = first_component->clone();

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.

[P1] Convert inferred bounds to the physical first-component type

The sink converts the result of id_generator to id_type, but this helper retains the generator's original first-component type. For example, this is a valid configuration:

ENGINE = TimeSeries
SETTINGS id_type = 'Tuple(String, UInt64)',
         id_generator = 'tuple(sipHash64(metric_name), sipHash64(tags))',
         recent_samples_ttl_seconds = 0

An insert converts the numeric hash to a String. A subsequent timeSeriesSelector(ts, 'm', 0, 100) instead generates time-range bounds with numeric sipHash64('m'). Comparing the stored tuple to those bounds, or its first component to the outside-range escape, raises NO_COMMON_TYPE for String versus UInt64. The probe catches its own error, but the main time-ranges join repeats the invalid comparison, so supported custom ids become unreadable. The previous optimization skipped this custom generator.

Please cast the substituted first component to its declared physical type before constructing either predicate, and add a selector regression test. Independently checked on ClickHouse 26.10.1.448: the tuple cast succeeds, while both emitted comparison shapes raise NO_COMMON_TYPE.

if (!first_component || !dependsOnMetricNameOnly(first_component))
return {};

/// The identifiers must be two-component tuples: the range spans the whole second component.

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.

[P1] Skip range inference for nullable first components

Only the second physical component is validated here, so range inference also accepts Tuple(Nullable(UInt64), UInt64). This is a supported comparable, top-level non-nullable id type; it can be used with Memory inner targets, for example. A valid generator such as tuple(if(metric_name = 'm', NULL, sipHash64(metric_name)), sipHash64(tags)) gives metric m ids with a NULL prefix.

For selector m, the inferred bounds become (NULL, 0) through (NULL, UINT64_MAX). Their comparisons evaluate to NULL, discarding every matching row from the time-ranges subquery. The escape predicate tupleElement(id, 1) != NULL also evaluates to NULL, so the outer filter rejects the series and existing samples silently disappear from the result. This differs from the original id-set path, which can match a tuple containing a nested NULL.

Please exclude nullable first components from this optimization or implement null-safe predicates, with a selector regression test. Casting the generated prefix to the physical type alone will not fix this case.

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master ce8b083de

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@vitlibar
vitlibar added this pull request to the merge queue Oct 14, 2026
Merged via the queue into ClickHouse:master with commit 46379b2 Oct 14, 2026
856 of 869 checks passed
@vitlibar
vitlibar deleted the timeseries-split-tags-table branch October 14, 2026 23:27
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 15, 2026
…uted

Master moved TimeSeriesVersion.h to src/Parsers/Prometheus and replaced the
min_time/max_time tags columns with a time ranges table (ClickHouse#121924). The
Prometheus HTTP series query now uses master's time-ranges filtering on the
TimeSeries table this branch resolves from the stored storage pointer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 15, 2026
Since ClickHouse#121924 a new TimeSeries table also has a ".inner_id.timeranges" table that
every insert writes to. The test did not stop merges on it, and its name check still
passed because it only looked for the tables it already knew. Stop merges there too,
and fail if any inner table that takes inserts is missing from the stopped list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 15, 2026
…grams-storage

Master added the optional "time ranges" target table (ClickHouse#121924), which now
holds min_time and max_time instead of the tags table, and moved the
CREATE-query setting helpers to Parsers/Prometheus/CreateQueryTimeSeriesSettings.

The histograms target becomes the third optional target: it is counted by
countTimeSeriesInnerTables, gets its UUID through the new
isTimeSeriesHistogramsTargetEnabled helper, and a histogram-only time series
now gets a row in the time ranges table, so selectors filtering by time still
find it. The tests read min_time and max_time from timeSeriesTimeRanges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 15, 2026
Master moved min_time and max_time out of the tags table into a separate time
ranges table (ClickHouse#121924) and changed this test's fixture to match. The series that
this PR adds still inserted five values into the tags table, which now has three
columns, so the module fixture failed and no test in the file ran.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
feiyunwill pushed a commit to feiyunwill/ClickHouse that referenced this pull request Oct 16, 2026
…t_prometheus_protocols

test_multiple_instant_vectors failed on an unrelated PR (amd_tsan, targeted):
the Prometheus "reader", which gets its data from ClickHouse via RemoteRead,
returned the two `http_errors` series swapped relative to the "receiver".

An instant vector has no defined series order. ClickHouse answers RemoteRead
with `GROUP BY timeSeriesIdToGroup(id)` and no ORDER BY, so the series come
in the order the tags were read, and Prometheus v3.7.3 passes that order
through for an instant vector (only matrices are sorted). Since ClickHouse#121924 this
order varies between requests: locally the reader returned the series
swapped in 80/600 requests with master 6caeb45 and 0/600 with 5a7acf9, its
predecessor. `http_api_response_close_to` compared by raw string (eps == 0)
or by index (eps > 0), so an order-only difference failed the test.

`http_api_response_close_to` gets `ordered=True`; `ordered=False` sorts the
series of a "vector" result by labels on both sides first. It is used only
for the reader-vs-receiver comparison. `execute_query_in_prometheus` now
returns the receiver's result, and `do_query_test` compares that strictly
with the expected result, so an order PromQL defines (for example `topk`,
`bottomk` or the `sort` functions) is still checked against Prometheus.
ClickHouse's own results are still compared strictly. The unused
`expect_error` parameter of `execute_query_in_prometheus` is removed,
because the unordered comparison cannot compare error text.

With the master CI binary of the base commit, the test fails 8/50 runs
before the change and passes 100/100 after; the whole test_evaluation.py
module passes 36/36.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit to amosbird/ClickHouse that referenced this pull request Oct 16, 2026
…he split `TimeSeries` tags table

After ClickHouse#121924 a `TimeSeries` table has a different set of
inner tables (the tags table is a `ReplacingMergeTree` ordered by `(metric_name, id)`, and there is an
`AggregatingMergeTree` ordered by `id`). The test still shows that each inner table is created once with
the reversed key (for `ts`) and once with the original key (for `mv_ts`); only the reference was stale.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=94017&sha=latest&name_0=PR&name_1=Fast%20test
PR: ClickHouse#94017

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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.

4 participants