Skip to content

Validate PromQL selector regex matchers (PromQL test scaffolding) - #123488

Closed
alexey-milovidov wants to merge 53 commits into
masterfrom
continue-pr-104484-promql-selector-validation
Closed

alexey-milovidov wants to merge 53 commits into
masterfrom
continue-pr-104484-promql-selector-validation

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Supersedes #104484 by @BadLiveware (original commits and authorship are preserved). The original branch could not be updated after merging master, because the merge touches .github/workflows files and the fork push was rejected.

Related: #104484
Related: #104271

The native PromQL selector validation itself (invalid regex, non-empty matcher requirement, metric name set twice) has meanwhile landed in master via #121099, so this PR now carries the remaining shared test and review scaffolding for the native PromQL-to-SQL feature PRs:

  • ClickHouse PromQL regression corpus in test_compliance.py, grouped by the semantic risk each case protects.
  • A negative-test helper in test_query_api.py asserting that a PromQL query fails with a given error through both prometheusQuery SQL and the HTTP API, pinning unsupported-but-parseable functions and wrong-arity calls.
  • Native-lowering developer notes in src/Storages/TimeSeries/PrometheusQueryToSQL/README.md.
  • A unit test that selector-validation errors report at position N as a UTF-8 byte offset.
  • RemoteRead adds the synthetic __name__!="" matcher only when no matcher is already obviously non-empty, so an exact __name__="foo" request keeps the metric name hoisted and the whole-metric fast path in StorageTimeSeriesSelector (addresses a review comment on the original PR).

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)

🤖 Generated with Claude Code


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

BadLiveware and others added 30 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.
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.
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.
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.
Use the existing eps parameter when checking live Prometheus HTTP results against expected JSON, and compare ClickHouse HTTP output against the live Prometheus result. This keeps numeric drift bounded to eps while preserving exact shape, label, and timestamp checks.
Matcher validation intentionally turns malformed label regexes into PromQL parse errors. Construct RE2 with log_errors disabled so rejected selectors do not also emit internal RE2 error log lines on every parse attempt.
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.
# Conflicts:
#	tests/integration/test_prometheus_protocols/test_compliance.py
…und-trips

`InstantSelector::toString` hoisted a `__name__="foo"` matcher in front of the
braces unconditionally. For a valid selector with more than one `__name__`
matcher, e.g. `{__name__="foo",__name__!="bar"}`, this produced
`foo{__name__!="bar"}`, which sets the metric name twice and is rejected on
reparse (the `timeSeriesSelector` lowering round-trip), so the whole query
errored instead of selecting `foo`.

Only hoist the metric name out of the braces when there is exactly one
`__name__` matcher; otherwise keep all matchers inside the braces, which
Prometheus and our parser accept. Add a gtest round-trip case.
alexey-milovidov and others added 11 commits August 16, 2026 04:58
…-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.
…-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
#104484 (comment)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…-base

Conflict resolution: master already implements the PromQL selector validation
(invalid regex, non-empty matcher requirement, metric name set twice) via
#121099, so the parser and the
`RemoteRead` matcher serialization take master's versions, and the duplicated
parser expectations are dropped in favour of master's dedicated tests. The
byte-offset error-position test is kept with positions matching master's
implementation (regex and duplicate metric name errors point at the matcher).
The `~invalid` label cases in the regression corpus follow master's UTF-8 label
name semantics (accepted by Prometheus 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the synthetic `__name__!=""` matcher only when no matcher is already
obviously non-empty. For a request with an exact `__name__="foo"` matcher, an
extra metric-name matcher prevented hoisting the metric name in
`InstantSelector::toString`, which disabled the whole-metric fast path in
`StorageTimeSeriesSelector::tryMakeWholeMetricIDRangeConditions`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov added pr-not-for-changelog This PR should not be mentioned in the changelog comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Oct 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af48e8e]

Summary: ✅


AI Review

Summary

This PR now mostly carries PromQL test and review scaffolding around functionality that has already landed on master: it expands the regression/compliance corpus, adds stale-marker and malformed-regex integration coverage, documents PromQL-to-SQL lowering constraints, and makes a small RemoteRead matcher-serialization tweak to preserve the exact-metric selector fast path. I did not find a concrete correctness, safety, performance, or metadata issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit af48e8e.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing af48e8e40 with master 9e4e2d2bc (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 49a47ff77; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

9 translation units recompiled, 29 s compile time in total, 9 of them have a recent master baseline.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 49a47ff77

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 90.44% 90.44% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 561 (+22) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 662 -> 662 (+0) 67 -> 67 (+0) 3 -> 3 (+0)

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

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
@vitlibar
vitlibar removed this pull request from the merge queue due to a manual request Oct 2, 2026
@vitlibar vitlibar self-assigned this Oct 2, 2026
@vitlibar

vitlibar commented Oct 2, 2026

Copy link
Copy Markdown
Member

I'll take a look

.matcher_type = PrometheusQueryTree::MatcherType::NE});
/// The synthetic matcher is added only when no matcher is already obviously non-empty:
/// an extra `__name__` matcher would prevent hoisting an exact metric name, which disables
/// the whole-metric fast path in `StorageTimeSeriesSelector`.

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.

We don't need this

- `SQLQueryPiece` carries the lowered expression, result type, storage shape, time grid, scalar values, and metric-name state between lowering steps.
- `SelectQueryBuilder` creates the SQL AST fragments. Lowering code should prefer explicit AST construction over stringly SQL where practical.
- `timeSeries*ToGrid` aggregate functions are the main bridge between raw samples and PromQL's per-evaluation-step vector or matrix results.
- `finalizeSQL.cpp` converts the final `SQLQueryPiece` into the table-function result shape expected by SQL and HTTP API callers.

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.

Looks like some dump from AI agent, we don't need this

@vitlibar

vitlibar commented Oct 3, 2026

Copy link
Copy Markdown
Member

The validation for PromQL regex matchers have been implemented in #121099, so this PR is not needed

@vitlibar vitlibar closed this Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... 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.

3 participants