Skip to content

Support PromQL changes and resets - #104487

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

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

Conversation

@BadLiveware

@BadLiveware BadLiveware commented May 9, 2026 •

Copy link
Copy Markdown

Adds native lowering for the PromQL counter state range functions changes and resets over ClickHouse TimeSeries data.

The implementation uses dedicated time-series aggregate helpers so reset/change detection is handled in the same range-grid execution shape as the existing rate and delta family.

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 changes and resets over ClickHouse TimeSeries data.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

BadLiveware added 13 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.
Wire PromQL changes() and resets() through the existing TimeSeries aggregate helpers so the native converter can evaluate those range functions instead of reporting them unsupported.

Match Prometheus handling for consecutive NaN samples in changes(), and add differential coverage for reset windows, sparse or empty inputs, special values, and query_range alignment.

Validation: Build (amd_debug); test_prometheus_protocols/test_evaluation.py::test_function_over_time; test_prometheus_protocols/test_compliance.py::test_promql_compliance.
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 [ca38c3f]

Summary: ✅


AI Review

Summary

This PR adds native PromQL lowering for changes and resets, and it also tightens the surrounding semantics for stale markers, fixed-time @ handling on subqueries/range functions, selector validation, and the supported-function docs. After checking the current diff and re-verifying the previously resolved review threads against the current code, I did not find a remaining correctness or PR-metadata issue.

Final Verdict
  • Status: ✅ Approve

@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.
The nested aggregate function can canonicalize its parameter list during factory
creation. Wrap the nested function with that canonical parameter set instead of
the original parser parameters so the Array wrapper and nested aggregate keep the
same definition.
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.
The Array combinator now keeps the nested aggregate's canonical parameters, so
it no longer reads the original factory parameter list. Leave the argument
unnamed to satisfy warning-as-error builds while preserving the override
signature.
@alexey-milovidov

Copy link
Copy Markdown
Member

The FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly failure on this PR is a known flaky test that was fixed in #104418. Could you please update the branch with the latest master to pick up the fix?

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.
Keep the PromQL parser, modifier, and selector fixes from the local matrix pass, but move the high-value regression coverage into the existing protocol and compliance suites instead of adding the standalone matrix harness to the PR branch.\n\nThis keeps fixed-time range evaluation covered through the existing evaluation tests and records the parser, matcher, timestamp-modifier, and sparse range cases in the shared compliance corpus.
Build (arm_tidy) flagged the vector-grid finalization predicate because one call cloned an AST pointer while another argument moved the same pointer. C++ argument evaluation order can make that a use-after-move.\n\nCreate separate AST nodes for the null and stale-marker checks so the generated predicate stays the same without relying on argument evaluation order.
Parse `@ start()` and `@ end()` as timestamp modifier variants instead of
rewriting the raw query text before parsing. This keeps label values and
regular expressions untouched while resolving symbolic bounds in the query
range planner.

Propagate symbolic `@` modifiers through the PromQL tree and SQL lowering so
instant selectors and range-vector functions bind to the query start or end
consistently with Prometheus.
The selector-matcher validation branch should not also introduce symbolic
`@ start()` and `@ end()` modifier parsing. Remove that parser/evaluation
feature from the base branch so the behavior can be reviewed independently.

Move the symbolic timestamp-modifier compliance cases out with the feature.
Keep the offset-only case here because it exercises existing modifier behavior.
Symbolic `@ start()` and `@ end()` modifiers need parser-level handling so
selectors, string literals, and regular expressions are not rewritten as raw
text. Remove the temporary text-substitution path from the base branch; the
symbolic modifier implementation belongs with the dedicated parser change.
…anges-resets

# Conflicts:
#	tests/integration/test_prometheus_protocols/test_compliance.py
#	tests/integration/test_prometheus_protocols/test_evaluation.py
An instant-vector `VECTOR_GRID` (built by `last_over_time` for an instant
selector) keeps Prometheus stale markers in its `values` array: they are
filtered out only later, when the grid is finalized as an instant vector
(see `finalizeInstantVectorAsSQL`).

A subquery such as `stale_counter_values[60s:10s]` reuses the same grid as a
range vector via `applySubquery`, which only flips the result type to
`RANGE_VECTOR`. The downstream consumers - `finalizeRangeVectorAsSQL` and the
`VECTOR_GRID` branch of `applyFunctionOverRange` - feed the array straight into
`timeSeriesFromGrid` without the stale-marker check, so the Prometheus stale
`NaN` surfaced as a real matrix sample (and could also feed range functions
applied over the subquery).

