Repository navigation
TimeSeries: Split the tags table into new tags table without min_time, max_time and new time ranges table - #121924
Conversation
9cb4fab to
7bb7437
Compare
|
Workflow [PR], commit [e11e2bc] Summary: ✅
AI ReviewSummaryAdds an optional Findings❌ Blockers
Tests
Missing context / blind spots
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. |
7bb7437 to
512c87d
Compare
a1d3658 to
43d4c5c
Compare
Build profile diff (arm_release)Commit See the job log for details. |
980adc4 to
b0d041c
Compare
|
📊 Cloud Performance Report 🟢 AI verdict: 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 · Flagged queries (2 of 43)
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
|
|
@groeneai Analyze CI failures |
|
Both failures are unrelated to this PR. Both come from the master this run was built against.
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( |
There was a problem hiding this comment.
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
- It stops after the first counterexample found. We need to pin
join_algorithmandoptimize_read_in_orderto make it happen, though. - The memory needed is bounded.
- 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.
- 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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
|
@kirillshokhin I think we can merge it, and then I'll address your comments in a follow-up PR |
…vious id generator
…for min_time and max_time
… the filter lines of the plan only
…ist of alternatives
6c85350 to
8741613
Compare
8741613 to
e11e2bc
Compare
| ``` | ||
| )DOCS_MD", .category = FunctionDocumentation::Category::TableFunction}, SecretArgumentsSpec{}); | ||
|
|
||
| factory.registerFunction<TableFunctionTimeSeriesTarget<ViewTarget::TimeRanges>>( |
There was a problem hiding this comment.
[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(); |
There was a problem hiding this comment.
[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 = 0An 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. |
There was a problem hiding this comment.
[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.
PromQL Compliance ReportBaseline: S3 master
Note: Prometheus compliance score is unchanged vs baseline. |
46379b2
…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]>
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]>
…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]>
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]>
…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]>
…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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Split the
tagstable into newtagstable without columnsmin_time,max_timeand newtime rangestable.Workflow [PR]
Sync PR [sync-upstream/pr/121924]
Version info
26.10.1.2420-master(included in26.10and later)