Repository navigation
Support PromQL date/time functions called without arguments - #111869
Conversation
In Prometheus, the date/time functions (day_of_month, day_of_week, days_in_month, day_of_year, hour, minute, month, year) are variadic with 0 or 1 arguments: a zero-argument call is equivalent to calling the function on vector(time()), i.e. it is evaluated at each step timestamp in UTC and returns a single series with an empty label set. Previously such queries were rejected with "Function 'X' expects 1 arguments, but was called with 0 arguments". Now, when no argument is given, the converter substitutes the evaluation time as an implicit argument (extracted from the time() implementation as makeTimeQueryPiece()), matching Prometheus behavior. Calls with one argument work as before.
|
Workflow [PR], commit [4906c15] Summary: ✅
AI ReviewSummaryThis PR makes PromQL date/time functions accept the zero-argument form and keeps both Final Verdict✅ No new findings on the current head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 72/82 (87.80%) · Uncovered code |
Stateless tests failure on the previous run is unrelated: server died while running 03915_exchange_tables_race (known flaky, see ClickHouse#110133).
|
The stateless-tests failure is unrelated to this PR: the server died while running |
Stress test (amd_debug) failure is unrelated: Logical error 'Inconsistent KeyCondition behavior' (known signature STID 5182-2f27), KeyCondition is not touched by this change.
…oid Float32 precision loss makeTimeQueryPiece() (used by time()) legitimately casts the evaluation time to context.scalar_data_type, which can be Float32 for a TimeSeries table with a Float32-typed value column. applyDateTimeFunction() reused that same helper for the 0-argument case (day_of_week, day_of_month, days_in_month, day_of_year, minute, hour, month, year), so the synthesized evaluation time was rounded to Float32 precision (~128 seconds at today's epoch magnitude) before toDateTime64()/toHour()/toMinute()/etc. ever saw it - enough to flip the returned minute/hour/etc. near a boundary. This affected both a single evaluation time (instant queries) and a range of evaluation times (range queries), confirmed by reproducing both with an unfixed build. Add makeTimeQueryPieceNative(), a sibling of makeTimeQueryPiece() that keeps the evaluation time (or, for a range, the timeSeriesRange() array) typed as context.timestamp_data_type instead of context.scalar_data_type, and use it only in applyDateTimeFunction()'s 0-argument branch. time() itself keeps calling the original makeTimeQueryPiece() unchanged. Add a regression test creating a TimeSeries table with an explicit Float32 value column and checking minute() (0-arg) at a timestamp chosen so the Float32 rounding would flip the minute, for both an instant and a range query. Co-Authored-By: Claude Sonnet 5 <[email protected]>
The previous commit fixed the implicit 0-argument branch of applyDateTimeFunction() (e.g. minute()) to synthesize the evaluation time via makeTimeQueryPieceNative(), avoiding Float32 precision loss on a TimeSeries table with a Float32-typed value column. The PromQL spec says f() is equivalent to f(vector(time())), but the explicit vector(time()) carrier still went through the generic conversion path (fromFunctionTime() -> makeTimeQueryPiece()), which casts the evaluation time down to context.scalar_data_type. So on a Float32 table, minute(vector(time())) still rounded 1770582700 to 1770582656 and returned 30, disagreeing with minute() returning 31 - two equivalent PromQL spellings with different answers. Add asVectorOfTime() to detect the vector(time()) argument shape at the AST level, and, when detected, rebuild that argument with makeTimeQueryPieceNative() (the same helper the 0-argument branch already uses) instead of the lossy piece the generic path already built. Extend the existing Float32-table regression test with sibling assertions for minute(vector(time())), both instant and range, expecting the same answer as the zero-argument form. Verified against the built binary: minute()/minute(vector(time())) and hour()/hour(vector(time())) now agree (31 and 20 respectively) at timestamp 1770582700 on a Float32-valued TimeSeries table, both as instant and range queries. The standalone compliance harness shows no regressions from this change (390 pass / 4 fail / 143 unsupported / 2 ref_mismatch); all non-passing queries are quantile()/histogram_quantile()/ label_replace()/label_join() cases fixed by the unrelated PR ClickHouse#111871, which this branch forked before and does not include. Co-Authored-By: Claude Sonnet 5 <[email protected]>
The previous commit added asVectorOfTime() to special-case the single AST shape vector(time()) as an argument to a date/time function (e.g. minute()), rebuilding it via makeTimeQueryPieceNative() to avoid Float32 precision loss. But scalar() and vector() are semantically pure passthrough wrappers - applyFunctionScalar()'s CONST_SCALAR/SINGLE_SCALAR/SCALAR_GRID cases and applyFunctionVector() both return their argument's SQLQueryPiece unchanged aside from `type`/`node` - so wrapping vector(time()) in scalar(...) or another vector(...) produces the exact same underlying (lossy) value, just with `type` flipped between SCALAR and INSTANT_VECTOR. asVectorOfTime() only matched the single literal shape vector(time()), so minute(vector(scalar(vector(time())))) still rounded through Float32 and disagreed with minute()/minute(vector(time())). Replace asVectorOfTime() with findTimeCallThroughScalarVectorWrappers(), which recursively peels scalar(...)/vector(...) wrapper calls down to a bare time() node, matching the established pattern of "see through semantically-inert wrappers" used elsewhere in this converter. Also peel unary `+` (checked against applyUnaryOperator.cpp: the '+' case is a literal passthrough, `return res;`, while '-' negates and is correctly left alone), since it's the only other value-preserving single-argument wrapper PromQL allows around a bare function call. Extend the Float32-table regression test with minute(vector(scalar(vector (time())))), both instant and range, expecting the same answer as the zero-argument and vector(time()) forms. Verified against the built binary on a Float32-valued TimeSeries table at timestamp 1770582700: minute()/minute(vector(time()))/minute(vector(scalar (vector(time()))))/minute(vector(+time())) all now agree (31), matching hour() variants agreeing at 20; minute(scalar(vector(time()))) still correctly fails type-checking (scalar() produces SCALAR, not INSTANT_VECTOR); ordinary scalar()/vector() uses on non-time() values (vector(3), scalar(vector(3))) are unaffected; unary minus around time() correctly continues to take the generic (non-native) path since it isn't value-preserving. Reproduced the bug live on the unfixed binary first (minute(vector(scalar(vector(time())))) returned 30) before applying the fix. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ppers findTimeCallThroughScalarVectorWrappers() already peeled scalar()/vector()/ unary '+' wrappers around time() before falling back to the lossy context.scalar_data_type cast. Extend it to also peel an Offset node (the "@ <timestamp>" / "offset <duration>" AST wrapper): applyOffset.cpp's offsetEvaluationTime()/setEvaluationTime() are value-preserving no-ops for CONST_SCALAR/SINGLE_SCALAR/SCALAR_GRID pieces (only start_time/end_time/step bookkeeping changes, never scalar_value/select_query), and NodeEvaluationRangeGetter pre-computes each node's evaluation range in a separate upfront pass, already folding the @/offset adjustment into the range it assigns to the wrapped inner expression - so looking up the range for the innermost time() node directly still yields the correctly shifted start_time/end_time. Verified empirically that, per the current PromQL grammar/parser, an Offset node is only ever constructed directly around an InstantSelector, RangeSelector, or Subquery - never directly around a Function or UnaryOperator - so this branch is presently unreachable via any valid PromQL syntax (queries like `vector(time()) @ 123` fail to parse). It's kept as a defensive, provably non-regressing generalization consistent with the existing scalar()/vector()/unary-'+' peeling, documented inline. No new regression test was added for this specific path since no valid query exercises it; all pre-existing regression tests (Float32 date/time precision, SQL-level PromQL parser tests) were re-verified to still pass. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…t_date_time_functions_zero_arg_with_float32_scalar
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 72/82 (87.80%) · Uncovered code |
| /// defensive forward-compatibility (e.g. if the grammar is ever relaxed) and is a verified no-op for every | ||
| /// currently-reachable AST, since it only recurses into cases the pre-existing checks already reject. | ||
| /// Returns nullptr if `node` isn't (possibly wrapped) exactly a bare `time()` call. | ||
| const PQT::Function * findTimeCallThroughScalarVectorWrappers(const Node * node) |
There was a problem hiding this comment.
I don't like the PQT abbreviation. It's likely not from your code. I will send a PR changing it globally.
alexey-milovidov
left a comment
There was a problem hiding this comment.
Everything else LGTM.
|
🕵 The |
…-0arg Resolves the conflict in fromFunctionTime.cpp between this branch's 0-argument-support refactor (splitting fromFunctionTime() into makeTimeQueryPiece()/makeTimeQueryPieceNative() plus a thin argument-count-checking fromFunctionTime() wrapper) and upstream's unrelated change to the same function signature. Also completes the `PQT` -> `PrometheusQueryTree` rename (from upstream PR ClickHouse#113168, "Unwind the `PQT` abbreviation") in the new code this branch adds to fromFunctionTime.cpp/.h and applyDateTimeFunction.cpp, which auto-merged without conflict markers but still referenced the now-removed `PQT` alias.
|
🕵 Both
Neither fix has landed on |
|
🕵 Merged The remaining red, The PR is approved and the AI review reports no findings on the current head. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units9 translation units recompiled, 9 s compile time in total, 6 of them have a recent master baseline. |
Related: #57545
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
PromQL: date/time functions (
hour(),minute(),month(),year(),day_of_week(),day_of_month(),day_of_year(),days_in_month()) can now be called without arguments, defaulting tovector(time())as in Prometheus.Description
In Prometheus, calling a date/time function with no arguments is equivalent to calling it on
vector(time())— it evaluates against each step timestamp of the query. ClickHouse's PromQL implementation rejected such calls withFunction 'hour' expects 1 arguments, but was called with 0 arguments.This change makes
applyDateTimeFunctionaccept 0 or 1 arguments and synthesize the implicitvector(time())argument for the zero-argument form, reusing the query-piece construction extracted fromfromFunctionTime(makeTimeQueryPieceNative). The one-argument path is unchanged.Key Technical & Precision Highlights:
context.timestamp_data_type(nativeDateTime64precision) viamakeTimeQueryPieceNative(). On TimeSeries tables withFloat32value columns, standardmakeTimeQueryPiece()casts evaluation time toFloat32, introducingtime()calls through nestedscalar(...),vector(...), and unary+carriers (e.g.minute(vector(+time())),minute(vector(scalar(vector(time()))))) viafindTimeCallThroughScalarVectorWrappers, ensuring all equivalent PromQL spellings evaluate in the native timestamp domain and yield identical results.Semantics verified against Prometheus 3.5.0: results are identical (single series with empty label set, UTC field values per step) for both instant and range queries.
Testing: new cases in
tests/integration/test_prometheus_protocols/test_evaluation.pycovering all eight functions in instant queries, range queries, and carrier variations (minute(),minute(vector(time())),minute(vector(scalar(vector(time())))),minute(vector(+time()))) on Float32 TimeSeries tables. This flips 7 queries of the PromQL compliance suite ({{.dateFunc}}()variants) from failed to passed.