Repository navigation
Lower PromQL predict_linear and honour stale markers in selectors - #104495
BadLiveware wants to merge 76 commits into
Conversation
Add the common PromQL compliance reporting and developer notes used by the follow-up TimeSeries PromQL lowering slices. Keep the parser compliance corpus expectation explicit for selectors Prometheus rejects.
Add focused Prometheus protocol tests for user-facing native lowering errors: unsupported-but-parseable functions and invalid date-function arity. These are semantic guardrails for clear errors, not broad coverage padding.
Add increase as a native lowering slice on top of the existing rate implementation. ClickHouse timeSeriesRateToGrid already implements Prometheus-compatible counter reset and extrapolation logic, so increase scales the per-second rate back to the requested range length.
Add deriv and predict_linear as a separate range-regression slice. Both lower to existing ClickHouse time-series linear regression aggregates rather than duplicating regression logic in PromQL conversion, and deriv scales timestamp-unit slopes back to Prometheus per-second semantics.
Avoid fork-local wording in the PromQL review base. These are ClickHouse PromQL regression cases and evidence requirements, not fork-specific artifacts.
Avoid fork-local wording in the PromQL review base. These are ClickHouse PromQL regression cases and evidence requirements, not fork-specific artifacts.
Remove the standalone native histogram discovery Markdown note from the PromQL split branches.
Remove the standalone native histogram discovery Markdown note from the PromQL split branches.
Remove downstream promshim-specific evidence and non-goal language from the native PromQL lowering README so the note stays focused on ClickHouse review guidance.
Remove downstream promshim-specific evidence and non-goal language from the native PromQL lowering README so the note stays focused on ClickHouse review guidance.
Rewrite the native PromQL lowering notes around external SQL-transpiler measurements. Document measured and mixed SQL patterns with target PromQL shapes, pseudocode, and the ClickHouse-side validation expected for in-tree changes.
Rewrite the native PromQL lowering notes around external SQL-transpiler measurements. Document measured and mixed SQL patterns with target PromQL shapes, pseudocode, and the ClickHouse-side validation expected for in-tree changes.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.
|
Workflow [PR], commit [934dc1c] Summary: ❌
AI ReviewSummaryThis PR adds native Final Verdict✅ Approve LLVM Coverage ReportMeasured on commit 934dc1c.
Changed lines: Changed C/C++ lines covered: 443/474 (93.46%) · Uncovered code |
Match Prometheus parser behavior by requiring vector selectors to contain at
least one matcher that cannot match an empty label value. This prevents broad
selectors like `{job=~".*"}` or `{__name__=~".*"}` from silently selecting every
metric when the user likely intended an explicit non-empty constraint.
Users who intentionally want all real metrics can still use `{__name__=~".+"}`,
and empty-matching label matchers remain valid when combined with that explicit
metric-name matcher.
Deduplicate expanded compliance cases by query text before checking the `should_fail` expectation. A query listed once as expected success and once as expected failure is now reported as conflicting metadata instead of slipping through as two separate cases.
…plit/promql-regression-range-functions
Mirror the upstream PromQL compliance corpus for label transformation invalid label-name cases. These cases should remain should-fail entries so ClickHouse acceptance of invalid destination labels stays visible as a rejection mismatch rather than being counted as expected coverage.
Add positive evaluation coverage for increase, deriv, and predict_linear so the lowering changes are checked against Prometheus and ClickHouse outputs, not only unsupported/error paths.
Do not stop selector validation after finding the first matcher that cannot match an empty label value. Later regex matchers still need syntax validation so equivalent selector reorderings cannot change parse validity. Add parser regressions for invalid regex matchers after an implicit metric-name matcher and after explicit non-empty matchers.
|
|
||
| auto values = makeASTFunction( | ||
| "arrayMap", | ||
| makeASTLambda({"x"}, makeFilterStaleMarkerValue(make_intrusive<ASTIdentifier>("x"))), |
There was a problem hiding this comment.
Prometheus stale markers are supposed to make an instant selector absent, but this helper only rewrites the chosen sample to NULL and keeps the row alive in VECTOR_GRID.
That is enough for top-level finalization, but downstream cardinality checks still operate on rows, not non-NULL presence. For example, applySimpleBinaryOperator.cpp still does count() > 1 when validating the “one” side of vector matching, and dropMetricName.cpp does the same after collapsing __name__. Two stale series that collapse under ignoring(...) or after metric-name drop can therefore still raise duplicate-series exceptions even though Prometheus would treat both series as absent at that timestamp.
Could we drop selector rows whose values array became entirely NULL, or otherwise teach the downstream duplicate/matching logic to count only non-NULL timestamps instead of raw rows? A focused regression here would be two stale instant-selector series that collide under ignoring(instance).
There was a problem hiding this comment.
🕵 Fixed in 9018293e75b0. filterInstantSelectorStaleMarkers now also filters out rows whose values are NULL at every grid point - exactly the case where the series is absent for the whole evaluation - so a fully stale series no longer reaches the row-counting duplicate-series checks in applySimpleBinaryOperator, dropMetricName and applyLabelManipulationFunction. Partially stale series keep their row and their live samples.
Added the regression test you asked for: a stale_pair fixture of two series which differ only by instance and go stale at the same time, evaluated as stale_pair + ignoring(instance) stale_pair (empty result in both Prometheus and ClickHouse instead of a duplicate-series exception), plus a range query showing that a series stale at only some evaluation timestamps is still returned at the others.
There was a problem hiding this comment.
The fully-stale case is fixed, but the range-query variant is still open. filterInstantSelectorStaleMarkers only drops rows when the whole grid becomes NULL (src/Storages/TimeSeries/PrometheusQueryToSQL/fromSelector.cpp:70-73).
In query_range, two selector series that collapse under ignoring(instance) can therefore each keep one live point on different steps and still survive as two rows, and applySimpleBinaryOperator.cpp still validates the “one” side with count() > 1 over rows rather than per-step non-NULL presence (src/Storages/TimeSeries/PrometheusQueryToSQL/applySimpleBinaryOperator.cpp:146-152). So the added stale_pair regression covers the synchronized-staleness case, but a staggered case (A live only at 125, B live only at 145) would still throw even though Prometheus evaluates each step independently and accepts it.
There was a problem hiding this comment.
🕵 The staggered case is real, but it is not specific to stale markers and this change does not introduce it.
filterInstantSelectorStaleMarkers drops a row only when the whole grid is NULL on purpose: a series which is stale on part of a range query is still present at the other evaluation timestamps, so dropping its row would lose live points. What makes the staggered case throw is that the duplicate-labelset checks in applySimpleBinaryOperator, dropMetricName and applyLabelManipulationFunction count rows rather than per-timestamp presence — which is already the behaviour on master for ordinary series, with no stale marker involved.
Verified locally on this build, with two plain series whose only samples are ten minutes apart:
SELECT * FROM prometheusQueryRange(ts, 'dj', '2026-01-01 00:00:00', '2026-01-01 00:10:00', INTERVAL 10 MINUTE)
[('__name__','dj'),('instance','a')] [('2026-01-01 00:00:00.000',1)]
[('__name__','dj'),('instance','b')] [('2026-01-01 00:10:00.000',2)]
SELECT * FROM prometheusQueryRange(ts, 'dj + ignoring(instance) dj', ...)
Code: 768. DB::Exception: Multiple series have the same tags {}, duplicate series in the same result set are not allowed
So the fix belongs to the vector-matching lowering, not to stale-marker handling, and relaxing the check alone is not enough: to return what Prometheus returns, the matching rows would also have to be merged per timestamp (each side keeping the value of whichever series is live at that step). That changes the result of every PromQL binary operation, dropMetricName and the label-manipulation rewrites, so it is a separate change and a maintainer call rather than something to fold into this PR.
The contract is now scoped explicitly instead, in 84153e683319: a series counts as absent only when all of its selected samples are stale markers. This is stated in the comment at filterInstantSelectorStaleMarkers and in the documentation of prometheusQuery / prometheusQueryRange, together with the note that ordinary series with samples in disjoint parts of the range behave the same way.
There was a problem hiding this comment.
🕵 This is now covered on master by #121098. replaceStaleMarkersWithNulls in fromSelector.cpp drops vector-grid rows that are NULL at every step, which is the same contract as here. The staggered range-query case is still out of scope for stale-marker handling, as explained above: duplicate-labelset checks count rows, and that also affects ordinary series. See #104495 (comment) for why this PR is now superseded.
Conflict resolution: - `applyFunctionOverRange.cpp`: `master` (commit `b356cac288ab`) added its own PromQL `deriv` lowering and fixed `timeSeriesDerivToGrid` to scale the slope by the timestamp tick resolution inside the aggregate. Kept `master`'s `impl_map` entry and dropped this branch's duplicate entry together with the whole `PostProcessFunction` mechanism, whose only user was the now-redundant per-second rescaling of `deriv`. - `applyFunctionOverRange.cpp`: for the dynamic (`SCALAR_GRID`) `predict_linear` offset the prediction is computed in SQL as `intercept + slope * predict_offset`, where `slope` comes from `timeSeriesDerivToGrid`. That slope is now per second, and `predict_offset` is already expressed in seconds, so the `10^timestamp_scale` conversion to timestamp ticks was removed - keeping it would make such predictions 10^scale times too large. - `TableFunctionTimeSeries.cpp`: merged both supported-function tables, listing `deriv` (from `master`) and `predict_linear` (from this branch). - `PrometheusHTTPProtocolAPI.cpp`: kept `master`'s `lookback_delta` handling while keeping this branch's deferred `PrometheusQueryTree` construction. - `test_evaluation.py`: dropped this branch's `deriv(test[45s])[120s:15s]` case because `master`'s own `deriv` test in the same function has byte-identical expectations.
…valueless `filterInstantSelectorStaleMarkers` rewrote the selected sample of a stale series to `NULL` but kept its row in the vector grid. Downstream duplicate-series checks (`applySimpleBinaryOperator`, `dropMetricName`, `applyLabelManipulationFunction`) count rows rather than non-`NULL` values, so two series that are stale everywhere and collapse to the same labelset under `ignoring(...)` or after `__name__` removal could still raise a duplicate-series exception, while Prometheus treats both series as absent and returns an empty result. Drop rows whose values are `NULL` at every grid point, which is exactly the case where the series is absent for the whole evaluation, and keep partially stale series intact. Adds a `stale_pair` fixture of two series which differ only by `instance` and go stale at the same time, a regression test evaluating `stale_pair + ignoring(instance) stale_pair`, and a range query showing that a series stale at only some evaluation timestamps is still returned at the others.
|
🕵 Updated the branch to current Merge with
So, after Stale-selector absence (AI Review Major). Fixed in
|
…sion-range-functions Resolved a conflict in `tests/integration/test_prometheus_protocols/test_evaluation.py`: master made the Prometheus-side comparison approximate and plumbed `eps` into `execute_query_in_prometheus` and `execute_range_query_in_prometheus`, while this branch captured the actual Prometheus response to compare the ClickHouse HTTP API result against it. Kept both: pass `eps` through and keep comparing the HTTP API result with the captured Prometheus response.
`tests/queries/0_stateless/04841_mongo_dialect_sort_direction.{sh,reference}` and
`tests/queries/0_stateless/uuid_test_e3m1c6y3d0l8.parquet` were never part of this
pull request nor of `master`: they were untracked files in the working tree that got
staged by accident while resolving conflicts in a previous merge.
The stray test made `Fast test` red, because it uses `--allow_experimental_mongo_dialect`,
a setting that does not exist: `Code: 552. DB::Exception: Unrecognized option
'--allow_experimental_mongo_dialect'`.
|
🕵 Updated the branch to current
Merge with
|
Build profile diff (arm_release)Comparing commit See the job log for details. |
…sion-range-functions
Conflict resolution notes:
* `applyFunctionOverRange.cpp`: master implemented fixed `@` modifier handling
for range functions (`getFixedAtModifier` plus repeating the single aggregate
result over the outer grid), which supersedes this branch's
`getAtModifierRangeArgument`/`expandSingleValueToGrid`. Kept master's version
and rebuilt `predict_linear` on top of it; the `predict_linear` timestamp
shift now uses `hasAtModifier` so it also covers master's symbolic `@ start()`
/ `@ end()` modifiers. For `predict_linear` the `timeSeriesFromGrid`
expression is repeated instead of aliased, because two aggregate functions are
built over the same time series and the alias must not be defined twice.
* `applyOffset.cpp`: master's `setEvaluationTime` now returns a range vector
unchanged, which supersedes this branch's `VECTOR_GRID` and `RAW_DATA` special
cases and its `std::max` -> `std::min` scale fix. Reverted the file to master.
* `PrometheusQueryParsingUtil-antlr.cpp`: master added its own check that a
metric name is not set twice, so this branch's redundant
`validateSelectorDoesNotSetMetricNameTwice` was dropped; the non-empty matcher
validation is kept.
* `gtest_PromQLParser.cpp`: kept master's new `start` / `end` identifier tests
and this branch's expectation that `{__name__=~".*"}` is rejected, since
rejecting selectors without a non-empty matcher is the point of this change.
* `TableFunctionTimeSeries.cpp`: union of both documentation tables.
… step
The AI review asks to make stale-marker absence step-aware for range queries,
because two series which are live at disjoint evaluation timestamps and collapse
to the same labelset are reported as duplicate series instead of being matched
step by step.
The gap is real but it is not specific to stale markers, and it is not
introduced by this change: the duplicate-labelset checks in
`applySimpleBinaryOperator`, `dropMetricName` and `applyLabelManipulationFunction`
count rows, so two ordinary series with samples in disjoint parts of the queried
range already raise the same exception without any stale marker being involved.
Verified locally on this build with two plain series ten minutes apart:
`dj + ignoring(instance) dj` over a two-step range query throws
`Multiple series have the same tags {}`.
Making those checks step-aware would additionally require merging the matching
rows per timestamp, which changes the result of every PromQL binary operation, so
it is a separate change to the vector-matching lowering rather than part of
stale-marker handling. Scope the contract explicitly instead: a series counts as
absent only when all of its selected samples are stale markers, both in the code
comment at `filterInstantSelectorStaleMarkers` and in the documentation of
`prometheusQuery` and `prometheusQueryRange`.
|
🕵 Updated the branch: merged current
So this PR now lowers Built
all matching Prometheus semantics, plus the stale-marker cases (a fully stale series is absent, and On the remaining AI-review blocker (staggered staleness in range queries) I replied on the thread: the case is real but is not introduced here — two ordinary series with samples in disjoint parts of the range already raise the same duplicate-series exception on |
`getStartPos(const antlr4::ParserRuleContext *)` returned ANTLR's raw code-point index while every other overload converts it to a byte offset, so the new `vector selector must contain at least one non-empty matcher` and `invalid regular expression in label matcher` errors pointed at the wrong place after multi-byte UTF-8 text. Route it through the `Token` overload and cover the contract in a new `SelectorValidationErrorPosition` test. Also drop `predict_linear` from both `Not yet supported` lists in the embedded `prometheusQuery` docs (it is listed as supported in the same file), and update `test_native_promql_error_paths` for master's new `expects 0 or 1 arguments` wording in `applyDateTimeFunction`.
…sion-range-functions
|
🕵 Merged the latest Review findings
CI failures
The Still a draft experimental feature - not un-drafting or merging. |
Resolved with a single merge base (`bb113c384`) because the two branches have criss-cross merge bases and the recursive merge produced spurious conflicts across unrelated files. Conflicts: * `applyFunctionOverRange.cpp`: `master` implemented `sum_over_time`, `avg_over_time` and `count_over_time` and dropped `avg_over_time` from the TODO list, while this branch dropped `predict_linear` from it - took both removals. * `TableFunctionTimeSeries.cpp`: the embedded docs tables are the union of master's new `sum_over_time` / `avg_over_time` / `count_over_time` and this branch's `predict_linear`; the `Not yet supported` lists take master's shape with `predict_linear` removed.
…ector
`validateSelectorHasNonEmptyMatcher` passed the start position of the
whole selector into every `matcherMatchesEmptyString` call, so a query
such as `{__name__=~".+", job=~"(.*"}` reported `invalid regular
expression in label matcher` at byte `0` instead of at the second
matcher.
Each matcher's own start position is now collected next to the matcher
itself and used for the per-matcher error. The `vector selector must
contain at least one non-empty matcher` error is about the selector as a
whole, so it keeps pointing at the start of the selector.
`PromQLParser.SelectorValidationErrorPosition` gains cases where the
invalid regexp comes after an earlier valid matcher, after a metric
name, and after multi-byte UTF-8 text. Two existing expectations move
from the selector start to the matcher start, which is the point of the
change.
|
🕵 Merged the latest AI Review Major - Merge with
The diff against Verification. The remaining open thread on |
…sion-range-functions # Conflicts: # src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionOverRange.cpp # src/TableFunctions/TableFunctionTimeSeries.cpp
…meSeries(Float32)` tables The second argument of `predict_linear` may be a scalar expression which depends on the evaluation time, e.g. `predict_linear(m[5m], time() - 1700000000)`. Scalar expressions are converted in the scalar (value) data type of the `TimeSeries` table, and `Float32` only has ~128 seconds of precision at today's epoch magnitude, so on a table with `Float32` values the evaluation timestamps were rounded to that granularity before the offsets were computed: distinct steps collapsed to the same offset and the per-step predictions were wrong. `Converter` now converts the offset argument of `predict_linear` with `scalar_data_type` temporarily set to `Float64` (`visitNodeWithFloat64Scalars`, driven by `isFunctionOverRangeFloat64ScalarArgument`), and the constant-offset path emits a `Float64` literal too. Added an integration test with a `TimeSeries(Float32)` table and an exactly linear series where the wrong offsets used to be 76, 76 and 204 seconds instead of 60, 120 and 180. Co-Authored-By: Claude Fable 5.1 <[email protected]>
PromQL Compliance ReportBaseline: S3 master
Uploaded compliance JSON for this PR commit Baseline updateThis run reports 85.77% vs master baseline 84.23% ( |
|
🕵 I tried to merge current
I checked that each of these commits is an ancestor of The only parts not on |
|
@BadLiveware, on behalf of @nikitamikhaylov, @vitlibar, and @JTCunning, let me apologise for delayed reaction in this PR. I want to personally thank you for the contribution. However, as all components have been independently implemented and merged into master, I have to close this. |
Adds native lowering for PromQL regression and extrapolated range functions over ClickHouse
TimeSeriesdata.The implementation lowers
predict_linearthrough the ClickHouse time-series linear-regression aggregates, and additionally tightens PromQL selector parsing,@-modifier handling, and Prometheus stale-marker filtering for the range functions.Note:
increaseandderivlowering landed onmasterindependently -increaseastimeSeriesIncreaseToGrid(which handles counter resets in the aggregate itself) andderivtogether with a fix that scales the regression slope by the timestamp tick resolution insidetimeSeriesDerivToGrid. When updating this branch both were resolved in favor of themasterimplementation: the localrate-scaled-by-range post-processing forincreaseand the per-second rescaling ofderivwere dropped. BecausetimeSeriesDerivToGridnow returns a per-second slope, the dynamic (non-constant)predict_linearoffset no longer converts the slope to timestamp ticks either.Split out from the integration draft #104271; shared base #104484.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added native PromQL-to-SQL lowering for
predict_linearover ClickHouseTimeSeriesdata, and made instant selectors honour Prometheus stale markers.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/104495]