Repository navigation
Conversation
…dpoints The Prometheus HTTP API had placeholder implementations for the series, labels, and label-values endpoints that threw NOT_IMPLEMENTED. This makes them functional by querying the TimeSeries tags table: - /api/v1/series: Returns all series with their full label sets by querying metric_name and tags from the tags table. Supports optional match[] parameter for metric name filtering. - /api/v1/labels: Returns all unique label names by extracting distinct keys from the tags Map column. Always includes __name__ as a virtual label. Supports optional match[] filtering. - /api/v1/label/<name>/values: Returns distinct values for a specific label. For __name__, queries the metric_name column directly. For other labels, extracts values from the tags Map column. These endpoints are required for Grafana's Prometheus data source to function properly (label autocomplete, metric browser, etc.).
|
|
|
Please sign the CLA. |
|
Workflow [PR], commit [0126adf] Summary: ❌
AI ReviewSummaryThis PR fills out the Prometheus metadata endpoints for the Findings
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 744/782 (95.14%) · Uncovered code |
|
/rerun |
|
Corporate CLA is signed. |
|
@ajonkisz: greetings, I'm the product manager for PromQL support and the TimeSeries table engine. I'm happy to see this contribution through and attribute it to you if you were to resolve the merge conflicts. If you would like me to take it over, solve the conflicts, shepherd it through CI, and get it merged, I can also do that. |
…api-endpoints # Conflicts: # src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp
- `getLabelValues`: the `__name__` branch produced no `WHERE` clause, yet a
non-empty `match[]` parameter appended ` AND ...`, yielding invalid SQL
(`... FROM table AND metric_name = ...`). Collect conditions into a list and
emit `WHERE`/`AND` correctly so the query is valid in every branch.
- JSON-escape all label names and values written by `getSeries`, `getLabels`,
and `getLabelValues` using `writeJSONString`, matching `writeTags`. Raw
`writeString` of column data could emit invalid JSON when a value contained a
quote, backslash, or control character.
- Quote string literals interpolated into the generated SQL with `quoteString`
instead of bare `'{}'`, so metric names and label names containing a quote no
longer break the query.
- Use a raw string literal for the `__name__` JSON prefix (`modernize-raw-string-literal`).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `tags` column of the tags target table is a `Map`, which materializes as `ColumnMap`, not `ColumnArray`. The previous `typeid_cast<const ColumnArray *>` always failed, so `getSeries` silently dropped every label and `/api/v1/series` returned only `__name__`. Read the nested array via `ColumnMap::getNestedColumn` and `ColumnMap::getNestedData` instead. The tags target is usually `AggregatingMergeTree`/`ReplacingMergeTree` and stores a row per write, so the same series can appear multiple times until parts are merged. Use `SELECT DISTINCT` to deduplicate by series identity, and drop the arbitrary `LIMIT 10000` that silently truncated the result. Also remove the now-unused `NOT_IMPLEMENTED` error code (fixes the style check). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…meter `request.getURI()` includes the query string, so a request such as `/api/v1/label/host/values?match[]=cpu_usage` no longer ended with `/values` and fell through to a 404 before `getLabelValues` was reached. Route on the path component (the URI with the query string stripped) instead. `match[]` was not reserved in `QueryAPIImpl::isSettingLikeParameter`, so it was treated as a ClickHouse setting in `makeContext` and a request like `/api/v1/series?match[]=cpu_usage` failed with an unknown-setting error. Reserve `match[]` so it is handled as an endpoint parameter. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `setup` fixture never created the `prometheus` `TimeSeries` table, so every test errored with `Table default.prometheus does not exist` (the remote-write endpoint returned 404). Create the table before sending test data. The `/api/v1/label/<name>/values` handler rule used `<url>/api/v1/label/*/values</url>`, but the URL filter matches non-regex values exactly (`*` is a literal, not a wildcard), so dynamic label names never matched and the endpoint returned 404. Use a `regex:` rule instead. Add regression tests covering the fixes: `/api/v1/series` now returns the full label set, `match[]` filtering works, `/api/v1/label/<name>/values?match[]=...` routes correctly with a query string, and series are deduplicated. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…api-endpoints # Conflicts: # src/Parsers/Prometheus/tests/gtest_PromQLParser.cpp # src/Server/PrometheusRequestHandler.cpp # src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp # src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.h
The branch explicitly rejected the `lookback_delta` parameter while it was not implemented. `master` now implements it for `/api/v1/query` and `/api/v1/query_range`, so the explicit rejection (an auto-merged semantic conflict) would have disabled the new feature. Keep rejecting only the still-unimplemented `timeout` and `stats` parameters, and update the test and the documentation accordingly. Co-Authored-By: Claude Fable 5 <[email protected]>
…tadata endpoints
Three findings of the AI review on `79a7ea14bb9c`:
1. `getLimitParam` read the `limit` parameter with `params->get("limit", "")`, so a
present-but-empty `limit=` was indistinguishable from an omitted one and silently
turned a malformed request into an unbounded response. It is now rejected with
`BAD_ARGUMENTS` (`bad_data`), the same way `start=` / `end=` already are.
2. `/api/v1/labels` and `/api/v1/label/<name>/values` materialized labels straight
from the raw carriers, so a row holding different non-empty values for a
`tags_to_columns` tag in the dedicated column and in the residual `tags` Map was
reported by them while `/api/v1/query`, `/api/v1/series`, and the write path
(`timeSeriesStoreTags`) reject it - the metadata endpoints hid the corruption.
Both endpoints now evaluate the same `throwIf` carrier check that
`timeSeriesTagNameToAST` applies to matchers, for the labels they materialize:
`/api/v1/labels` for every configured tag, `/api/v1/label/<name>/values` for the
requested one. A request that reads neither carrier (e.g. the values of a
Map-only label) is unaffected.
3. The `lookback_delta` parameter is supported since the master merge, but the
documentation block registered in `StorageTimeSeries.cpp` still listed it as not
implemented, contradicting `time-series.mdx` and the behavior.
Tests: new `test_series_labels_api_empty_limit_param.py` (empty `limit=` rejected on
all three metadata endpoints and on `/api/v1/query` / `/api/v1/query_range`, absent
and valid values still work), and the conflicting-carrier fixture now also asserts
`bad_data` from `/api/v1/labels` and `/api/v1/label/host/values`.
…bels
`/api/v1/labels` derived the map-backed label names from raw `mapKeys(tags)`,
so a supported external `tags` table row like `tags = {'env': ''}` surfaced
`env` as a label name even though the rest of the implementation treats an
empty label value as "label absent" (`/api/v1/series` drops such entries,
matcher translation treats them as the missing case, and
`/api/v1/label/<name>/values` filters them). The spurious name also counted
toward `limit`. Build the map-backed side of the label-keys array from
key/value pairs filtered to non-empty values before the `LEFT ARRAY JOIN`,
in both the plain and the `tags_to_columns` variants of the expression.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97032&sha=984be728783e19cc624fb7e60acb45a15471aa3a
Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Pushed
Both CI failures on
|
|
The I did not open a competing PR. I root-caused it independently first and landed on the same two edges, then found #113397 already covered them plus a third file I had missed ( So this artifact will keep reproducing here until #113397 merges. Both halves of your request now have an owner. |
…equests Two fail-close fixes for the Prometheus metadata endpoints: - Reject 'start'/'end' whenever the `store_min_time_and_max_time` setting is disabled, before consulting the external table schema. Disabling only that setting leaves `filter_by_min_time_and_max_time` reading as `true`, and a supported external 'tags' table can still physically keep the `min_time`/`max_time` columns, so the endpoints would otherwise apply a prefilter over stale bounds that `StorageTimeSeriesSelector::readImpl` explicitly skips in this mode. - Stop pushing the 'limit' parameter down as a SQL `LIMIT` on `/api/v1/series`, `/api/v1/labels`, and `/api/v1/label/<name>/values`: the mixed-carrier `bad_data` validation must see every matched row, and a SQL-side `LIMIT` lets the scan stop early, so whether a corrupted row was detected depended on the caller's 'limit' and on row order. The limit is now enforced only in the emission layer, like on `/api/v1/query`. With the `LIMIT limit + 1` arithmetic gone, the `UInt64` max value of 'limit' no longer needs to be rejected and behaves as an ordinary huge limit. New integration tests: `test_series_labels_api_store_disabled_external_bounds.py` (ranged requests rejected with `store_min_time_and_max_time = 0` on an external tags table that still has the bound columns, unranged requests keep working) and `test_series_labels_api_limit_conflicting_row.py` (a conflicting-carrier row that sorts after more than 'limit' valid series still fails the request with `bad_data` on all three endpoints, and truncation still works when the selector excludes the malformed row). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97032&sha=699f63d1288291ae74bc740eada27a394b8b5b3e PR: ClickHouse#97032 Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Pushed Blocker — ranged metadata requests now gate on Major — CI on
|
…point test Commit 4ad6cfd moved the limit enforcement of the metadata endpoints to the emission layer and removed the UInt64-max rejection in `PrometheusRequestHandler::getLimitParam` (replacing `test_limit_uint64_max_is_rejected` with `_is_accepted`), but `test_invalid_limit_is_rejected_on_query_endpoints` still expected 400 for `limit=18446744073709551615` on `/api/v1/query`, which now correctly returns 200 - the only failure of CI run https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=97032&sha=4ad6cfd7e276d7a45cdc7688b041012e78b55f82&name_0=PR (the same test in 6 jobs). Also pin the accepted behavior on `/api/v1/query` in `test_limit_uint64_max_is_accepted`.
…alue
Prometheus rejects a series selector in which every matcher matches the
empty label value (e.g. `{job=~".*"}`), because such a selector does not
narrow the series set at all; accepting it made `match[]={job=~".*"}`
behave like an unfiltered scan on the metadata endpoints, bypassing the
"'match[]' is required" guard on `/api/v1/series`. Now
`makeMatchCondition` requires at least one matcher per selector that
cannot match the empty label value, with regexp matchers evaluated
against the empty string using the same fully-anchored RE2 semantics as
the generated `match` condition. Every matcher is checked (no
short-circuit), so an invalid regexp anywhere in a selector is also
rejected with `bad_data` at parse time instead of failing later inside
the generated SQL. Addresses the AI review Major on
src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp.
`test_negative_alternation_regexp_is_fully_anchored` gains a metric name
matcher (its bare `{host!~"server1|server2"}` selector is now rejected,
as in Prometheus), and the new
`test_series_labels_api_empty_matching_selector.py` covers the rejected
and accepted selector shapes, the union behavior, and invalid regexps.
|
🕵 Pushed
The 6 red CI jobs were all one stale test case ( All the endpoint behaviors were verified live against a local build (rejected and accepted selector shapes, union of a valid and an invalid |
| quoteString(label_name), | ||
| makeTagCarrierConflictCheck(label_name, column_name)); | ||
| query = fmt::format("SELECT DISTINCT {} AS label_value FROM {}", value_expr, tags_table_id.getFullTableName()); | ||
| conditions.push_back(fmt::format("{} != ''", value_expr)); |
There was a problem hiding this comment.
value_expr now contains throwIf(...), and this WHERE starts by evaluating value_expr != '' before the later match[] / start / end predicates. With short_circuit_function_evaluation defaulting to disable, that means the conflicting-carrier check runs on every row of the tags table, not just on the rows selected by this request. A single bad host row in some unrelated series would therefore make /api/v1/label/host/values?match[]=cpu_usage fail even when the corrupt row is outside the requested selector or time range. Please filter by match[] / range in a subquery first and only then compute and validate label_value.
| /// An absent parameter means "no limit", but a present-and-empty one (e.g. "limit=") is malformed: | ||
| /// treating it as absent would silently turn a broken request into an unbounded response, so reject | ||
| /// it - Prometheus answers such requests with a `bad_data` error as well. | ||
| UInt64 getLimitParam() const |
There was a problem hiding this comment.
This parser no longer matches Prometheus' own optional-parameter semantics. Upstream Prometheus treats limit= as the default 0 (no limit), treats empty start= / end= as omitted bounds, and rejects limit once it overflows int; this branch instead 400s on blank optional parameters and accepts huge UInt64 limits such as 18446744073709551615. That makes the API stricter in some cases and looser in others than the Prometheus-compatible behavior the new tests are claiming. If the goal here is compatibility, this helper should mirror Prometheus' parsing rather than define a different wire contract.
|
Dear @nikitamikhaylov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
All of them were implemented in separate PRs. |
Implement the three remaining Prometheus HTTP API metadata endpoints for the
TimeSeriesengine, which previously threwNOT_IMPLEMENTED. These endpoints are required by Grafana's Prometheus data source for label autocomplete and the metric browser./api/v1/series: returns all series with their full label sets by querying the tags table, filtered by thematch[]series selectors. Each row is normalized to its logical Prometheus label set (atags_to_columnstag can live in the dedicated column or in the residualtagsMapof a supported external table) with the same rules astimeSeriesStoreTags: both carriers are merged, exact duplicates collapse, empty values are dropped, and conflicting carrier values are rejected withbad_data, so deduplication is by series identity rather than by the raw table layout./api/v1/labels: returns all distinct label names from the tagsMapcolumn and from thetags_to_columnscolumns, always including__name__as a virtual label. An empty label value means the label is absent, so a map entry with an empty value (possible in a supported externaltagstable, e.g.tags = {'env': ''}) does not surface its key as a label name and does not count towardlimit, consistently with the other endpoints./api/v1/label/<name>/values: returns the distinct values for a specific label, reading themetric_namecolumn for__name__, the dedicatedtags_to_columnscolumn (falling back to the residualtagsMap) for a configured tag, or the tagsMapotherwise.Both of these endpoints validate the carriers of the labels they materialize the same way
/api/v1/seriesand the query endpoints do, so a row holding different non-empty values for one tag in its dedicated column and in the residualtagsMapis rejected withbad_datainstead of being silently reported.The optional
limitparameter is supported on all the endpoints, and a present-but-emptylimit=,start=, orend=is rejected withbad_datarather than being treated as an omitted parameter. The limit is enforced in the emission layer rather than as a SQLLIMIT, so the carrier validation above sees every matched row and a corrupted row cannot be hidden by a smalllimitand a favorable row order.The optional
start/endparameters filter by themin_time/max_timecolumns of thetagstable and are accepted only when bothstore_min_time_and_max_timeandfilter_by_min_time_and_max_timeare enabled - the same gate as the query path's tags-table prefilter. When either setting is disabled (including an externaltagstable that still physically has the bound columns whilestore_min_time_and_max_time = 0), a ranged metadata request is rejected instead of silently diverging from/api/v1/queryand/api/v1/query_range.The
match[]parameter accepts full Prometheus series selectors (a bare metric name or an instant selector with=,!=,=~,!~label matchers, e.g.cpu_usage{host="server1"}), parsed with the same PromQL parser as/api/v1/queryand translated into the sametags-table filter the query endpoints use, so all three metadata endpoints select exactly the series the query endpoints would read. A repeatedmatch[]is the union of the selectors, as in Prometheus. A matcher on atags_to_columnstag resolves the tag with the same carrier normalization as the endpoints themselves: the dedicated column wins when non-empty (NULL is normalized to the empty label value), the residualtagsMapis used otherwise, and a row carrying different non-empty values in the two carriers is rejected withbad_datainstead of silently preferring one of them. Regexp matchers are fully anchored (^(?:...)$), and non-legacy (UTF-8) label names are written as quoted string literals, e.g.{"http.status_code"="200"}, both as in Prometheus. A selector whose matchers all match the empty label value (e.g.{host=~".*"}) is rejected withbad_data, as in Prometheus - at least one matcher must not match the empty string, so amatch[]cannot degenerate into an unfiltered scan - and an invalid regexp anywhere in a selector is likewise rejected withbad_dataat parse time.Label names and values are JSON-escaped on output and string literals interpolated into the generated SQL are quoted, so values containing quotes, backslashes, or control characters are handled correctly.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Implemented the Prometheus
/api/v1/series,/api/v1/labels, and/api/v1/label/<name>/valuesmetadata endpoints for theTimeSeriesengine.Documentation entry for user-facing changes