Repository navigation
Draft: improve TimeSeries PromQL-to-SQL coverage - #104271
BadLiveware wants to merge 51 commits into
Conversation
Split the compliance report's broad failure buckets into actionable PromQL categories for staged TimeSeries work. Deferred histogram coverage, reference/corpus mismatches, should-fail mismatches, date default-argument errors, and implemented-feature result mismatches now surface separately without making the report a hard compliance gate. Validation: python3 -m ci.praktika run "integration" --test test_prometheus_protocols/test_compliance.py::test_promql_compliance -> passed (ci/tmp/promql-logs/test_promql_compliance_pr1_20260505T203957Z.log).
Add deterministic Prometheus protocol evaluation cases for already-supported binary operator behavior around +Inf, -Inf, and NaN inputs. These tests keep PR 2 test-only while documenting how Prometheus range results drop NaN samples for these expressions and preserve infinities through arithmetic and bool comparisons.
Add native PromQL lowering for sum/avg/min/max/count/stddev/stdvar/present_over_time in the existing PrometheusQueryToSQL path. The implementation reuses the converter's grid representation and evaluates each range window with ClickHouse array expressions, while preserving Prometheus metric-name dropping and empty-window behavior. Add integration coverage for instant and range-query forms, empty and nonexistent inputs, infinities, and NaN counting semantics. Validation: - Build (amd_debug): ci/tmp/promql-logs/build_amd_debug_pr3_20260505T221814Z.log - test_function_over_time: ci/tmp/promql-logs/test_function_over_time_pr3_20260505T225615Z.log - test_promql_compliance: ci/tmp/promql-logs/test_promql_compliance_pr3_20260505T225659Z.log
Wire PromQL changes() and resets() through the existing TimeSeries aggregate helpers so the native converter can evaluate those range functions instead of reporting them unsupported. Match Prometheus handling for consecutive NaN samples in changes(), and add differential coverage for reset windows, sparse or empty inputs, special values, and query_range alignment. Validation: Build (amd_debug); test_prometheus_protocols/test_evaluation.py::test_function_over_time; test_prometheus_protocols/test_compliance.py::test_promql_compliance.
Add native lowering for PromQL quantile_over_time through the existing TimeSeries query converter and a timeSeriesQuantileToGrid helper. The helper mirrors Prometheus scalar phi semantics, including NaN and out-of-range phi handling, NaN sample ordering, and weighted interpolation. Non-constant scalar-grid phi remains explicitly unsupported with a user-facing error, matching the current scalar-parameter policy for related operators. Validation: Build (amd_debug); test_prometheus_protocols/test_evaluation.py; test_prometheus_protocols/test_compliance.py::test_promql_compliance.
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.
Lower label_replace and label_join through the existing time-series tag helpers so native PromQL can transform labelsets without introducing a new IR path. The lowering preserves Prometheus UTF-8 label validation, label_replace's empty source-label behavior, metric-name restoration when __name__ is written, and duplicate-labelset merging with overlap detection. Also extends focused Prometheus protocol tests and compliance cases for label replacement, joins, empty label names, UTF-8 label names, regex errors, and replacement syntax. Validation: PYTHONPYCACHEPREFIX=/tmp/ch_pycache_pr7 python3 -m py_compile tests/integration/test_prometheus_protocols/test_evaluation.py tests/integration/test_prometheus_protocols/test_compliance.py; git diff --check; python3 -m ci.praktika run --workflow PR "Build (amd_debug)"; python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_evaluation.py::test_label_functions; python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_compliance.py::test_promql_compliance.
Implement native SQL lowering for PromQL count_values(label, vector) using the existing TimeSeries group/tag representation. The lowering formats sample values as Prometheus label strings, overwrites the destination label before aggregation, handles by/without grouping, and packs per-step counts back onto the vector grid. Also adds focused differential coverage for value formatting, destination-label overwrite, grouping variants, sparse subquery results, and empty inputs, plus compliance cases for count_values variants. Validation: git diff --check; Python py_compile for updated PromQL tests; Dockerized Build (amd_debug) passed; focused test_aggregation_operators passed; test_promql_compliance passed.
Implement native TimeSeries lowering for PromQL absent and absent_over_time using the existing SQLQueryPiece and AST builder pipeline. The lowering produces the synthetic single-series result only when inputs are absent, derives output labels from equality matchers, and keeps regex/negative matchers out of the synthetic labels. Add differential and compliance coverage for present and missing inputs, equality-derived labels, regex and negative matcher behavior, range-query output, and aggregation over absent. Validation: git diff --check; Python py_compile for updated PromQL tests; Dockerized Build (amd_debug) passed; test_prometheus_protocols/test_evaluation.py passed; test_promql_compliance passed.
PromQL scalar(vector) over a range must still produce one scalar value per evaluation step when the input vector is empty, using NaN for the scalar result. Previously the empty-vector path produced a zero-length scalar grid, which failed when converted back to a range vector with timeSeriesFromGrid.\n\nFill the empty VECTOR_GRID aggregation path with typed UInt64 counts and nullable scalar NaN values, and add range evaluation coverage for empty and multi-series scalar(vector) inputs.\n\nValidation:\n- git diff --check\n- PYTHONPYCACHEPREFIX=ci/tmp/pycache-pr10 python3 -m py_compile tests/integration/test_prometheus_protocols/test_evaluation.py\n- python3 -m ci.praktika run --workflow PR "Build (amd_debug)"\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_evaluation.py\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_compliance.py
Add focused PromQL integration coverage for instant selectors with offset and @ modifiers when they are evaluated as range grids. These cases guard evaluation-time behavior without changing production code.\n\nValidation:\n- git diff --check\n- PYTHONPYCACHEPREFIX=ci/tmp/pycache-pr11 python3 -m py_compile tests/integration/test_prometheus_protocols/test_evaluation.py\n- cmake --build build_debug --target clickhouse\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_evaluation.py::test_range_selectors\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_compliance.py::test_promql_compliance
Make the PromQL compliance report more useful for fork-local self-assurance by splitting failures into implemented wrong results, implemented unexpected errors, unsupported/deferred categories, and reference or should-fail mismatches.\n\nThe breakdown is feature/category based so deferred areas remain visible without importing a promshim-style expected-failures allowlist or turning this into an upstream hard gate.\n\nValidation:\n- git diff --check\n- PYTHONPYCACHEPREFIX=ci/tmp/pycache-pr12 python3 -m py_compile tests/integration/test_prometheus_protocols/test_compliance.py\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_compliance.py::test_promql_compliance
Split upstream Prometheus compliance cases from fork-local PromQL regression cases and group the latter by named semantic risk. This keeps custom coverage reviewable, gives future regressions an obvious home, and adds duplicate expanded-query detection without changing fixture data.\n\nCorpus audit:\n- upstream templates: 83\n- fork-local risk-mapped templates: 35\n- expanded queries: 539\n- unique queries: 539\n- duplicates: 0\n\nValidation:\n- git diff --check\n- PYTHONPYCACHEPREFIX=ci/tmp/pycache-pr13 python3 -m py_compile tests/integration/test_prometheus_protocols/test_compliance.py\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_compliance.py::test_promql_compliance\n- python3 -m ci.praktika run --workflow PR integration --test test_prometheus_protocols/test_evaluation.py
Document the discovery boundary for native histogram support in the TimeSeries PromQL path. The note inventories the current float-only storage, remote-write ingestion, and HTTP serialization shape; separates native histograms from classic _bucket compatibility; and proposes a narrow first prototype boundary for maintainer discussion.\n\nValidation:\n- path-existence check for referenced ClickHouse/protobuf files\n- git diff --check\n\nNo build or integration test was run because this is documentation/design discovery only.
…' into promql/native-promql-integration
…ses' into promql/native-promql-integration
…' into promql/native-promql-integration # Conflicts: # tests/integration/test_prometheus_protocols/test_evaluation.py
…tions' into promql/native-promql-integration # Conflicts: # src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionOverRange.cpp # tests/integration/test_prometheus_protocols/test_evaluation.py
… into promql/native-promql-integration # Conflicts: # src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionOverRange.cpp # tests/integration/test_prometheus_protocols/test_evaluation.py
…o promql/native-promql-integration # Conflicts: # tests/integration/test_prometheus_protocols/test_evaluation.py
…mql/native-promql-integration
…/native-promql-integration # Conflicts: # tests/integration/test_prometheus_protocols/test_evaluation.py
…omql/native-promql-integration
…promql/native-promql-integration
… into promql/native-promql-integration
…to promql/native-promql-integration # Conflicts: # tests/integration/test_prometheus_protocols/test_compliance.py
…ance' into promql/native-promql-integration # Conflicts: # tests/integration/test_prometheus_protocols/test_compliance.py
…into promql/native-promql-integration
The integration branch combines simple over-time reducers with quantile_over_time. Quantile_over_time does not have an ImplInfo entry, so raw range-vector handling must not dereference impl_info when deciding whether to groupArray raw samples for simple reducers.
Prometheus date/time helpers treat a missing argument as vector(time()). Native PromQL lowering previously required an explicit instant-vector argument, so no-arg day/month/hour functions failed compliance even though the explicit vector(time()) form worked. Synthesize the same time grid used by time() as an instant-vector argument before applying the existing date function lowering. This keeps the change isolated to date/time function semantics and makes it cherry-pickable as a standalone compliance fix. Validation: local clickhouse build passed; PromQL compliance moved from 489/550 to 496/550 passed.
Make PromQL over-time lowering build AST predicates with explicit ownership order so clang-tidy does not see unsequenced use-after-move paths. Also reserve combined capacity when merging quantile buckets to avoid rehashing already-present samples during aggregate-state merges. Validation: cmake --build build_debug --target clickhouse; targeted clang-tidy use-after-move check; git diff --check.
…l-integration # Conflicts: # tests/integration/test_prometheus_protocols/test_compliance.py
The upstream compliance corpus marks {__name__=~".*"} as an expected parse failure because PromQL requires vector selectors to include a non-empty matcher. Keep the parser unit coverage aligned with that expectation instead of treating the query as a valid selector.
When both sides of a binary operator lower from the same vector expression and no vector-matching modifier is present, evaluate the vector once and apply the operation with the same values array for both operands. This keeps the usual duplicate-series checks for metric-name dropping, while avoiding a second TimeSeries scan and join for shapes like rate(x[5m]) + rate(x[5m]).
Lower avg_over_time and max_over_time through dedicated TimeSeries aggregate functions instead of per-grid array filtering. The new aggregates keep the PromQL range window semantics and handle NULL, duplicate timestamps, NaN, and infinities while emitting the same grid shape expected by the existing converter. Validation: - cmake --build build_debug --target clickhouse - build_debug/src/unit_tests_dbms --gtest_filter='PromQLParser.ComplianceQueries' - build_debug/programs/clickhouse local --multiquery < tests/queries/0_stateless/03254_timeseries_functions_various_arguments.sql
Aggregate functions may canonicalize parameters while they are created; TimeSeries grid aggregates normalize timestamp parameters to the timestamp argument scale. The Array combinator wraps the created aggregate and must report the same effective parameters as the nested function, otherwise state metadata can diverge and debug builds fail the parameter consistency check. Also make Prometheus-side integration expectations use the existing epsilon-aware JSON comparator when a test supplies eps, avoiding architecture-specific float spelling differences. Validation: - cmake --build build_debug --target clickhouse - build_debug/src/unit_tests_dbms --gtest_filter=PromQLParser.ComplianceQueries - build_debug/programs/clickhouse local -q SELECT_timeSeriesQuantileToGridArray_repro - build_debug/programs/clickhouse local --multiquery < tests/queries/0_stateless/03254_timeseries_functions_various_arguments.sql
Use the project memory-tracking multiset alias for the max_over_time sliding window and allow that alias to take the custom comparator needed for PromQL NaN ordering. Validation: - cmake --build build_debug --target clickhouse - build_debug/programs/clickhouse local --multiquery < tests/queries/0_stateless/03254_timeseries_functions_various_arguments.sql - git diff --check
LLVM Coverage Report
Changed lines: 81.92% (1826/2229) | lost baseline coverage: 6 line(s) · Uncovered code |
|
The |
|
It seems many parts of this PR have been already implemented:
What is missing: some functions like clamp, absent, round, timestamp, histogram functions. Can you please make separated PRs dedicated to adding/improving specific things, one thing per PR? If everything is in one big PR then it's difficult for review and easily outdates. |
Hi, yes. This PR has been superseded by split out PRs, I will close this PR:
|
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Not for changelog yet. This is a draft visibility PR for early maintainer feedback and is expected to be split into smaller reviewable PRs before merge.
Documentation entry for user-facing changes
Documentation is not complete in this draft. If maintainers agree with the direction, the split PRs will include user-facing documentation for the supported PromQL surface and remaining histogram limitations.
Draft / early-feedback PR
This PR makes visible an ongoing effort to improve ClickHouse TimeSeries native PromQL-to-SQL conversion coverage. It is intentionally a large integration branch and not intended to merge as one PR. The goal is to let maintainers see the current direction, semantic choices, validation shape, and split plan before the work is carved into smaller upstreamable PRs.
Development disclosure: this branch is mostly AI-developed, with human review/steering. The semantics and test coverage are a port of learnings from
BadLiveware/promshim-clickhouse: specifically, PromQL behavior and PromQL-to-ClickHouse-SQL compatibility knowledge. It does not port promshim's Go IR or renderer wholesale; the implementation keeps ClickHouse's existingPrometheusQueryTree::Node -> SQLQueryPiece -> ASTPtrconversion architecture.What this integration branch contains
High-level areas included in the draft branch:
changes,resets,increase,deriv, andpredict_linear.quantile_over_timeand quantile phi edge semantics.label_replaceandlabel_join.count_values,absent, andabsent_over_time.timestamp,round,clamp_*, selector validation, subquery/offset alignment.histogram_quantilesupport over classic_bucket{le=...}float series. Native histogram implementation remains deferred pending storage/result representation agreement.Compliance coverage
Fresh validation on this integration branch after classic histogram quantile support reports:
Classic
histogram_quantile(...)over_bucket{le=...}float series is now covered in the compliance corpus. Native histogram support remains a separate deferred design/prototype item.Non-obvious implementation choices to review
These are called out explicitly so maintainers can decide whether they like the shape or want the split PRs recut differently:
applyOneArgumentMathFunction.cppmaps PromQL functions to AST transforms instead of only ClickHouse function names becauseround()is not a direct alias: PromQL supports an optionalto_nearestscalar, defaults to nearest1, and rounds ties up (floor(x / to_nearest + 0.5) * to_nearest). Most entries still render simple one-argument ClickHouse calls; this could be recut as direct names plus one override if preferred.timeSeriesReplaceTag.cppvalidates/extracts thelabel_replace()source-label argument as a constant string rather than a tag-name helper. Prometheus validates the destination label, but an empty or missing source label is valid and matches the empty string.and/or/unlessbehave as if it matched at every timestamp.label_replace()/label_join()can collapse different input series to the same label set. The lowering keeps that visible as an invalid duplicate result vector instead of silently choosing one sample.absent()copies only unambiguous equality matchers into the synthetic output label set.absent_over_time()uses a range aggregation only as a per-step presence probe; sample values are discarded.quantile_over_timesorts NaN before numeric samples to match Prometheus interpolation behavior, treats out-of-range/NaN phi values as Prometheus does, and keeps duplicate timestamp handling deterministic when one duplicate value is NaN.quantile_over_time(<phi>, v[range:step]).Planned split before merge
If maintainers are open to the direction, I expect to split this into smaller PRs roughly along these boundaries:
changes,resets,increase,deriv,predict_linear).count_values,absent, and duplicate-labelset handling.timestamp, date defaults,round, clamp functions, selector validation, subquery/offset alignment).I am looking for feedback on the architecture and preferred split shape before spending review time polishing each slice.
Validation run for the current draft branch
Recent validation from the fork integration branch:
git diff --check: passedcmake --build build_debug --target clickhouse: passedtest_prometheus_protocols/test_evaluation.py::test_function_over_time:1 passedtest_prometheus_protocols/test_evaluation.py::test_function_histogram_quantile:1 passedtest_prometheus_protocols/test_evaluation.py:20 passed1 passed; report is550 / 550,0failed,0unsupported