Fix it at the single conversion point: when `applySubquery` turns a
`VECTOR_GRID` instant vector into a range vector, replace stale-marker grid
entries with `NULL`. `timeSeriesFromGrid` skips `NULL` entries, which matches
Prometheus dropping the stale step entirely, while regular `NaN` samples stay
visible.

Adds `test_subquery_drops_stale_marker` covering an instant-selector subquery
whose grid contains a stale marker.
The earlier fix filtered Prometheus stale markers only inside `applySubquery`,
which the AI review found to be too late on two still-reachable paths:

- Top-level `query_range`: `Converter::getSQL` rewrites a root instant-vector
  query to `RANGE_VECTOR`, so `finalizeRangeVectorAsSQL` feeds the grid's
  `values` straight into `timeSeriesFromGrid` (which only skips `NULL`). A
  query like `stale_counter_values` over `/api/v1/query_range` still emitted
  the stale step as a matrix sample.

- Instant-vector operators and functions: `fromSelector` kept stale markers in
  the grid, and elementwise transforms (`applyComparisonOperator`,
  `applySimpleFunction`, ...) run `arrayMap` over those values before the
  subquery filter. For `(stale_counter_values == bool 2)[30s:10s]` the stale
  `NaN` became `0` before the exact-bit-pattern check, so the step survived.

The real issue is that stale markers were filtered at leaf consumers rather
than at their source. A grid only ever receives stale markers in one place:
`fromSelector(InstantSelector)`, which reads raw selector data with
`filter_stale_markers = false` so that `last_over_time` can observe a stale
marker as the latest sample (masking earlier real samples in the window).

Fix it there: right after `last_over_time` collapses each window to its latest
sample, replace stale-marker grid entries with `NULL`. `timeSeriesFromGrid`
and the instant-vector finalizer both skip `NULL`, which matches Prometheus
dropping the stale step entirely, while regular `NaN` samples stay visible.
Because this is the sole entry point of stale markers into an instant-vector
grid, every downstream consumer - both finalizers, elementwise operators and
functions, and subqueries - now observes stale steps as `NULL`. The
now-redundant filter in `applySubquery` is removed.

Adds `test_range_query_drops_stale_marker` (top-level `query_range` path) and
`test_subquery_over_operator_drops_stale_marker` (a `bool` comparison subquery)
covering the two paths above.
@BadLiveware

Copy link
Copy Markdown
Author

Sorry for abandoning these(My open pull requests) for so long, lots of other work came up. I was going to close them as I didnt feel like I had the time to finish them properly.

I will likely have to go with a different approach anyway as it became clear that I need refreshing materialized views for a lot of the dashboard Im interested in.

Im going to leave them open for you to take over if you wish, @alexey-milovidov, since I see you working on them.

@alexey-milovidov

Copy link
Copy Markdown
Member

No problem. We are trying to merge it. Still needs a review from @vitlibar.

…functions

# Conflicts:
#	src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesChanges.h
Fixed-time `@` was carried through only for raw range selectors: a fixed
subquery like `test[45s:15s] @ 130` reached `setEvaluationTime` as
`StoreMethod::VECTOR_GRID`, where the grid was collapsed to
`arrayResize([], count, values[1])`, so a root matrix query degenerated
to its first step and a range function over the subquery aggregated a
one-point matrix.

`NodeEvaluationRangeGetter` already plans the subquery's inner grid at
the fixed evaluation time, so the fix is to keep a `RANGE_VECTOR` grid
intact in `setEvaluationTime` and to extend the fixed-window
aggregate-then-repeat logic in `applyFunctionOverRange` from
`StoreMethod::RAW_DATA` to `StoreMethod::VECTOR_GRID` arguments.

Addresses the AI review finding on
ClickHouse#104487.
…ange functions

The supported-function tables in the `prometheusQuery` and
`prometheusQueryRange` docs still listed only `rate`, `irate`, `delta`,
`idelta`, and `last_over_time`, so the two new range functions were not
discoverable.
@alexey-milovidov

alexey-milovidov commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Updated the branch: merged current master (clean) and addressed the remaining AI-Review finding — the supported-function tables in docs/en/sql-reference/table-functions/prometheusQuery.md and docs/en/sql-reference/table-functions/prometheusQueryRange.md now list changes and resets, and the documentation checkbox is ticked. Recompiled all touched translation units locally against the merged tree.

Both reds on the previous commit are unrelated to this PR:

Still a draft, and it still contains #104484, which needs to land first. Needs a review from @vitlibar.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 292/298 (97.99%) · Uncovered code

Full report · Diff report

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 3, 2026
@nikitamikhaylov

Copy link
Copy Markdown
Member

Merged here: #112352
We can still add a few additional test cases if you want.

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... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants