Repository navigation
Support PromQL over a Distributed table of TimeSeries shards - #117170
valerypetrov wants to merge 172 commits into
Conversation
A PromQL query could only be evaluated against a local TimeSeries table. Every
entry point resolved its target through storagePtrToTimeSeries(), a typeid_cast
that rejected anything else, so a Distributed table over per-shard TimeSeries
tables was refused with UNEXPECTED_TABLE_ENGINE and there was no way to query
several nodes with PromQL.
Raw samples are now selected on every shard and the PromQL is evaluated on the
initiator, so the answer equals evaluating the same query against one table
holding all the data. The selector leaf becomes
SELECT timeSeriesTagsToGroup(tags) AS group, timestamp, value
FROM cluster(<cluster>, view(
SELECT timeSeriesIdToTags(id) AS tags, timestamp, value
FROM timeSeriesSelector(<remote db>, <remote table>, ...)))
and nothing above the leaf changes, because every operator there consumes only
(group, timestamp, value). Evaluating the PromQL per shard and concatenating
instead would be silently wrong: `sum by (job)` would return one fully-formed row
per shard rather than a total, and there is no re-aggregation step to fix it.
timeSeriesTagsToGroup() has to stay in the outer query. Groups are dense integers
assigned per node in order of first appearance, so inside the view each shard
restarts its own counter and unrelated series collapse into one group with no
error. An empty remote database means each shard's own default database, so the
database argument is then omitted rather than resolved on the initiator, which
would be wrong under cross-replication.
Writes needed only the guard relaxed: the block is built from the target's
declared columns and inserted as an ordinary INSERT, which a Distributed target
routes by its sharding key to each shard's local TimeSeries table.
Refused with a clear message rather than answered wrongly: the /api/v1/series,
/api/v1/labels and /api/v1/metadata endpoints, which read the tags table directly
and need a separate cross-shard set union; the remote read protocol, whose
GROUP BY timeSeriesIdToGroup(id) would be pushed down into the same node-local
group problem; a Distributed over a table function, and one built by
ENGINE = Remote(...), neither of which names a cluster that can be resolved.
The table functions timeSeriesData/Samples/Tags/Metrics keep rejecting a
Distributed argument, since "give me the inner table" has no single answer.
The previous commit put timeSeriesTagsToGroup() directly on top of the cluster() call and claimed that was enough to evaluate it on the initiator. It is not, and the claim in that commit message is wrong. With the function directly above cluster(), the query above it is stage-Complete, so it ships to the shards: EXPLAIN PLAN shows a bare ReadFromRemote outputting `group`, with nothing running on the initiator. Each shard then restarts its own node-local counter, and unrelated series collapse into one group. Measured on a two-shard cluster with six distinct series split 4/2: the centralised reference gives six groups, this shape gives four. Downstream it is not even a quiet wrong answer - timeSeriesGroupToTags() on the initiator fails with "Group 1 is out of bounds", because nothing populated the collector there. Wrapping the cluster() call in its own view() leaves the outer SELECT on the initiator, which is where the collector lives. The same measurement then returns six, matching the centralised reference, and holds under aggregation, as a CTE, and with prefer_localhost_replica = 0. cluster()'s direct argument is still a view(), so the initiator still skips analysis of the shard query rather than trying to resolve the shard-local table locally.
|
Workflow [PR], commit [ab9698d] Summary: ❌
AI ReviewSummaryThe PR adds PromQL evaluation and synchronous Prometheus remote write through The distributed-target consumers are Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Close the local inner-table late-denial path and add the focused regression above. |
The rewrite to cluster(view(timeSeriesSelector(...))) drops the user-named wrapper before the planner ever sees it, so nothing enforced SELECT on the wrapper and a row policy on it was silently bypassed rather than applied. checkPrometheusQueryDistributedRead now runs at both read entry points - the table function and the HTTP query endpoints - checking the SELECT grant and failing closed with NOT_IMPLEMENTED on any row policy, which the rewritten query could not apply faithfully. The generated cluster() call also cannot carry the wrapper's DistributedSettings, so a table declaring skip_unavailable_shards (or a non-default mode) would behave differently through a prometheus query than through a plain SELECT - ClusterProxy::executeQuery forwards exactly these settings on the normal path. resolvePrometheusQueryTarget refuses such tables for now; forwarding them the way executeQuery does is the better end state and can replace the refusal. No tests yet on purpose: whether the settings answer is refusal or propagation is still a review question, and the fixtures differ.
05055 failed only on the distributed-plan flavor, whose users.d profile
sets serialize_query_plan = 1: the generated
cluster(<name>, view(timeSeriesSelector('ts_local', ...))) is then planned
on the initiator and shipped as plan fragments, so the unqualified table
name binds to the initiator's current database instead of each shard's own
default database - UNKNOWN_TABLE on
test_cluster_two_shards_different_databases, reproducible 33/33. The
classic path passes on the same sha because shipping the query text lets
every shard resolve the name in its session database, which is what a
Distributed table with an empty database argument means.
The cluster-level SELECT now carries SETTINGS serialize_query_plan = 0,
and only when the wrapper leaves the database empty: with an explicit
database the shard query is fully qualified and the serialized plan
resolves it correctly everywhere, so the flavor keeps its path.
SelectQueryBuilder learns an optional settings_changes clause for this,
rendered the standard way (a non-standalone ASTSetQuery).
… ref 81d0fd6 called StorageDistributed::getDistributedSettingsRef(), which is private - the fast build rejected it while the local syntax harness, resolving headers against its reference tree, let it through. The refusal only cares what the table DECLARES anyway, and the declared changes are public metadata: read settings_changes and refuse on the two shard-skipping names, naming the offending setting in the message.
5ef2dc0 called getInMemoryMetadataPtr() with no arguments from the context-less resolver; on this branch the method takes (ContextPtr, bool) and its handle forbids arrowing a temporary, so the fast build rejected both. The refusal moves into checkPrometheusQueryDistributedRead, which has the context, takes the storage itself now, and binds the metadata handle to a local the way every other caller in the PR does. Both fast-build breaks in this function came from trusting the reference tree's headers; every member this commit touches was checked against this branch's own headers instead.
Two over-broad refusals from the wrapper checks, narrowed on review: An always-true row policy (USING 1) restricts nothing, so the rewrite preserves behavior exactly; the null-only test refused it anyway. Gated on isAlwaysTrue() the way StorageMerge and the MergeTree index storages already do. The settings refusal keyed on presence, so declaring the Distributed default explicitly (skip_unavailable_shards = 0) was refused too. The declared changes are now applied to a DistributedSettings and the two read-path values compared against defaults; only a real divergence refuses. Four new arms pin both edges of both guards: always-true policy passes, real filter fails closed, declared default passes, non-default fails closed.
Three review findings on the guards, one commit. The engine-classification refusals ran before any access check on every protocol surface - the metadata endpoints, the remote-read constructor, and the HTTP API constructor - so a caller without SELECT could fingerprint a hidden table as a Distributed wrapper from NOT_IMPLEMENTED instead of getting ACCESS_DENIED. PrometheusRequestHandler does getTable with no check of its own, so each refusal now checks AccessType::SELECT on the storage id first. The settings refusal compared the table's declarations against defaults, but ClusterProxy::executeQuery applies declarations only when the query has not set the setting itself, and the generated cluster() call sees query settings either way. The refusal now fires exactly when the reads would diverge: the query leaves the setting unset and the declaration differs from the query's current value. SETTINGS skip_unavailable_shards = 0 on the query now reads a declaring wrapper, and a new arm pins it.
The write path had the same error-before-auth oracle the read surfaces had: WriteImpl resolves the table and the constructor classifies its engine before any INSERT check runs, so an unprivileged caller probing /api/v1/write could distinguish the engine-specific refusals from ACCESS_DENIED. The constructor now checks AccessType::INSERT on the storage id first, mirroring the SELECT-before-classify fix on the read and query paths.
The mode controls which exceptions shard skipping ignores, so with the flag effectively off it cannot change behavior - yet mode_diverges compared it unconditionally, refusing a wrapper that declares only the mode, and one whose declared skipping the query explicitly turns off. The comparison is now gated on the normal path's effective flag (the query's value when set, the declaration otherwise). When the flag itself diverges the skip check refuses regardless, and when it does not, that value is common to both paths, so gating on it is exact: a declared mode still refuses when skipping is actually active and the modes differ. New arm: a mode-only declaration reads fine.
The SELECT check lived only in the Distributed branch, so the SQL entrypoints - prometheusQuery through getConfiguration, and the timeSeriesSelector table function at both of its resolution sites - read a plain TimeSeries table with no grant check at all, while the HTTP API enforced it in its constructor. The check now runs on every path, right where the table is resolved, since the evaluation reads the table's data through generated queries the planner never attributes to this name. additional_table_filters aimed at the wrapper is refused for a Distributed target: the normal read remaps the entry onto the source table (ClusterProxy::executeQuery), but the generated cluster() call reads through a view the planner does not attribute to the wrapper, so the filter would silently vanish and return rows a plain SELECT would hide. Remapping it the way ClusterProxy does is the better end state; until then a matching non-empty entry fails closed, pinned by a new arm.
The SELECT check landed after storagePtrToTimeSeries, whose UNEXPECTED_TABLE_ENGINE throw is itself a pre-auth engine oracle - the same shape fixed on the protocol surfaces. Both entrypoints now resolve the table, check the grant, then cast.
The PR promises /api/v1/write through a Distributed table and nothing exercised it. The new integration case is self-contained: its own instance with a write and a query handler on the wrapper, a two-shard localhost cluster with per-shard default databases, TimeSeries tables on both shards, and a wrapper sharded by the host tag. It sends eight series over the protocol, flushes the Distributed queue, and asserts every sample landed exactly once with both shards non-empty, then reads the data back through prometheusQuery in SQL and count() over the HTTP query handler. Eight fixed host labels make the hash split deterministic per binary, so the both-shards assertion cannot flap between runs.
Three review findings, one gate order everywhere: grant, existence, engine, policy. The SELECT checks sat after DatabaseCatalog::getTable, so a caller without the right could still tell a hidden table from a missing one by the ACCESS_DENIED / UNKNOWN_TABLE split - on prometheusQuery*, on timeSeriesSelector, and on every HTTP surface with dynamic table selection, where the handler resolved the name before any check. The grant is now checked on the resolved id before the catalog lookup at all of them (INSERT on the write path), and the constructor checks stay as depth. timeSeriesSelector also read the inner tables with no look at the TimeSeries table's row policy, while a plain SELECT applies it through makeASTSelectFromTimeSeries - so PromQL could return rows SQL hides. A non-trivial policy now fails closed at both entrypoints, the same idiom as the Distributed wrapper guard; applying the filter instead remains possible follow-up work.
Three findings, one helper. checkTimeSeriesWrapperReadContract refuses a non-trivial row policy and a matching additional_table_filters entry, and every rewrite surface calls it: the Distributed guard, both timeSeriesSelector entrypoints (closing the filter half of the local bypass), and the metadata endpoints, which derived series and labels from the inner tables past the wrapper's policy and filters even on a local target. The key matching now mirrors PlannerJoinTree exactly - short name only from the same current database, full unquoted name from anywhere - so a short key aimed at a table in another database no longer refuses a read the planner would never filter. Arms pin the local fail-closed and the cross-database pass.
The block is filled with the column types the table declared when the write started. An ALTER of a Distributed wrapper between that point and the INSERT gives the pipeline new types, and the pipeline takes the old columns without checking them, so a retyped column reached a cast on the wrong column type. The write now compares the block with the INSERT header and refuses a mismatch with a retryable INCOMPATIBLE_SCHEMA before pushing any row. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… declare A Distributed table on the first hop forwards insert_expected_column_types to its shards without checking them itself. A table-wide INSERT grant on a wrapper that declares fewer columns than its shard table let a key name a column only the shard has, and the shard, checking as the cluster user, confirmed it or reported its type. The wrapper now refuses any key it does not declare before forwarding. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The table was checked against one metadata snapshot before the SELECT was planned, while the conversion and the sinks take their own snapshots later. An ALTER that ran in between (e.g. while url() inferred its schema) let a Memory table changed from UInt64 to UInt8 take the insert and store 300 as 44. Checking the expectations once more after the pipeline is built refuses it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A metadata-only write over a Distributed wrapper needs only INSERT on the four metadata columns, but it still set insert_expected_column_types for the samples column, and the INSERT then asked for SHOW COLUMNS on it. A caller granted only the metadata columns got a permanent 403. The samples expectation now applies only when the request carries samples. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `parallel_distributed_insert_select`, an INSERT SELECT from a `*Cluster` source into a replicated table, or one run with parallel replicas, is sent to other nodes as a whole. `insert_expected_table_engine` and `insert_expected_column_types` were already checked and consumed on the initiator by then, so a requirement set in the session or a profile never reached the nodes that insert into their own tables. Such an INSERT now runs on the initiator, into the table that was checked. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A Distributed table sends every column it declares, with the default of each one the insert leaves out, and the shard converts it. Remote write checked the types of the columns it fills only, so a samples-only write over a wrapper declaring `type Int64` sent the type '0' with no family name, which the shard refuses as incorrect data: a permanent 400 that makes Prometheus drop the batch. Every outer column the wrapper declares is now held to the type a TimeSeries table has. A column the write leaves out may be one the caller has no grant on, so its refusal does not name it. Co-Authored-By: Claude Fable 5.2 <[email protected]>
An Alias table has the columns of its target, and a grant on the alias shows them all. A user with INSERT on the alias and no grant on a column of the target could name that column in insert_expected_column_types and read its type from the INCOMPATIBLE_SCHEMA error, before the write through the alias asked for the grant on the target. DESCRIBE and system.columns already ask for SHOW COLUMNS on every table the alias resolves through; so does the INSERT now. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…he shards The requirements an INSERT states are checked on the table it names and then consumed. An Alias table over a Distributed one still passed the INSERT SELECT to its target, which sends the query text to the shards: with parallel_distributed_insert_select = 2 a shard got insert_expected_table_engine = 'Alias' for its own table and refused the insert. The table's own distributed write is now skipped as well once the requirements are consumed, like the other two ways of handing the insert over. Co-Authored-By: Claude Fable 5.2 <[email protected]>
AI review of a later commit does not approve the PR, see the AI Review comment.
PromQL Compliance ReportBaseline: S3 master
Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream Note: Prometheus compliance score is unchanged vs baseline. |
… its defaults The refusal of a Distributed table whose samples type differs from its shards' named both types to any caller. A metadata-only writer holds no grant on that column, so it now gets the refusal without the column and its types. The check that asks for INSERT on a shard this server writes in-process split the request block as sent. A metadata-only block has no `tags`, so a sharding key that reads them could not be evaluated and every shard counted as written: a caller without a grant on the local shard was refused a write that goes to the remote one. The block is now completed with the defaults the insert fills in before the key is evaluated. Co-Authored-By: Claude Fable 5.2 <[email protected]>
… not deterministic The check that asks for `INSERT` on a shard this server writes in-process evaluated the defaults of the columns a request leaves out, but the insert evaluates them again. With a sharding key that reads a column with a default like `toString(rand64())`, the two evaluations could route the rows differently, and a caller without the local grant got a late refusal after a remote shard had committed its part. Such a default now counts every shard as receiving rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rite check Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master moved to 26.12, so the settings history check requires the two new settings, `insert_expected_table_engine` and `insert_expected_column_types`, to be recorded under the current version. Move their records from 26.11 to 26.12. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A remote write over a Distributed table maps an `ACCESS_DENIED` raised by a shard's own insert after the shard-target check to a retryable status, but only when it was a remote exception. A shard that is the initiator itself is written in-process on the caller's context, so its denial is a local exception and was answered 403, which Prometheus drops instead of resending. The local denial is now retryable exactly when the grant the check asked for on the shard-local table (INSERT on the columns the sink sends) is no longer held: that is a grant revoked between the check and the insert, and the resent batch is refused with 403 by the check, before any shard is written. A denial while that grant is still held stays 403: the wrapper's own grant revoked in the same window, or a grant the check does not cover, such as INSERT on the inner tables of the shard-local TimeSeries table. Those are permanent for the caller, and a retryable status would make Prometheus resend the batch forever. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
PromQL queries can now be evaluated against a
Distributedtable over per-shardTimeSeriestables, so a Prometheus query can span several ClickHouse nodes. Prometheus remote write can write through such a table too. New settingsinsert_expected_table_engineandinsert_expected_column_typesmake anINSERTrefuse a table with another engine or other column types.A PromQL query could only be evaluated against a local
TimeSeriestable. Every entry point resolved its target throughstoragePtrToTimeSeries(), atypeid_castthat rejects anything else, so aDistributedtable over per-shardTimeSeriestables was refused withUNEXPECTED_TABLE_ENGINE. Plain SQL through such a table already worked; only the PromQL layer did not.How it evaluates
Raw samples are selected on every shard and the PromQL is evaluated on the initiator, so the answer equals evaluating the same query against a single table holding all the data. The selector leaf becomes:
Nothing above the leaf changes, because every operator there consumes only
(group, timestamp, value).Evaluating the PromQL per shard and concatenating would be silently wrong.
sum by (job)translates to a complete aggregation, not a partial state, so each shard would return one fully-formed row perjobit happens to hold and the pipeline has no re-aggregation step to combine them — the response would carry duplicate series and the true total nowhere. The same applies totopk, quantiles, and binary vector matching, whose join is shard-local.Two details are load-bearing:
cluster()call needs its ownview()around it. Groups are dense integers assigned per node in order of first appearance and the collector is never serialised. PuttimeSeriesTagsToGroup()directly abovecluster()and the query above it is stage-Complete, so it ships to the shards —EXPLAIN PLANshows a bareReadFromRemoteoutputtinggroup— and each shard restarts its own counter, collapsing unrelated series into one group. Measured on two shards with six series split 4/2: six groups centrally, four that way, six with the extraview().Writes build the block from the target's declared columns and insert it as an ordinary
INSERT, which aDistributedtarget routes by its sharding key to each shard's localTimeSeriestable. Before that, every replica is asked whether its shard-local table is aTimeSeriestable with the wrapper's samples type (on an internally replicated shard, one verified replica is enough). If one is not, the write is refused withUNEXPECTED_TABLE_ENGINEorINCOMPATIBLE_SCHEMA; if one cannot be checked, withALL_CONNECTION_TRIES_FAILED. The insert runs in the foreground with async insert off, so no batch waits on the initiator after that check, andinsert_shard_idandinsert_distributed_one_random_shardare refused.Two new settings,
insert_expected_table_engineandinsert_expected_column_types, make anINSERTrefuse a table with another engine or other column types. Remote write sets them, so a shard-local table swapped after the check still refuses the batch. They work for anyINSERT; aDistributedtable passes them on to its shards. A replica on an older server checks neither these settings nor the selector's grants, so reads and remote write over it fail with a retryable5xxuntil it is upgraded.Refused rather than answered wrongly
/api/v1/series,/api/v1/labels,/api/v1/label/<name>/values,/api/v1/metadata— these read the tags table directly and need a separate cross-shard set union.GROUP BY timeSeriesIdToGroup(id)would be pushed into the shards and hit the same node-local group problem.Distributedwhose target is a table function, and one built byENGINE = Remote(...); neither names a cluster that can be resolved.timeSeriesData/timeSeriesSamples/timeSeriesTags/timeSeriesMetricskeep rejecting aDistributedargument, since "give me the inner table" has no single answer.A
Distributedwhose shard-local table is itselfDistributedis not rejected up front — from the initiator only the remote name is known, and a local catalog lookup would be wrong under cross-replication. It still fails, fromtimeSeriesSelectoron the shard.This also changes a plain
TimeSeriestable: the PromQL selector now needsSELECTon theTimeSeriestable itself, and refuses withNOT_IMPLEMENTEDwhile a row policy or a restrictiveadditional_table_filtersentry applies to it, because it reads the inner tables directly and would not apply them. The/api/v1/series,/api/v1/labels,/api/v1/label/<name>/valuesand/api/v1/metadataendpoints refuse the same way.Test
05055_promql_over_distributedshards oncityHash64(tags['host'])rather than on the metric name, so the series of one metric land on different shards and the aggregations genuinely cross them — with a metric-name key every query would be answerable by a single shard and the merge would never be exercised. Bothjobvalues of metricmstraddle the two shards. The expected values are taken from evaluating the same PromQL against a localTimeSeriestable holding the same five series, which is the contract this change has to satisfy.The HTTP endpoints, remote write, the access checks and the shard checks are covered by the new
test_*_distributed.pyintegration tests intests/integration/test_prometheus_protocols, and the two new settings by05099_insert_expected_table_engine.Workflow [PR]
Sync PR [sync-upstream/pr/117170]