Skip to content

Validate PromQL selector regex matchers - #104484

Closed
BadLiveware wants to merge 51 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-common-base
Closed

BadLiveware wants to merge 51 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-common-base

Conversation

@BadLiveware

@BadLiveware BadLiveware commented May 9, 2026 •

Copy link
Copy Markdown

Adds native PromQL selector validation plus shared test and review scaffolding for the native PromQL-to-SQL feature PRs: parser expectation coverage, ClickHouse PromQL regression corpus organization, native-lowering developer notes, and targeted native error-path tests.

The parser now follows Prometheus selector semantics: a vector selector must include at least one matcher that cannot match the empty string, so {__name__=~".*"} is invalid because .* can match an empty metric name, and an outside metric name combined with an in-brace __name__ matcher (foo{__name__="bar"}) is rejected. Invalid regular expressions in matchers are rejected at parse time. Keeping these as expected successes would make later compliance deltas misleading.

The compliance harness could already observe and report errors, and the low-level query helpers could execute calls that are expected to fail. What was missing was a small focused evaluation helper that says: this ClickHouse PromQL query should fail with this error through both prometheusQuery SQL and the HTTP API. This PR adds that negative-test shape and pins two current native-lowering errors: unsupported-but-parseable functions and wrong-arity calls.

Further changes made while addressing review:

  • InstantSelector::toString hoists the metric name in front of the braces only when there is exactly one __name__ matcher, so valid selectors with multiple __name__ matchers survive a round-trip.
  • Prometheus stale markers are filtered out on the instant-vector and range-vector grid paths of the PromQL-to-SQL conversion (Float64 value columns; Float32 tables lose the stale NaN payload at ingest and are a known limitation).
  • A subquery under @ <timestamp> keeps its fixed evaluation window: setEvaluationTime no longer collapses a range-vector grid, and range-vector functions aggregate over the fixed range before spreading the result over the query grid.
  • Selector-validation errors report at position N as a UTF-8 byte offset, consistent with the other parser errors.

Split out from the integration draft #104271.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not for changelog.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

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.
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 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.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.

@BadLiveware BadLiveware May 10, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont know if you want things like this living in the repo, but this is a distillation for what I think are high value future optimizations(They were for querying from an external system). Other (mostly discarded) attempts are documented here for the transpiler https://github.com/BadLiveware/promshim-clickhouse/blob/main/docs/tier2-optimization-attempts.md

There are likely things in there that were discarded but may be more feasible to implement in ClickHouse itself rather than an outside system

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 README with the native-lowering notes is kept as-is in #123488 (which supersedes this PR); whether it should live in the repository is left to the reviewers there.

@BadLiveware
BadLiveware marked this pull request as ready for review May 10, 2026 03:04
@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 [c4588b6]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
Test script failed FAIL cidb
Logical error: Iceberg data file has A columns while its schema has B fields (STID: 4224-3b20) FAIL cidb

AI Review

Summary

This PR tightens PromQL selector validation, adds regression/compliance coverage around matcher semantics, and documents the PromQL-to-SQL lowering work. The parser-side changes are mostly sound, but the current merge result still has one new RemoteRead performance regression and one previously dismissed stale-marker correctness gap on supported Float32 TimeSeries tables.

Findings

