Repository navigation
Add the Prometheus /federate endpoint - #125250
Conversation
A Prometheus server can now scrape a TimeSeries table through /federate: for each series matched by the match[] selectors it returns the latest sample of the last 5 minutes in the text exposition format, like Prometheus 3.5.0 (stale markers dropped, families sorted by metric name, an empty instance label added, underscore name escaping, Go float format). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Do not write a trailing comma when the series already has an instance label, and skip empty blocks of the result. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A failed /federate request kept the text exposition Content-Type over its JSON error body; the error path now sets application/json like the other endpoints. The test now takes its timestamps after the cluster starts, so a slow startup cannot push the samples out of the 5-minute window. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [a1b6863] Summary: ✅
AI ReviewSummaryAdds Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block. Fix or explicitly reject |
clang-tidy rejects `return f(...)` in a void function and `find() != npos` where `contains` works. The tag loops now also take the start offset of the row once, like `writeTags` does, so the first row reads no offset before it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master now parses every SQL query that the Prometheus HTTP API generates without the request's dialect and parser limits (serverGeneratedQueryFlags). The /federate query was added before that and still used empty flags, so `dialect=kusto`, a small `max_query_size` or `max_parser_depth` in the URL made it fail with 400. Use the same flags as the other endpoints. The test also pins that a label name with ':' is written as is, like Prometheus does: expfmt keeps any name that passes IsValidLegacyMetricName. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
| String sql_query = fmt::format( | ||
| "SELECT timeSeriesIdToTags(id) AS tags, argMax(value, timestamp) AS last_value, " | ||
| "toUnixTimestamp64Milli(toDateTime64(max(timestamp), 3)) AS last_timestamp FROM ({}) GROUP BY id " | ||
| "HAVING reinterpretAsUInt64(toFloat64(last_value)) != 0x7FF0000000000002 ORDER BY arrayFirst(tag -> tag.1 = '__name__', tags).2, tags", |
There was a problem hiding this comment.
❌ The stale-marker filter does not work for supported Float32 samples.
A TimeSeries table can store samples Array(Tuple(DateTime64(3), Float32)). Remote write inserts the incoming double into that value column, narrowing the dedicated stale marker before this query reads it. Widening it with toFloat64 cannot restore its original payload: a focused SQL check produced 0x7FF8000000000000 after the Float32 round trip, rather than 0x7FF0000000000002, so this predicate returned 1.
Consequently, a series whose latest remote-written sample is a stale marker is emitted as ordinary NaN, violating the endpoint's promise to omit stale series. The current test exercises only the default Float64 schema. Please preserve a distinguishable stale marker for this storage type and filter it appropriately, or explicitly reject/document the unsupported schema for federation. Add a Float32 remote-write/federation case that also distinguishes ordinary NaN from staleness.
…uery argMax(value, timestamp) took an arbitrary sample when the newest timestamp of a series had several. The instant query keeps a real value over a NaN or a stale marker and then the greatest value, so /federate could export a different value or drop a live series. Order by (timestamp, not NaN, value) to follow that rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+106.02 KiB total), 1 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units12 translation units recompiled, 36 s compile time in total, 11 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
/federate resolved the table and read it through the target tables without checking the source table grant. A user with only the target-table grants could read the samples, and a missing table answered differently from an existing one. The check now runs before the lookup, so both cases give the same access error. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
Prometheus 3.5.0 checks label names against the legacy metric name rule
(prometheus/common v0.65.0 EscapeMetricFamily uses IsValidLegacyMetricName
for labels too), so with the default underscores escaping a label `a:b`
stays `a:b` and only characters like '.' become '_'. Measured on the
Prometheus 3.5.0 binary: `colon_metric{"a:b"="x","c.d"="y"}` is federated
as `colon_metric{a:b="x",c_d="y",...}`. Go back to one name rule for
metric and label names and pin both cases in the test.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`/federate` checked `SELECT` on the source `TimeSeries` table, but read the samples through `timeSeriesSelector`, whose `StorageTimeSeriesSelector::readImpl` queries the target tables directly. A row policy defined on the `TimeSeries` table itself was therefore never applied, so a user whose direct `SELECT` returned no rows could still export those samples and labels via `/federate`. The policy is expressed over the columns of the `TimeSeries` table and cannot be applied to the target tables as is, so `federate` now throws `ACCESS_DENIED` when `getEffectiveRowPolicyFilter` reports a row policy on the `TimeSeries` table, like `mergeTreeIndex` does. Row policies of the target tables keep being applied by the query that reads them. Related: ClickHouse#125250 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a change of `id_generator` the old rows keep their identifiers, so the same tags can have two identifiers. `GROUP BY id` exported such a series twice, and when the newest sample of the new identifier was a stale marker, it still exported the older live sample of the old identifier. Group by `timeSeriesIdToGroup(id)` and take the tags from `timeSeriesGroupToTags`, as the instant query and remote read do, so the newest-sample and stale-marker rules apply to the whole series. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's timeSeriesSelector now takes a sixth argument `return_columns`
('samples' or 'timestamp_and_value') and reads five arguments as
`table, selector, min_time, max_time, return_columns`. /federate passed the
database and the table as two arguments without it, so after the merge the
call was read with shifted arguments and every /federate request failed.
It now asks for 'timestamp_and_value', which gives one sample per row for
both the bucketed and the one-sample-per-row tables.
The test waited for 9 rows in timeSeriesData, but a bucketed samples table
keeps one row per series and bucket, so it now counts the samples.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Server/PrometheusRequestHandler.cpp
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
| if (!Poco::URI(uri).getPath().ends_with("/format_query")) | ||
| { | ||
| /// Check the grant before the lookup, so a missing table gives the same error as an existing one. | ||
| if (Poco::URI(uri).getPath().ends_with("/federate")) |
There was a problem hiding this comment.
Please remove checking access here, it's a known gap, it presents in other handlers too, it will be fixed in separate PR #120267
There was a problem hiding this comment.
Done: removed the access check from the handler, together with the integration tests that covered it.
| /// `timeSeriesSelector` reads the samples and the tags from the target tables, so a row policy of the `TimeSeries` table | ||
| /// itself is not applied there. Federation is refused instead of exporting the rows such a policy hides. | ||
| if (getEffectiveRowPolicyFilter(*time_series_storage, getContext())) | ||
| throw Exception(ErrorCodes::ACCESS_DENIED, | ||
| "Cannot federate the table {} because a row policy is applied on it. " | ||
| "The /federate endpoint reads the samples from its target tables, so it cannot apply the row policy", | ||
| storage_id.getNameForLogs()); |
There was a problem hiding this comment.
Please remove this check. Handling of row policies must be fixed, not rejected. It's a known gap, other handlers have it too, will be fixed separately (maybe #127035)
There was a problem hiding this comment.
Done: removed the row policy check and its integration test.
| finishExecutedQuery(io, query_finish_callback); | ||
| } | ||
|
|
||
| void PrometheusHTTPProtocolAPI::federate(WriteBuffer & response, const Strings & match_params, QueryFinishCallback query_finish_callback) |
There was a problem hiding this comment.
File PrometheusHTTPProtocolAPI.cpp is already quite big, let's create a helper function building AST in a separate file:
ASTPtr makeASTSelectLatestSamples(
const StorageID & time_series_storage_id,
const Strings & selectors,
DateTime64 time,
Decimal64 lookback_delta,
UInt32 time_scale);
There was a problem hiding this comment.
Done: the query is now built by makeASTSelectLatestSamples() in src/Storages/TimeSeries/makeASTSelectLatestSamples.{h,cpp} with the suggested signature. It takes the selectors, the time, the lookback delta and the time scale, and returns the query as an AST. federate() only formats it and executes it.
| /// Like the instant query, the samples are grouped by `timeSeriesIdToGroup`, because different identifiers can have | ||
| /// the same tags (after a change of `id_generator` the old rows keep their identifiers), and they are one series. | ||
| String sql_query = fmt::format( | ||
| "SELECT timeSeriesGroupToTags(group) AS tags, argMax(value, (timestamp, NOT isNaN(value), value)) AS last_value, " |
There was a problem hiding this comment.
Instead of argMax and max - it's better to use functions timeSeriesLastToGrid and timeSeriesTimestampOfLastToGrid because they were designed for time series.
There was a problem hiding this comment.
Done: argMax/max are replaced by timeSeriesLastToGrid and timeSeriesTimestampOfLastToGrid on a one-point grid at now with a 5 minute window. The window is now left-open like in the instant query, (now - 5m, now]. I could only compile-check this, so CI is the first run of the integration tests.
| } | ||
|
|
||
| /// Writes a sample value like Go's strconv.FormatFloat(value, 'g', -1, 64), which the Prometheus text format uses. | ||
| void writeFederateValue(Float64 value, WriteBuffer & out) |
There was a problem hiding this comment.
Try using writeScalar instead of writeFederateValue
There was a problem hiding this comment.
Done: writeFederateValue is removed and the values are written with writeScalar. As a consequence a value like 1234567 is now written as 1234567 instead of Go's 1.234567e+06; both are valid in the text format and parse to the same number. I updated the expected output in test_federate_text_format.
… query with timeSeries*ToGrid in a helper Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
|
|
||
| /// Writes a metric or label name with the "underscores" escaping, the default of the Prometheus text format: | ||
| /// like Prometheus, each character not allowed in a legacy metric name ([a-zA-Z_:][a-zA-Z0-9_:]*) becomes '_'. | ||
| void writeFederateName(std::string_view name, WriteBuffer & out) |
There was a problem hiding this comment.
Actually we've implemented something like this already, in PrometheusMetricsWriter. Let's use it, we can make function writePrometheusLabelValue in PrometheusMetricsWriter.cpp public, and replace function replaceInvalidChars there with the following function:
void writePrometheusLabelName(std::string_view name, WriteBuffer & out)
{
for (size_t pos = 0; pos < name.size();)
{
char first_byte = name[pos];
bool valid = isAlphaASCII(first_byte) || (first_byte == '_') || (first_byte == ':') || (isNumericASCII(first_byte) && pos > 0);
writeChar(valid ? first_byte : '_', out);
/// A multi-byte character is replaced as a whole; a sequence cut off at the end of the name is not read past it.
pos += std::min<size_t>(UTF8::seqLength(static_cast<UInt8>(first_byte)), name.size() - pos);
}
}
then use it instead of replaceInvalidChars to escape metric or label name in PrometheusMetricsWriter.cpp.
The existing check in PrometheusMetricsWriter.cpp:
if (!replaceInvalidChars(key))
continue;
is actually redundant, it never returned false
There was a problem hiding this comment.
Done: writePrometheusLabelName and writePrometheusLabelValue (the old writeLabelValueEscaped) are now public in PrometheusMetricsWriter, and /federate uses them. replaceInvalidChars and its redundant checks are removed, so PrometheusMetricsWriter.cpp escapes names with writePrometheusLabelName too. One side effect: a name whose first characters are digits used to have them stripped, now each is replaced by _.
| stale = "reinterpretAsFloat64(toUInt64(9218868437227405314))" | ||
| old, new = f"fromUnixTimestamp64Milli({ms(60)})", f"fromUnixTimestamp64Milli({ms(30)})" | ||
| # Version 9 is the latest one which allows changing `id_generator`. | ||
| node.query("CREATE TABLE prometheus_idgen ENGINE=TimeSeries SETTINGS version = 9") |
There was a problem hiding this comment.
We don't need to test older versions
There was a problem hiding this comment.
Done: removed test_federate_after_id_generator_change. I also changed the fed_mem sample in the text format test from 0.00001 to 0.25: after switching to writeScalar the old expected output 1e-05 failed in CI.
…he id_generator federate test Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
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. |
|
It looks like all the review threads are addressed. @vitlibar, could you please recheck once you have time? |
…ated from PromQL" This reverts commit 4d76414 (ClickHouse#128764), reversing changes made to 8886954. ClickHouse#129565 fixed the staging of the adaptive aggregator that made the grid aggregation of the SQL generated from PromQL slower, so that SQL can use the aggregator again. The conflict in the includes of PrometheusHTTPProtocolAPI.cpp is resolved by keeping `Server/PrometheusMetricsWriter.h`, added later by ClickHouse#125250. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Adds the Prometheus federation endpoint
/federateto the Prometheus HTTP API handler. For every series matched by thematch[]selectors it returns the newest sample of the last 5 minutes in the Prometheus text format (0.0.4), skipping series whose newest sample is a stale marker, so a Prometheus server can scrape ClickHouse. Name escaping, label order, theinstancelabel and the float format follow Prometheus. The Accept header is not negotiated (always text with underscore escaping), native histograms are not served and the lookback is fixed at 5 minutes.Measured against Prometheus 3.5.0 with the same remote-write payload (30 float series with edge values, stale markers, dotted/unicode names, escaped label values) sent to both:
match[]=m_a(12 lines){job="node"},{__name__=~".+"}, 3 overlapping selectorsmatch[]/ bad selectorChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The Prometheus HTTP API now supports the
/federateendpoint, so a Prometheus server can scrape the latest samples of selected series from aTimeSeriestable.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/125250]
Version info
26.11.1.1314-master(included in26.11and later)