Skip to content

Support PromQL date/time functions called without arguments - #111869

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
valerypetrov:promql/date-funcs-0arg
Aug 9, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
valerypetrov:promql/date-funcs-0arg

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Related: #57545

Changelog category (leave one):

  • Experimental Feature

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 to vector(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 with Function 'hour' expects 1 arguments, but was called with 0 arguments.

This change makes applyDateTimeFunction accept 0 or 1 arguments and synthesize the implicit vector(time()) argument for the zero-argument form, reusing the query-piece construction extracted from fromFunctionTime (makeTimeQueryPieceNative). The one-argument path is unchanged.

Key Technical & Precision Highlights:

  1. Native DateTime64 Domain Preservation: Keeps evaluation timestamps in context.timestamp_data_type (native DateTime64 precision) via makeTimeQueryPieceNative(). On TimeSeries tables with Float32 value columns, standard makeTimeQueryPiece() casts evaluation time to Float32, introducing $\sim 128$-second timestamp rounding errors. Using native precision prevents calendar/minute/hour boundary shifts.
  2. Value-Preserving Wrapper Peeling: Detects time() calls through nested scalar(...), vector(...), and unary + carriers (e.g. minute(vector(+time())), minute(vector(scalar(vector(time()))))) via findTimeCallThroughScalarVectorWrappers, 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.py covering 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.

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.
@nikitamikhaylov nikitamikhaylov added comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... can be tested Allows running workflows for external contributors labels Jul 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4906c15]

Summary: ✅


AI Review

Summary

This PR makes PromQL date/time functions accept the zero-argument form and keeps both f() and explicit time()-carrier spellings on the native timestamp path so Float32 TimeSeries tables no longer round the evaluation timestamp before extracting calendar fields. I reviewed the current PR head, the current diff, the prior inline threads and replies, and the updated tests, and I did not find any remaining correctness, compatibility, or coverage issues that warrant new review comments.

Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.90% 86.50% +5.60%
Functions 91.30% 91.90% +0.60%
Branches 72.90% 78.80% +5.90%

Changed lines: Changed C/C++ lines covered: 72/82 (87.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 25, 2026
Stateless tests failure on the previous run is unrelated: server died
while running 03915_exchange_tables_race (known flaky, see ClickHouse#110133).
@valerypetrov

Copy link
Copy Markdown
Contributor Author

The stateless-tests failure is unrelated to this PR: the server died while running 03915_exchange_tables_race (known flaky test, see #110133, same amd_llvm_coverage/old-analyzer configuration), and the other 8 flagged tests were collateral UNKNOWNs from the same server death. Sibling shards 1/3 and 3/3 of the identical configuration passed. Pushed an empty commit to retrigger CI.

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]>
valerypetrov and others added 2 commits July 28, 2026 23:12
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]>
valerypetrov and others added 2 commits July 29, 2026 20:40
…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
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 72/82 (87.80%) · Uncovered code

Full report · Diff report

/// 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)

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.

I don't like the PQT abbreviation. It's likely not from your code. I will send a PR changing it globally.

@alexey-milovidov alexey-milovidov left a comment

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.

Everything else LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 3, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The Upgrade check (amd_release) failure is unrelated to this PR: the errors are DiskLocalCheckThread races on the shared clickhouse_disk_checker_<uuid> probe file (disks disk1_02961…disk4_02961 and backups all check the same file and one thread unlinks it while others open it, giving CANNOT_UNLINK/FILE_DOESNT_EXIST). A fix is already in progress: #110773 (give each disk check thread its own probe file). I merged the latest master into this branch to retrigger CI.

…-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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Both Stress test failures on 50c9312 are unrelated to this PR (which only touches PromQL date/time function translation):

Neither fix has landed on master yet, so re-merging master would not clear these reds. The rest of the CI run is still in progress.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master again (merge commit 2ca2e304b33) to pull in #113225, which merged into master today and fixes the Stress test (amd_asan_ubsan) red on this PR (the fleet-wide Logical error: 'column->size() == num_rows' from 04756_nested_sibling_shared_offsets_prefetch.sql, tracked in #113411). Verified both changed translation units (applyDateTimeFunction.cpp, fromFunctionTime.cpp) still compile after the merge.

The remaining red, Stress test (arm_debug), is the stress-harness fault-injection verify timeout — unrelated to this PR; fix is in #113248.

The PR is approved and the AI review reports no findings on the current head.

@alexey-milovidov alexey-milovidov added can be tested Allows running workflows for external contributors and removed can be tested Allows running workflows for external contributors labels Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4906c15cf with master a96691076 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 16bd8e494; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 689.52 MiB 687.14 MiB -2.38 MiB (-0.34%)

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 units

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

Job report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit e9bb68e Aug 9, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... pr-experimental Experimental Feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants