Skip to content

Lower PromQL predict_linear and honour stale markers in selectors - #104495

Closed
BadLiveware wants to merge 76 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-regression-range-functions
Closed

BadLiveware wants to merge 76 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-regression-range-functions

Conversation

@BadLiveware

@BadLiveware BadLiveware commented May 9, 2026 •

Copy link
Copy Markdown

Adds native lowering for PromQL regression and extrapolated range functions over ClickHouse TimeSeries data.

The implementation lowers predict_linear through 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: increase and deriv lowering landed on master independently - increase as timeSeriesIncreaseToGrid (which handles counter resets in the aggregate itself) and deriv together with a fix that scales the regression slope by the timestamp tick resolution inside timeSeriesDerivToGrid. When updating this branch both were resolved in favor of the master implementation: the local rate-scaled-by-range post-processing for increase and the per-second rescaling of deriv were dropped. Because timeSeriesDerivToGrid now returns a per-second slope, the dynamic (non-constant) predict_linear offset no longer converts the slope to timestamp ticks either.

Split out from the integration draft #104271; shared base #104484.

Changelog category (leave one):

  • Experimental Feature

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

Added native PromQL-to-SQL lowering for predict_linear over ClickHouse TimeSeries data, and made instant selectors honour Prometheus stale markers.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

BadLiveware added 14 commits May 9, 2026 13:52
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.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [934dc1c]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR adds native predict_linear lowering for TimeSeries, tightens PromQL selector validation so empty-matching selectors are rejected like Prometheus, and filters Prometheus stale markers on selector paths. I reviewed the current diff together with the full prior discussion; the previously reported Float32 precision bug in the time-dependent predict_linear offset path is fixed in the current head, and I did not find any new correctness, contract, or coverage issues in the remaining changes.

Final Verdict

✅ Approve

LLVM Coverage Report

