Repository navigation
Support PromQL set binary operators - #123503
Closed
alexey-milovidov wants to merge 89 commits into
Closed
alexey-milovidov wants to merge 89 commits into
alexey-milovidov wants to merge 89 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 native lowering for PromQL and, or, and unless over instant vectors. The lowering keeps Prometheus set semantics by matching on the configured vector-matching label set and using per-step presence masks, so range/subquery grids include or exclude samples at each evaluation timestamp rather than only at the series level. Reject scalar operands and group modifiers for set operators, and keep parser-level bool rejection covered by differential tests. Add coverage for default matching, on/ignoring, metric-name matching, empty operands, and subquery/range presence behavior. Validation: python3 -m ci.praktika run "Build (amd_debug)"; python3 -m ci.praktika run integration --test test_prometheus_protocols/test_evaluation.py; python3 -m ci.praktika run integration --test test_prometheus_protocols/test_compliance.py.
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.
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-set-binary-operators
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.
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.
…plit/promql-set-binary-operators
Add parser and HTTP API coverage for Prometheus selector validation rules: negated non-empty matchers, invalid regex validation after non-empty matchers, and duplicate metric-name matchers. Rejecting duplicate outside/in-brace metric names keeps ClickHouse parsing aligned with Prometheus expression parsing.
Set operators compare series by membership signatures and must keep every matching LHS series, including cases like `on()` where multiple series share the same join key. Use an ALL join when masking LHS values by RHS presence so join-order optimization cannot collapse those matches. Expand set-operator integration coverage for default matching, `on`, `ignoring`, empty-signature matching, explicit `__name__` matching, LHS precedence, scalar/grouping errors, and range-subquery behavior. Validation: - `ninja -C build_debug clickhouse` - `python -m ci.praktika run "integration" --test tests/integration/test_prometheus_protocols/test_evaluation.py::test_set_binary_operators`
Ignore string literals and selector matchers when routing compliance failures by query shape. This keeps report categories from treating label values or exponent signs as binary operators, and recognizes bare '<' and '>' comparisons.
Add a range-subquery case where both operands produce the same output labelset but only one side has a value at some steps. This protects the set-operator union path that combines matching groups after preserving RHS-only steps.
# Conflicts: # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorAnd.cpp # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorAnd.h # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorOr.cpp # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorOr.h # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorUnless.cpp # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorUnless.h
Master replaced the `PQT` alias with the full `PrometheusQueryTree` name in `applyFunctionOverRange.cpp`; update the fixed-range detection block accordingly. Co-Authored-By: Claude Fable 5 <[email protected]>
…fsets `error_pos` is a UTF-8 byte offset everywhere else in this parser, but the selector-validation errors passed `ctx->getStart()->getStartIndex()` through unconverted, so a query with multibyte text before the selector misreported `at position N`. Convert the `ParserRuleContext` overload of `getStartPos` through `convertCodePointPositionToByteOffset`, matching the terminal-node overload, and add a multibyte regression test covering all three selector-validation errors. Co-Authored-By: Claude Fable 5 <[email protected]>
…' into pr-104489-w2c
# Conflicts: # src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp
# Conflicts: # src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorOr.cpp # tests/integration/test_prometheus_protocols/test_evaluation.py
…set-binary-operators' Conflicts resolved: - `PrometheusHTTPProtocolAPI.cpp`: keep this branch's deferred `PrometheusQueryTree` construction (moved below the time-argument parsing), together with master's `lookback_delta` handling. - `test_evaluation.py`: keep this branch's version. The base branch's latest master merge accidentally dropped `STALE_NAN`, `test_native_promql_error_paths`, `test_instant_selector_with_multiple_name_matchers`, `test_range_query_drops_stale_marker` and the `@`-modifier tests; everything the base branch adds to this file already comes from master and is present here.
…nary-operators
Conflicts resolved:
- `applyBinaryOperatorAnd/Or/Unless.cpp` and the new `applyBinaryOperatorSet.{h,cpp}`:
keep the deletions of this branch, which consolidates all three set operators into
`applySetBinaryOperator.cpp`. Master's per-step presence mask
(`groupBitOrForEach(arrayMap(x -> isNotNull(x), values))` instead of
`countForEach(values)`) is ported into `selectPresenceByJoinGroup` there, so
`applyBinaryOperatorSet.{h,cpp}` has no remaining users and is dropped too.
- `applyFunctionOverRange.cpp`: take master's `@`-modifier implementation
(`getFixedAtModifier`), which supersedes the equivalent one carried from #104484.
- `gtest_PromQLParser.cpp`: keep master's new `start`/`end` label tests and this
branch's expectation that a selector whose every matcher can match the empty string
is rejected.
Master reworked several parts of the PromQL lowering while this branch carried an earlier version of the same work from the shared base #104484. Take master's version of the overlapping code and keep only what is specific to this branch: - `PrometheusQueryParsingUtil-antlr.cpp`: master introduced the `selectorIdentifier` grammar rule (quoted label names and quoted metric names) and a lexer that validates multiline strings. Take master's file and re-apply on top of it the check that a vector selector has at least one matcher which cannot match an empty label value. - `applyOffset.cpp`: take master's `@`-modifier handling, to match master's `applyFunctionOverRange.cpp` taken during the merge. - `PrometheusHTTPProtocolAPI.cpp`, `StoragePrometheusQuery.cpp`: drop the cosmetic reordering of the `PrometheusQueryTree` construction and follow master.
- `04816_promql_shared_subqueries_materialized`: with `enable_materialized_cte = 0`
the consolidated `or` lowering re-reads every shared grid, so the samples table is
read 5 times instead of 3. Update the expectation and the comment describing it.
- `gtest_PromQLParser`: master serializes a `__name__` equality matcher as a quoted
metric name, so `{__name__="foo", __name__!="bar"}` round-trips as
`{"foo",__name__!="bar"}`; and master reports "metric name must not be set twice"
at the offending in-brace matcher rather than at the start of the selector.
…nary-operators Criss-cross merge: `git merge-base --all` returned two bases, so the `ort` virtual base produced 233 spurious conflicts although the branch touches 25 files. Resolved mechanically: every conflicted file outside the branch's own file set was taken from `master` verbatim, and the branch's own files (the deleted `applyBinaryOperatorAnd`/`Or`/`Unless`, `applyBinaryOperator.cpp`, `fromSelector.cpp`, `test_evaluation.py`) were kept as-is because `master` did not touch them since the real merge base. Verified that the merged tree equals `master` plus the branch's diff, byte for byte.
… function to a grid A grid built for an instant selector intentionally keeps Prometheus stale markers (`fromSelector` passes `filter_stale_markers = false`); they are dropped only at finalization. When such a grid is consumed by `applyFunctionOverRange` - for example by a subquery like `last_over_time(m[40s:10s])` - it never reaches that finalizer, and `timeSeriesFromGrid` only skips NULL entries, so a stale step was turned into a real `NaN` sample: `last_over_time` returned nothing instead of the last real sample, and `changes` counted the stale step as a change. Moved the stale-marker dropping out of `applySetBinaryOperator` into the shared `dropStaleMarkers` and applied it to the `VECTOR_GRID` argument of a range function. Added `05044_promql_stale_marker_in_subquery_range`, which writes the staleness NaN bit pattern directly into the samples table and checks all three cases.
The Prometheus stale marker (`0x7ff0000000000002`) was normalized only in the set operators and in `applyFunctionOverRange`, so every other consumer of an instant vector still saw it as an ordinary value. Arithmetic, unary and comparison operators and aggregations quiet the NaN payload (`0x7ff0000000000002 + 1` is `0x7ff8000000000002`), so the marker check at finalization no longer recognizes it and the stale step leaks out as a visible `NaN` sample: `stale_counter + 1`, `-stale_counter` and `sum(stale_counter)` all returned `nan` at the stale step, and `stale_counter != bool 0` returned `1` for a series which is absent there. Normalize the markers where the grid of an instant selector is built instead - `fromSelector` is the only place which produces a grid carrying them, because the raw samples keep the markers on purpose so that a marker hides the samples before it while `timeSeriesLastToGrid` picks the last sample of every step. Once the grid is built, a stale step simply means "the series is absent here" for every consumer, so a single `dropStaleMarkers` there covers arithmetic, unary and comparison operators, functions, aggregations, set operators and subqueries alike.
…nary-operators
Master landed its own Prometheus stale-marker handling ("Fix PromQL stale-marker
selector semantics"): `fromSelector` now filters the markers from range selectors and
replaces them with NULL in the grid of an instant selector (`replaceStaleMarkersWithNulls`),
so no consumer of an instant vector sees a marker. Conflicts in `applyFunctionOverRange`,
`finalizeSQL` and `fromSelector` are resolved by taking master's side, and the branch's
now-redundant `dropStaleMarkers` helper and its use in the set operators are removed.
In the integration tests, the branch's tests are kept next to master's `test_stale_markers`,
and the compliance breakdown keeps the branch's `kind: category` keys with master's
combined-results reporting. The stateless tests insert into the `samples` column, which
master renamed from `time_series`.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The AST fuzzer found `Reading from materialized CTE 'prometheus_query_step_N' before its materialization completed` on queries like `SELECT count() FROM prometheusQueryRange(..., 'a or b', ...) LIMIT 0`. `or` was the only set operator where a materialized CTE (the per-group presence mask of the left side) read another materialized CTE (the left side itself). When the plan is embedded by `prometheusQueryRange`, the nested materialization could be read before it completed. The presence mask is now computed by two single-use plain subqueries from the already materialized left side, so the samples table is still read once for it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…nary-operators Master merged its own empty-matcher selector validation (#121099) and the `RemoteRead` synthetic `__name__!=""` matcher, so take master's versions of `PrometheusQueryParsingUtil-antlr.cpp` and `PrometheusRemoteReadProtocol.cpp`. Keep the PR's regrouped compliance cases, updated for master's UTF-8 label name expectations (`~invalid` is a valid label name in Prometheus 3). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master validates label-matcher regular expressions itself and reports an invalid one at the matcher, i.e. byte offset 32 in `SelectorValidationErrorPositionIsByteOffset`, not at the selector start. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 task
Contributor
|
Workflow [PR], commit [d97d794] Summary: ❌
|
vitlibar
marked this pull request as draft
October 2, 2026 18:19
vitlibar
reviewed
Oct 3, 2026
| #include <Common/Exception.h> | ||
| #include <Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorAnd.h> | ||
| #include <Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorOr.h> | ||
| #include <Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorUnless.h> |
Member
There was a problem hiding this comment.
PromQL binary set operators have been already implemented by us, and I don't think we should replace our code with some random code from AI agents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Supersedes #104489 by @BadLiveware (original commits and authorship are preserved). The original branch could not be updated after merging
master, because the merge touches.github/workflowsfiles and the fork push was rejected.Adds native lowering for PromQL set binary operators over ClickHouse
TimeSeriesdata.The implementation supports
and,or, andunlesswith PromQL vector matching rules over packed vector grids. Matching is evaluated per timestamp so a series present on one side at one step does not accidentally match every step.The shared selector validation from the common base has meanwhile landed in
mastervia #121099, so the merge takesmaster's versions ofPrometheusQueryParsingUtil-antlr.cppandPrometheusRemoteReadProtocol.cpp.Related: #104489
Related: #123488
Related: #104271
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 set binary operators
and,or, andunlessover ClickHouseTimeSeriesdata.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123503]