Skip to content

Add the Prometheus /federate endpoint - #125250

Merged
vitlibar merged 26 commits into
ClickHouse:masterfrom
valerypetrov:promql-federate
Nov 4, 2026
Merged

vitlibar merged 26 commits into
ClickHouse:masterfrom
valerypetrov:promql-federate

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Adds the Prometheus federation endpoint /federate to the Prometheus HTTP API handler. For every series matched by the match[] 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, the instance label 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:

test case query Prometheus 3.5.0 this PR
one metric match[]=m_a (12 lines) reference byte-identical
stale and out-of-window series 2 lines reference byte-identical
dotted/unicode names 4 lines reference byte-identical
{job="node"}, {__name__=~".+"}, 3 overlapping selectors 25-40 lines reference same lines; series order inside a family differs (Prometheus leaves it unsorted)
no match[] / bad selector 200 empty / 400 200 empty / 400
integration test file 11 cases 11 passed in CI

Changelog category (leave one):

  • New Feature

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

The Prometheus HTTP API now supports the /federate endpoint, so a Prometheus server can scrape the latest samples of selected series from a TimeSeries table.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1314-master (included in 26.11 and later)

valerypetrov and others added 6 commits October 11, 2026 11:03
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]>
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]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a1b6863]

Summary: ✅


AI Review

Summary

Adds /federate to export the latest matching TimeSeries samples as Prometheus text. The current aggregation still exports stale Float32 series as ordinary NaN. Source-table authorization and row-policy bypasses also remain, following an explicit decision to defer them to separate PRs. No genuinely new inline findings were identified; the findings below already have discussion threads.

Findings

❌ Blockers

Tests
  • ⚠️ Add a focused remote-write/federation case for Float32, distinguishing a newest stale marker from ordinary NaN. The current tests use the default Float64 samples.
  • ⚠️ The current head's federation integration results were not available during review; no local ClickHouse binary/build was available. Complete the focused integration run after the latest aggregation and writer changes. The available fast-test result does not establish the HTTP behavior.
Final Verdict

Status: ❌ Block. Fix or explicitly reject Float32 federation and cover that behavior. The two dismissed security findings remain dependent on the separate fixes cited above; safe exposure requires those fixes to cover /federate or an equivalent restriction until they land.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Oct 11, 2026
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]>
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Oct 12, 2026
valerypetrov and others added 4 commits October 13, 2026 10:27
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]>
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
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",

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.

❌ 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.

valerypetrov and others added 2 commits October 14, 2026 10:34
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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

6 object files changed (+106.02 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/makeASTSelectLatestSamples.cpp.o new 90.09 KiB +90.09 KiB

719 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

12 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.
The matched translation units cost +2.7 s (+9%) in total before that adjustment.

Job report

valerypetrov and others added 2 commits October 19, 2026 17:17
/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]>
@mintlify

mintlify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit a1b6863.

Approve preview

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]>
valerypetrov and others added 3 commits October 28, 2026 11:31
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
@vitlibar vitlibar self-assigned this Nov 1, 2026
Comment thread src/Server/PrometheusRequestHandler.cpp Outdated
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"))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please remove checking access here, it's a known gap, it presents in other handlers too, it will be fixed in separate PR #120267

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: removed the access check from the handler, together with the integration tests that covered it.

Comment on lines +1099 to +1105
/// `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());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)

@vitlibar vitlibar Nov 3, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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, "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Instead of argMax and max - it's better to use functions timeSeriesLastToGrid and timeSeriesTimestampOfLastToGrid because they were designed for time series.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Try using writeScalar instead of writeFederateValue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

valerypetrov and others added 2 commits November 3, 2026 11:05
… query with timeSeries*ToGrid in a helper

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)

@vitlibar vitlibar Nov 3, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We don't need to test older versions

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master ef3ab708d

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.17% 93.17% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 682 -> 682 (+0) 16 -> 16 (+0) 34 -> 34 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@valerypetrov

Copy link
Copy Markdown
Contributor Author

It looks like all the review threads are addressed. @vitlibar, could you please recheck once you have time?
Thank you for the review!

@vitlibar
vitlibar added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit 84451f1 Nov 4, 2026
186 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 13, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... external Author is not a member of the ClickHouse organization pr-feature Pull request with new product 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