Measured on commit 934dc1c.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 443/474 (93.46%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label May 10, 2026
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.
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.
@vitlibar vitlibar self-assigned this May 13, 2026

auto values = makeASTFunction(
"arrayMap",
makeASTLambda({"x"}, makeFilterStaleMarkerValue(make_intrusive<ASTIdentifier>("x"))),

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.

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

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.

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

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

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.

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

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.

🕵 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.
@alexey-milovidov alexey-milovidov changed the title Lower PromQL increase, deriv, and predict_linear Lower PromQL predict_linear and honour stale markers in selectors Aug 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch to current master and addressed the remaining AI Review finding.

Merge with master. The branch was CONFLICTING; resolved in 088ec63c1837:

  • 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.
  • Consequently the dynamic (SCALAR_GRID) predict_linear path, which computes intercept + slope * predict_offset in SQL from timeSeriesDerivToGrid, no longer multiplies by 10^timestamp_scale: the slope is per second and predict_offset is already in seconds, so keeping the conversion would make such predictions 10^scale times too large.
  • Merged the supported-function tables in TableFunctionTimeSeries.cpp (deriv from master, predict_linear from here), kept master's lookback_delta handling in PrometheusHTTPProtocolAPI.cpp alongside this branch's deferred PrometheusQueryTree construction, and dropped this branch's deriv(test[45s])[120s:15s] test case because master's own deriv test in the same function has byte-identical expectations.

So, after increase, deriv is now also provided by master; this PR effectively lowers predict_linear and carries the selector parsing, @-modifier and stale-marker work. The title, description and changelog entry were updated accordingly.

Stale-selector absence (AI Review Major). Fixed in 9018293e75b0: instant selectors now drop rows whose values are NULL at every grid point, so a fully stale series is absent to the row-counting duplicate-series checks rather than merely valueless, with the ignoring(instance) regression test that was requested plus a range query proving partially stale series are unaffected.

ninja clickhouse and the gtest_PromQLParser translation unit build clean locally; the integration coverage is left to CI.

…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'`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch to current master and removed stray files that were making Fast test red.

Fast test failure was not from this pull request. The only failing test at 9018293e was 04841_mongo_dialect_sort_direction, failing with Code: 552. DB::Exception: Unrecognized option '--allow_experimental_mongo_dialect'. That test - together with tests/queries/0_stateless/uuid_test_e3m1c6y3d0l8.parquet - exists neither in master nor in either parent of the previous merge commit 088ec63c1837: they were untracked files in the working tree that got staged by accident while resolving conflicts. Removed in dd183f445b64. Since Fast test gates the workflow, every other job was DROPPED, so this was the only thing standing between the pull request and a full run.

Merge with master (55df1eb4a1ba), one 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 so the ClickHouse HTTP API result could be compared against it rather than against the expected literal. Kept both.

ninja clickhouse and the gtest_PromQLParser translation unit build clean against the merged tree; integration coverage is left to CI.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 934dc1c14663a4b9fc395f0bff68ca2089b7061e with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

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`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Updated the branch: merged current master and resolved the conflicts.

master has now superseded two more parts of this PR, so the conflict resolution took master's side in both cases:

  • Fixed @ modifier over range functions. master implemented getFixedAtModifier in applyFunctionOverRange.cpp and repeats the single aggregate result over the outer grid, which is what this branch did with 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(). For predict_linear the timeSeriesFromGrid expression is repeated instead of aliased, because two aggregate functions are built over the same time series and an 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, so the file was reverted to master.
  • PrometheusQueryParsingUtil-antlr.cpp: master added its own "metric name must not be set twice" check, so the redundant validateSelectorDoesNotSetMetricNameTwice was dropped; the non-empty matcher validation stays.
  • gtest_PromQLParser.cpp: kept master's new start / end identifier tests and this branch's expectation that {__name__=~".*"} is rejected, which is the point of the selector validation here.

So this PR now lowers predict_linear, validates selector matchers, and honours stale markers; increase and deriv come from master.

Built clickhouse and gtest_PromQLParser.cpp.o cleanly and smoke-tested the reworked lowering locally against a TimeSeries table with samples 1, 3, 5 at t = 0, 30, 60:

query result
predict_linear(m[2m], 60) @ 60 9
deriv(m[2m]) @ 60 0.0666…
predict_linear(m[2m] @ 1767225660, 60) @ 60 9
predict_linear(m[2m] offset 30s, 60) @ 60 9
predict_linear(m[2m], 60) range 30…90/30s 7, 9, 11
predict_linear(m[2m], time() - 1767225600) range 5, 9, 13
predict_linear(m[1m:30s], 60) range 7, 9, 5

all matching Prometheus semantics, plus the stale-marker cases (a fully stale series is absent, and stale_pair + ignoring(instance) stale_pair returns empty instead of throwing, while two genuinely live duplicates still throw).

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 master, because the duplicate-labelset checks count rows rather than per-timestamp presence. Making them step-aware also requires merging matching rows per timestamp, which changes the result of every PromQL binary operation, so it is a separate change to the vector-matching lowering. The contract is documented explicitly instead.

`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`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master and addressed the AI Review findings; pushed 84153e683319..4492062b7cbb.

Review findings

  • Major — error_pos regression in the new selector validation (PrometheusQueryParsingUtil-antlr.cpp): the newly added getStartPos(const antlr4::ParserRuleContext *) returned ANTLR's raw code-point index, while every other overload converts it to a byte offset. It now forwards to the antlr4::Token * overload, so invalid regular expression in label matcher and vector selector must contain at least one non-empty matcher point at the right place even after multi-byte UTF-8 text.
  • Tests — added PromQLParser.SelectorValidationErrorPosition, which pins both the message and the error_pos contract for the two new failures, including the UTF-8 case ({foo="é"} or {job=~".*"} must report byte 14, not code point 13). All 22 PromQLParser gtests pass locally.
  • Nit — self-contradicting docs (TableFunctionTimeSeries.cpp): predict_linear is removed from both Not yet supported lists, so the generated prometheusQuery / prometheusQueryRange docs agree with the supported-range-functions table.

CI failures

  • test_prometheus_protocols/test_evaluation.py::test_native_promql_error_paths (6 shards) was a stale expectation after the previous master merge: applyDateTimeFunction now says Function 'day_of_week' expects 0 or 1 arguments, ... (it used to say expects 1 arguments). The expected string is updated.
  • 04510_not_has_function_explain (Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), Timeout) is unrelated: on 2026-08-22 it timed out on ~40 unrelated PRs and on master itself, and it has essentially stopped since 2026-08-23, so the master merge should clear it.

The master merge had to be done with a single merge base (git merge-tree --merge-base=) because the branch has a criss-cross history with two bases; the resulting diff against master is exactly the 13 files this PR owns.

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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master, resolved the conflicts, and fixed the remaining AI Review Major; pushed de3246ba4690..8e56050f9c98.

AI Review Major - error_pos for a later invalid label matcher (PrometheusQueryParsingUtil-antlr.cpp). validateSelectorHasNonEmptyMatcher passed the start of the whole selector into every matcherMatchesEmptyString call, so {__name__=~".+", job=~"(.*"} reported invalid regular expression in label matcher at byte 0. Each matcher's own start position is now collected next to the matcher and used for the per-matcher error, so the message points at the offending matcher (byte 17 for that query). The vector selector must contain at least one non-empty matcher error is about the selector as a whole and keeps pointing at the start of the selector. PromQLParser.SelectorValidationErrorPosition gains three cases where the bad regexp comes after an earlier valid matcher, after a metric name, and after multi-byte UTF-8 text; two existing expectations moved from the selector start to the matcher start, which is the point of the change.

Merge with master. The two branches have criss-cross merge bases, so the merge was done against the single base bb113c384 to avoid spurious conflicts in unrelated files. Two real conflicts:

  • applyFunctionOverRange.cpp: master implemented sum_over_time, avg_over_time and count_over_time and removed avg_over_time from the TODO list, while this branch removed predict_linear from it - took both removals.
  • TableFunctionTimeSeries.cpp: the embedded docs tables are the union of master's new range functions and this branch's predict_linear, and the Not yet supported lists take master's shape with predict_linear removed.

The diff against master is unchanged in shape: exactly the 13 files of this pull request.

Verification. ninja clickhouse and ninja unit_tests_dbms build clean; all 22 PromQLParser gtests pass. Smoke-tested through clickhouse local: predict_linear(m[2m], 60) over samples 7, 8, 9 spaced 30 s apart returns 11, and {__name__=~".+", job=~"(.*"} reports the parse error at position 17. whitespace_check, cpp, catch_all, clickhouse_spelling and embedded_doc_snippets style checks pass locally.

The remaining open thread on fromSelector.cpp is the staggered-staleness one. As explained there, it is pre-existing master behaviour of the row-based duplicate-labelset checks and is not introduced by this change; a real fix needs per-step counting plus per-timestamp merging across every PromQL binary operation, which is a maintainer call and is documented in the embedded docs.

alexey-milovidov and others added 2 commits September 16, 2026 13:51
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 57e97ff50

Metric Baseline Current Δ
Score 84.23% 85.77% +1.54%
Passed 454 482 +28
Failed 3 2 -1
Unsupported 82 78 -4

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 85.77% vs master baseline 84.23% (57e97ff50). Merging to master will publish a new S3 object from the integration job that runs test_promql_compliance, which becomes the baseline for later PRs.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 I tried to merge current master (a029f7a3d035a8416cd9059aaa4a04a8cc85b1af) into this branch. There are conflicts in 9 files, and in every one of them master now has its own implementation of what this PR adds:

  • predict_linear: implemented in applyFunctionPredictLinear.cpp. It came in with Revert "Revert "Implement PromQL range functions present_over_time, absent_over_time, quantile_over_time and predict_linear"" #120352 (the re-land of present_over_time / absent_over_time / quantile_over_time / predict_linear, merged 2026-09-17) and was then switched to Float64 values in 4d2ca403ec8. master already lists predict_linear in the prometheusQuery / prometheusQueryRange docs.
  • Stale markers in selectors: Fix(PromQL): PromQL stale-marker selector semantics #121098 (fromSelector.cpp, replaceStaleMarkersWithNulls). Range selectors filter stale markers out of the raw data. Instant selectors let last_over_time select the marker, turn it into NULL, and drop rows that are NULL at every step. That is the same behaviour as filterInstantSelectorStaleMarkers here, including the fix for the duplicate-series exception from the review thread.
  • Selectors must have a non-empty matcher, and invalid regexps are reported at the matcher: Fix(PromQL): Reject PromQL selectors with only empty-matching matchers #121099 (PrometheusQueryParsingUtil-antlr.cpp, plus the SelectorRequiresNonEmptyMatcher gtest).
  • The Float64 scalar handling in Converter.cpp is no longer needed: context.scalar_data_type was removed on master, and scalars are always Float64 now.
  • The @ modifier over range functions was already taken from master (getFixedAtModifier) in an earlier merge.

I checked that each of these commits is an ancestor of origin/master, and that none of them was reverted later.

The only parts not on master are the PrometheusQueryToSQL/README.md, the two documentation notes (absence of a series is decided per series, and stale markers are only recognized with a Float64 value column), and some extra integration-test cases. A mechanical merge would mean taking master's side in every source conflict, so the PR would shrink to those leftovers. Because of that I did not push a merge. A maintainer should decide whether to close this PR as superseded, or to cut it down to the docs and tests in a follow-up.

@alexey-milovidov

Copy link
Copy Markdown
Member

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

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... manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants