Repository navigation
Align PromQL scalar, timestamp, and clamp lowering - #104494
BadLiveware wants to merge 69 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.
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
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.
Add native lowering for the remaining simple scalar/vector functions covered by the non-histogram compliance gaps: timestamp(), round(), clamp_min(), clamp_max(), and clamp(). timestamp() is implemented as a grid-aware function so it returns the evaluation timestamp only where the input vector has a sample. clamp() preserves Prometheus' empty result when constant max < min, while clamp_min/max and round are applied value-by-value through the existing simple-function path. Validation: local clickhouse build passed; PromQL compliance moved from 505/550 to 517/550 passed, leaving only skipped histograms, range regression/increase functions, and two expectation mismatches.
Support valid round(v, to_nearest) calls, keep timestamp(vector(...)) range queries on the per-step grid, and propagate NaN clamp bounds instead of falling through ClickHouse comparisons. Also make duplicate timestamp handling in quantile_over_time deterministic around NaN by preferring numeric samples over NaN, matching the existing PromQL NaN sort policy. Validation: red baseline focused conversion/math tests failed before the implementation; build_debug clickhouse target passed; focused conversion/math integration tests passed; PromQL compliance integration test passed; duplicate-NaN quantile local checks now return [1] for both insertion orders.
timestamp() over an instant selector must report the timestamp of the selected source sample, not the evaluation timestamp. Lower that direct selector case by scanning the selector lookback window and aggregating raw sample timestamps with the same lookback window used for selection. Add integration coverage for instant and subquery timestamp(test) behavior.
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
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.
|
Workflow [PR], commit [d948b33] Summary: ❌
AI ReviewSummaryThis PR substantially improves Findings❌ Blockers
💡 Nits
Tests
Final Verdict❌ Needs changes before merge. The stale-marker fixes and selector validation look good at head, but the two blockers above still produce wrong PromQL results. |
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.
…plit/promql-scalar-time-functions
PromQL `clamp` returns an empty vector when `min > max`. Preserve that rule for single-row scalar bounds such as `scalar(...)`, not just for constant scalar arguments known during planning.
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.
…-functions # Conflicts: # src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionScalar.cpp
…-time-functions # Conflicts: # tests/integration/test_prometheus_protocols/test_compliance.py
The `timestamp(selector)` lowering replaced the raw sample value with `toFloat64(timestamp)` before `timeSeriesLastToGrid`, so the value handed to the finalizer was the timestamp rather than the original sample value. The finalizer detects Prometheus stale markers by checking the sample value's bit pattern (`reinterpretAsUInt64(value) != 0x7ff0000000000002`), so this hid the stale marker: if the latest sample within the lookback window was a stale marker, `timestamp(test)` / `timestamp(test offset ...)` returned that stale sample's timestamp instead of an empty result. Build two aligned last-sample grids over the same window: one over the original value (used only to detect empty positions and stale markers) and one over the sample timestamp (the value `timestamp` must return). Null out grid positions whose last sample is missing or stale so the normal vector-grid finalizer drops them, while keeping genuine timestamps.
Add a `stale_test` series whose most recent samples within the lookback window are Prometheus stale markers, with an earlier non-stale sample so an empty result proves `timestamp` drops the stale last sample rather than falling back. Verify `timestamp(stale_test)` and `timestamp(stale_test offset 30s)` return an empty vector both in Prometheus and in ClickHouse.
`round` now accepts one or two arguments, but the shared invalid-arity check in `checkArgumentTypes` still reported `expects 1 arguments` for unsupported calls such as `round(v, 1, 2)`, contradicting the new contract. Report `1 or 2` for `round` and keep `1` for the unary math functions. Addresses AI Review finding on PR ClickHouse#104494 (ClickHouse#104494). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The public `prometheusQuery` / `prometheusQueryRange` docs still listed
the old supported function set and did not mention the tightened
selector validation. Document the newly supported functions
(`timestamp`, `round`, `clamp`, `clamp_min`, `clamp_max`, and the
no-argument form of the date/time helpers) and the rule that a selector
must contain at least one non-empty matcher (rejecting selectors such as
`{job=~".*"}`).
Addresses AI Review finding on PR ClickHouse#104494
(ClickHouse#104494).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…r(time())`, not `time()` `applyDateTimeFunction` accepts only an `INSTANT_VECTOR` argument, while `time()` lowers to a scalar, so an explicit `day_of_week(time())` call is rejected by the converter. Correct the note in `prometheusQuery.md` and `prometheusQueryRange.md` to say the omitted argument defaults to the equivalent of `vector(time())`.
The `round` lowering multiplied, floored and divided the selector value before finalization, which quiets the Prometheus stale-marker `NaN` payload (`0x7ff0000000000002`) into an ordinary `NaN`. The finalizer matches the marker by its exact bit pattern, so `round(stale_test)` kept a `NaN` sample instead of producing an empty result. Pass stale samples through `round` unchanged. `timestamp` over a computed instant vector replaces the value with a timestamp and only checked for `NULL`, so a stale position survived there as well; it now drops stale positions too, which makes `timestamp(round(stale_test))` empty. Adds regression tests for `round(stale_test)`, `round(stale_test, 0.1)` and `timestamp(round(stale_test))`.
`floor`, `sqrt`, `exp` and the trigonometric functions quiet the stale-marker payload the same way the `round` formula does, and `sgn` replaces it with a number, so a stale sample survived every one of them. Move the guard from the `round` lowering into `applyOneArgumentMathFunction` so every math function keeps stale samples droppable, and cover `floor` and `sgn` with tests. Verified with `clickhouse local` over a `TimeSeries` table holding a stale marker: `round`, `round(v, 0.1)`, `floor`, `sgn`, `sqrt` and `timestamp(round(...))` all return an empty result at a stale evaluation time and unchanged values otherwise; a genuine `NaN` such as `ln(-1)` is still kept.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 583/636 (91.67%) · Uncovered code |
…-time-functions # Conflicts: # docs/en/sql-reference/table-functions/prometheusQuery.md # docs/en/sql-reference/table-functions/prometheusQueryRange.md # src/Storages/StoragePrometheusQuery.cpp
…elpers Address the AI review blockers on ClickHouse#104494. `clamp_min`, `clamp_max` and `clamp` return the bound itself when it is `NaN`, so `clamp_min(stale_test, NaN)` replaced the Prometheus stale marker with a fresh `NaN` and the finalizer could no longer recognize the stale sample by its `0x7ff0000000000002` bit pattern; the stale series was reported instead of being dropped. The `DateTime` helpers (`day_of_week`, `minute`, `month`, ...) cast the sample value with `toDateTime64` before anything strips stale samples, and `convertToDecimal` rejects non-finite input, so `day_of_week(stale_test)` threw `Cannot convert infinity or NaN to decimal` instead of returning an empty vector. Prometheus drops stale samples before it evaluates a function, so the marker is now passed through in both places and dropped at finalization. The `keepStaleMarker` helper introduced for one-argument math functions is moved into a shared `staleMarker.h`, together with `replaceStaleMarker`, which substitutes a valid timestamp for the marker so that the conversion cannot throw. Regression tests: `clamp_min(stale_test, NaN)`, `clamp_max(stale_test, NaN)`, `clamp(stale_test, NaN, 2)`, `day_of_week(stale_test)` and `minute(stale_test)` all return an empty vector.
`master` moved the documentation from the Docusaurus tree under `docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every file this branch edits. The edits are replayed at the new paths: - `docs/en/sql-reference/table-functions/prometheusQuery.md` -> `docs/reference/functions/table-functions/prometheusQuery.mdx` - `docs/en/sql-reference/table-functions/prometheusQueryRange.md` -> `docs/reference/functions/table-functions/prometheusQueryRange.mdx`
Conflicts resolved: - `applyDateTimeFunction.cpp`: master gained its own implementation of the no-argument date/time helpers (`makeTimeQueryPieceNative` + `findTimeCallThroughScalarVectorWrappers`), which keeps native `DateTime64` precision; dropped this branch's earlier `makeDefaultTimeVectorArgument` in favour of it, keeping the branch's stale-marker handling around the `toDateTime64` conversion. - `PrometheusHTTPProtocolAPI.cpp`: kept master's `lookback_delta` handling and this branch's later placement of the `PrometheusQueryTree` parsing. - `prometheusQuery.mdx` / `prometheusQueryRange.mdx`: union of master's `deriv` row and this branch's `round`/`clamp*` entries. - `test_evaluation.py`: union of both sets of `days_in_month` tests.
Master removed the \`PQT\` alias from \`ConverterDefs.h\`; spell out \`PrometheusQueryTree\` in the files added by this pull request so the merged tree builds again.
`scalar` aggregated the vector grid with `count`/`any` (instant) and `countForEach`/`anyForEach` (range grid), which only skip `NULL`. A sample carrying the Prometheus stale marker (a `NaN` with the payload `0x7ff0000000000002`) was therefore counted as a present value, so `scalar(stale_test)` returned the marker itself instead of collapsing to `NaN` as it does for an empty instant vector, and the marker leaked into every expression built on top of that scalar. Added `nullifyStaleMarker` to `staleMarker.h` and applied it to the values before those aggregations, so a stale sample is treated as an absent sample. Verified with `clickhouse local` over a `TimeSeries` table holding a stale-only series: before the change `SELECT hex(reinterpretAsUInt64(value)) FROM prometheusQuery(ts, 'scalar(stale_test)', 160)` returned `7FF0000000000002`, after it returns `7FF8000000000000`; live series are unaffected. Regression tests for `scalar(stale_test)` and `vector(scalar(stale_test))[40:10]`, plus a direct check of the returned bit pattern (both spellings print as `NaN` over the HTTP API).
| timeSeriesTimestampToAST(argument.start_time, context.timestamp_data_type), | ||
| timeSeriesTimestampToAST(argument.end_time, context.timestamp_data_type), | ||
| timeSeriesDurationToAST(argument.step, context.timestamp_data_type)), | ||
| make_intrusive<ASTLiteral>(fmt::format("Array({})", context.scalar_data_type->getName()))); |
There was a problem hiding this comment.
timestamp() is still being forced through scalar_data_type here, so on TimeSeries(Float32) tables it cannot represent present-day epoch seconds exactly. That is the same precision loss this PR had to work around for the zero-argument DateTime helpers: around 1770582700, Float32 rounds to 128-second buckets, so timestamp(vector(1)), timestamp(test), etc. return the wrong value over both SQL and the HTTP API on prometheus_f32-style tables.
Because timestamp() is newly added in this PR, it needs the same native-timestamp treatment as minute()/day_of_week() here (or a Float64 result type for time() / timestamp()), plus a focused regression on a Float32 TimeSeries table.
|
|
||
| expression.select_query = builder.getSelectQuery(); | ||
|
|
||
| /// `NodeEvaluationRangeGetter` has already planned the child range selector at the fixed evaluation time. |
There was a problem hiding this comment.
The new RAW_DATA special case fixes fixed-time range selectors, but fixed-time subqueries are still collapsed to values[1] by the SCALAR_GRID / VECTOR_GRID branch above. That branch is fine for instant vectors evaluated at one fixed time; it is wrong once the child is already a subquery/range vector, because values then contain the whole fixed inner grid.
A concrete trace is last_over_time(vector(time())[20s:10s] @ 160): the subquery should contain [150, 160] and return 160, but arrayResize(..., values[1]) rewrites it to [150] before last_over_time runs, so the result becomes 150. We need a range-vector-specific @ path here that preserves the full inner grid and only repeats after the consuming range function has aggregated it.
|
Closing in favor of #111870 |
Closes scalar/vector and time-function edge cases in ClickHouse
TimeSeriesnative PromQL-to-SQL conversion.The changes cover scalar-grid alignment, default-argument date functions,
timestamp,round,clamp, selector validation, and offset range-grid behavior. The goal is to match Prometheus query-range semantics and avoid accidental per-request timestamp or per-grid misalignment.Split out from the integration draft #104271; shared base #104484.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improved native PromQL-to-SQL lowering for scalar and time functions over ClickHouse
TimeSeriesdata, includingtimestamp, default-argument date functions,round,clamp, selector validation, and scalar-grid range-query alignment.Documentation entry for user-facing changes