Skip to content

Support PromQL set binary operators - #104489

Closed
BadLiveware wants to merge 87 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-set-binary-operators
Closed

BadLiveware wants to merge 87 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-set-binary-operators

Conversation

@BadLiveware

@BadLiveware BadLiveware commented May 9, 2026 •

Copy link
Copy Markdown

Adds native lowering for PromQL set binary operators over ClickHouse TimeSeries data.

The implementation supports and, or, and unless with 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.

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 set binary operators and, or, and unless over ClickHouse TimeSeries data.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

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.
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.
@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 [07cc6fc]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
timeseries_to_grid_aggregation_functions #8 FAIL dashboard
order_by_read_in_order #1 FAIL dashboard
timeseries_to_grid_aggregation_functions #18 FAIL dashboard
timeseries_to_grid_aggregation_functions #19 FAIL dashboard
timeseries_to_grid_aggregation_functions #5 slower query history
timeseries_to_grid_aggregation_functions #14 slower query history
timeseries_to_grid_aggregation_functions #15 slower query history

AI Review

Summary

This PR consolidates PromQL set-operator lowering for and, or, and unless, adds parser validation for selectors whose matchers can all match the empty string, and preserves RemoteRead compatibility by injecting a non-empty metric-name matcher before serializing raw protocol matchers back to PromQL. I re-read the current diff together with every existing review thread and did not find a remaining correctness, safety, or coverage gap in the changed code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 07cc6fc.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 230/241 (95.44%) · 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.
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.
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.
# 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
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 07cc6fc4da9db2a73d9d507cf3af5e9ce29abda7 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 5 commits August 8, 2026 23:48
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]>
# Conflicts:
#	src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp
# Conflicts:
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorOr.cpp
#	tests/integration/test_prometheus_protocols/test_evaluation.py
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104489&sha=11a188d230efa5b2252e2815b22cbc5e0df95ee5&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is a LeakSanitizer report unrelated to this PR: a direct leak of DB::UniqExactSet::SharedTwoLevelSet allocated in doDeepCopyIfNeeded (src/AggregateFunctions/UniqExactSet.h:441) during UniqExactSet::merge via AggregateFunctionMerge::add — i.e. a uniqExact/-Merge aggregation code path this PR does not touch. I found no existing open issue matching this stack (it is distinct from #114291 and #113954).

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already merged: #114053, Do not run the LeakSanitizer check on the forced exit path (merged 2026-08-13 08:40Z). No separate PR needed.

Why it covers this report. The reporting server (pid 3216) took the forced branch:

22:15:26 Received termination signal.
22:15:26 Closed all listening sockets. Waiting for 28 outstanding connections.
22:16:26 Closed connections. But 28 remain.
22:16:26 Will shutdown forcefully.

That is Server.cpp:3682, the exact call site #114053 changes from safeExit(0) to safeExit(0, LeakCheck::SkipAndReport). safeExit runs __lsan_do_leak_check(), so the check stopped the world with 28 connection handlers still mid-query and classified memory they still owned. All four blocks in the report (35072 direct + 231/10/15 indirect, 8194304 bytes total) root in one live uniqExact -Merge aggregation under Aggregator::executeImpl, which is consistent with a running query rather than a leak: nothing had dropped those states yet.

The fix is not in this build. The job ran 2026-08-12 19:43Z, ~13h before #114053 merged; base/base/safeExit.h at the newest master commit in the job's own master_commits has no LeakCheck enum, and the skip notice Not running the leak check: other threads are still running. does not appear in stderr.log.

On the tracking issue: I agree none exists, and none is needed now that the cause is fixed. If a report with this stack appears on a build that does contain #114053, that would be a different defect and worth a fresh issue.

…it/promql-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 ClickHouse#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 ClickHouse#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.
alexey-milovidov and others added 4 commits September 7, 2026 23:39
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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master b1224b869

Suite Baseline Current Delta
Prometheus compliance 96.47% 96.79% +0.32%
Extended support (upstream engine tests) 76.50% 76.50% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 520 -> 543 (+23) 3 -> 2 (-1) 16 -> 16 (+0)
Extended support (upstream engine tests) 560 -> 560 (+0) 147 -> 147 (+0) 25 -> 25 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 96.79% vs master baseline 96.47% (b1224b869). 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

🕵 Superseded by #123503. I merged master and resolved the conflicts, but I could not push to this branch: the merge touches .github/workflows files, and GitHub rejected the push to the fork. The new PR keeps your original commits and authorship. Thank you, @BadLiveware!

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.

5 participants