Repository navigation
Validate PromQL selector regex matchers (PromQL test scaffolding) - #123488
alexey-milovidov wants to merge 53 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.
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.
…-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 Co-Authored-By: Claude Opus 5.5 (1M context) <[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]>
|
Workflow [PR], commit [af48e8e] Summary: ✅
AI ReviewSummaryThis PR now mostly carries PromQL test and review scaffolding around functionality that has already landed on Final Verdict
LLVM Coverage ReportMeasured on commit af48e8e.
Changed lines: Changed C/C++ lines covered: 21/21 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 29 s compile time in total, 9 of them have a recent master baseline. |
PromQL Compliance ReportBaseline: S3 master
Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream Note: Prometheus compliance score is unchanged vs baseline. |
|
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`. |
| - `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. |
There was a problem hiding this comment.
Looks like some dump from AI agent, we don't need this
|
The validation for PromQL regex matchers have been implemented in #121099, so this PR is not needed |
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/workflowsfiles 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
mastervia #121099, so this PR now carries the remaining shared test and review scaffolding for the native PromQL-to-SQL feature PRs:test_compliance.py, grouped by the semantic risk each case protects.test_query_api.pyasserting that a PromQL query fails with a given error through bothprometheusQuerySQL and the HTTP API, pinning unsupported-but-parseable functions and wrong-arity calls.src/Storages/TimeSeries/PrometheusQueryToSQL/README.md.at position Nas a UTF-8 byte offset.RemoteReadadds 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 inStorageTimeSeriesSelector(addresses a review comment on the original PR).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Not for changelog.
Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/123488]