⚠️ Majors

  • [src/Storages/TimeSeries/PrometheusRemoteReadProtocol.cpp:78] Appending a synthetic __name__=~".+" matcher to every RemoteRead selector disables the whole-metric id-range optimization for requests that already have __name__="...". InstantSelector::toString can no longer hoist the metric name, so StorageTimeSeriesSelector::tryMakeWholeMetricIDRangeConditions sees two metric-name matchers and falls back to the expensive id IN <set> analysis path. Preserve the protocol invariant without adding a second metric-name matcher when an exact metric matcher is already present, or bypass the PromQL string round-trip on the RemoteRead path.
  • [dismissed by author -- https://github.com/Validate PromQL selector regex matchers #104484#discussion_r3516531586] Prometheus stale-marker filtering still only works when the TimeSeries value column is Float64. On supported Float32 tables, the stale NaN payload is already lost at ingest, so the reinterpretAsUInt64(...) == 0x7ff0000000000002 checks in fromSelector.cpp can never fire and stale samples still surface as ordinary NaN. This still looks like a real correctness gap unless the Prometheus paths explicitly reject Float32 tables or preserve staleness before the downcast.
Final Verdict

Status: ⚠️ Request changes

  • Keep exact-metric RemoteRead selectors on the whole-metric fast path while still accepting raw empty-matching non-name matchers.
  • Decide the contract for Prometheus stale markers on Float32 TimeSeries tables: either make that schema fail explicitly on the Prometheus paths, or preserve the stale-marker bit pattern before it is truncated.

LLVM Coverage Report

Measured on commit c4588b6.

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: 71/71 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog 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.
alexey-milovidov and others added 3 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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

…-base

Resolve conflicts in `applyFunctionOverRange.cpp` and `applyOffset.cpp` by
taking master's implementation of the fixed `@` modifier over range vectors,
which supersedes the equivalent fix made in this branch, and keep both the new
`start`/`end` label-name tests from master and this branch's selector
validation tests in `gtest_PromQLParser.cpp`.
Master gained support for quoted selector identifiers (`{"foo", job="bar"}`),
which replaced `LabelMatcherContext::labelName` with `selectorIdentifier`, and
moved the `metric name must not be set twice` check inside the matcher loop.
The branch had reverted that work in an earlier merge, so the branch no longer
compiled against the current grammar.

Take master's version of `PrometheusQueryParsingUtil-antlr.cpp` and re-apply
this branch's selector validation on top of it: `matcherMatchesEmptyString`,
`validateSelectorHasNonEmptyMatcher` and `validateSelectorDoesNotSetMetricNameTwice`
now run after all matchers of an instant selector have been collected, and
report the error at the byte offset of the selector itself.

Also update the round-trip expectation for a selector with several in-brace
`__name__` matchers: master now formats the first one as a quoted metric name.
alexey-milovidov added a commit to BadLiveware/ClickHouse that referenced this pull request Aug 26, 2026
…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.
alexey-milovidov added a commit to BadLiveware/ClickHouse that referenced this pull request Aug 26, 2026
…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.
alexey-milovidov added a commit to BadLiveware/ClickHouse that referenced this pull request Aug 26, 2026
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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, the only red on this PR was Stress test (amd_debug) failing with Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-457d) (report). It is unrelated to this PR (it only touches PromQL parsing and PromQL-to-SQL generation, no distributed or parallel-replicas code). Tracking: #81738 and #101325 (same error, sibling STID); the fix appears to be in progress in #113589 — please confirm it covers this signature. The branch has now been merged with current master, so CI has been re-run.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Confirmed, #113589 covers this signature.

The report normalizes the parameters; the concrete values in that run are shard_num=2 shard_count=1 cluster=test_cluster_one_shard_three_replicas_localhost, thrown from ClusterProxy::prepareClusterForParallelReplicas at src/Interpreters/ClusterProxy/executeQuery.cpp:788, reached through StorageView::readImpl and a nested InterpreterSelectQueryAnalyzer::getQueryPlan.

That pins the instance to the provenance defect rather than only to the message:

  • test_cluster_one_shard_three_replicas_localhost is one <shard> with three <replica> entries in tests/config/config.d/clusters.xml (the second <shard> block is commented out), so shard_count=1 is that cluster's own numbering and shard_num=2 cannot have been produced by it. Only a derivation that renumbers shards over each replica while copying the name can produce it, which is exactly what Bind the parallel replicas shard scope to the cluster that produced it #113589 detects.
  • The carrier is a read inside a VIEW carrying its own SETTINGS cluster_for_parallel_replicas, and the first arm of that PR's stateless test is this same cluster with a shipped shard_num=2, i.e. these parameters.
  • The admission guard is on this path: findQueryForParallelReplicas returns nullptr for a foreign shard scope, so the read builds the plain local plan and never reaches the bounds check that threw here.

The same message also fires from a second, unrelated root cause: random ORDER BY injected into an intermediate-stage child plan, fixed by #113266. That is excluded here, because #113266's merge commit is already an ancestor of 7dd0d6896d6d, and this stack has no ReadFromMerge and no injected Sorting frame.

Two side notes on the links. #81738 is closed (completed 2026-04-10); the live tracker is #101325, which #113589 closes. And this abort is a per-run event rather than a property of a given tree: over the last 14 days the message has 51 rows across 14 check families and 39 distinct pull requests, 3 of them on master, most recently 2026-09-02 00:25 UTC. So a green re-run on the new head would not mean it is resolved.

@abashkeev abashkeev added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Sep 4, 2026
alexey-milovidov and others added 2 commits September 16, 2026 02:56
…-base

# Conflicts:
#	src/Storages/TimeSeries/PrometheusQueryToSQL/finalizeSQL.cpp
…tor path

The stale-marker handling used to live only in `finalizeSQL`: the result of
`last_over_time` over an instant selector kept the stale markers in its
`VECTOR_GRID`, and they were filtered out only when the query result was
finalized. Every operator between the selector and the finalization decides
whether a series is present at a step by the presence of its value
(`isNotNull`, `countForEach`, `anyForEach`), so a series whose latest sample
is a stale marker still participated in `count(foo)`, `group(foo)`,
`foo and bar`, `foo or bar`, `foo unless bar`, `scalar(foo)` and so on.

Now `fromSelector` replaces the stale markers with NULL immediately after
`last_over_time`, before any other operator consumes the grid, and the
finalization is back to the version on `master`. Range selectors still filter
the stale markers out of the raw data, so `last_over_time(foo[1m])` keeps
returning the latest non-stale sample, as in Prometheus.

Added regression tests: a bare stale selector, the same selector composed
with aggregations, set operators, arithmetic, `scalar` and `absent`, and the
same in a range query.

Addresses the AI review blocker in
ClickHouse#104484 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: Stateless tests (arm_asan_ubsan, azure, parallel) on the previous head 06e042df failed with AddressSanitizer: heap-use-after-free (STID: 2837-40ba) followed by Server liveness check failed, and provide a fix in a separate PR. This PR touches only PromQL parsing and PromQL-to-SQL generation, so it is unrelated. The two PRs that mention this STID, #116103 and #117129, were closed without merging. If a fix is already in progress, link it here. The branch has been merged with current master and the AI review blocker about stale markers in composed expressions has been fixed, so CI has been re-run.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already merged, so no new PR from me is needed: @Michicosun's #118031 "Fix Crash during Traversal of Execution Graph" merged 2026-09-05T12:07:22Z as 7cf9942b0ada. It rewrites the nodes_mutex handling in ExecutingGraph::updateNode and removeAffectedEdges, which is exactly the frame in that report (updateNode reading a freed std::__list_node<ExecutingGraph::Edge> at ExecutingGraph.cpp:385 while another QueryPipelineEx thread frees it). That merge is also why the two PRs you list are dead ends: #116103 was closed at 12:07:23Z and #117129 at 12:13:52Z, both superseded by it.

The failing build predates the fix by three days, so it could not contain it. 06e042df was committed 2026-09-02T03:31:55Z, the job started 2026-09-02 06:45:46Z, and the tested merge used master b20da91bd (the same master the build profile diff above compares against); 7cf9942b0ada is not an ancestor of 06e042df (diverged, 1958 commits behind).

The current head 27392343d9 does contain it: its merge base with 7cf9942b0ada is 7cf9942b0ada itself. CIDB shows the class extinct since that merge: the last 2837-40ba occurrence anywhere is 2026-09-03, with none in the 11 days since, across every flavour that used to hit it (arm and amd asan_ubsan stateless, AST fuzzer (arm_asan_ubsan), stress). The same query still returns other heap-use-after-free STIDs in that window (4052-3035, 2758-4138), so it is not silently empty. Server liveness check failed there is the tail of the ASAN abort in the same job, not a second failure.

One related follow-up of mine is on your head as well: #119577 "Do not access ports from IProcessor::work()" (merged 2026-09-12) fixed a TSAN race, STID 3732-4438, in the pending-removal-group machinery that #118031 introduced.

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 94e392136

Suite Baseline Current Delta
Prometheus compliance 96.47% 96.79% +0.32%
Extended support (upstream engine tests) 76.37% 76.50% +0.14%
Suite Passed Failed Unsupported
Prometheus compliance 520 -> 543 (+23) 3 -> 2 (-1) 16 -> 16 (+0)
Extended support (upstream engine tests) 559 -> 560 (+1) 148 -> 147 (-1) 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% (94e392136). 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 #123488. I merged master (resolving conflicts; the selector validation itself has meanwhile landed via #121099) and addressed the open RemoteRead review comment, but could not push to this fork branch: the merge touches .github/workflows files and the push was rejected for lack of workflow scope. Your commits and authorship are preserved in the new PR. The Stress test (arm_release) failure here (Iceberg data file has 1 columns while its schema has 2 fields) is unrelated and is being fixed in #121821. 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... manual approve Manual approve required to run CI pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants