Skip to content

Implement PromQL range functions present_over_time, absent_over_time, quantile_over_time and predict_linear - #112842

Merged
nikitamikhaylov merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/phase3-range-functions
Sep 15, 2026
Merged

nikitamikhaylov merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/phase3-range-functions

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Related: #57545

Important

Depends on #115073. 04551_promql_phase3_range_functions runs
absent_over_time({__name__=~"up|up2",instance="host1"}[3m]) through --dialect promql, and the SQL
lexer rejects =~ before the PromQL parser sees the text:
Code: 62 ... Unrecognized token: Syntax error: failed at position 28 (~).
#115073 is what lets a raw-text dialect keep tokens the SQL lexer rejects. It is the only failing
test here, and it accounts for every red check on this PR; the rest of the suite is green. Existing
PromQL tests do not hit this because they pass the expression as a string literal to
prometheusQuery(...), where the lexer never sees it.

Merge #115073 first, then a master merge here turns this green. The test is deliberately left as-is
rather than rewritten to dodge the lexer bug.

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

PromQL: implemented range functions present_over_time(), absent_over_time(), quantile_over_time() and predict_linear().

Description

Implements four PromQL functions over range vectors that were previously rejected with a not-implemented error:

  • present_over_time(v range-vector) — for each grid point, 1 if its staleness window contains at least one sample, otherwise the series is dropped.
  • absent_over_time(v range-vector) — an empty vector if the range vector has any samples, otherwise a 1-element synthetic series with value 1 and the labels inferred from the selector's equality matchers (matching Prometheus absent_over_time / absent semantics).
  • quantile_over_time(phi scalar, v range-vector) — the φ-quantile of the sample values in each grid point's window, computed with the R-7 (inclusive) method (quantileExactInclusive). φ outside [0, 1] yields ±Inf and NaN φ yields NaN, as in Prometheus.
  • predict_linear(v range-vector, t scalar) — simple linear regression over the in-window samples, extrapolated t seconds past the evaluation time.

Implementation

  • Two new grid aggregate functions:

    • timeSeriesPresentToGrid — 1 if a window has any sample, else NULL.
    • timeSeriesQuantileToGrid — R-7 inclusive quantile over a window (non-invertible summary that collects window values and sorts them in getResult).

    Both are registered inline in AggregateFunctionTimeseriesHelpers.cpp. predict_linear reuses the existing timeSeriesPredictLinearToGrid aggregate (the is_predict variant of the linear-regression aggregate).

  • present_over_time is wired through applyFunctionOverRange's impl_map. quantile_over_time and predict_linear have dedicated translators because they take an extra scalar argument.

  • absent_over_time builds a per-series presence grid via present_over_time, then at runtime counts present series per grid point (countForEach) and inverts the result, so it works whether or not the metric exists (a selector on a missing metric is a runtime subquery, not a compile-time-empty one). Output labels are derived from the selector's matchers, like absent().

No parser changes were needed — the grammar already accepts these function names and getFunctionResultType already returns the correct result types.

Testing: new parser cases in gtest_PromQLParser.cpp for present_over_time and absent_over_time (quantile_over_time / predict_linear were already covered); new stateless test 04551_promql_phase3_range_functions.sh exercising all four functions (present/absent, quantile at φ = 0 / 0.5 / 1, predict_linear at offsets 0 and 60) against a multi-series TimeSeries table, with values verified against Prometheus semantics.

Update: time-varying predict_offset / phi

predict_linear's t and quantile_over_time's phi now also accept a per-grid-point-varying PromQL scalar (e.g. time() in a range query), not just a constant or single-row scalar. This is handled by two new, self-contained aggregate functions, timeSeriesPredictLinearVaryingToGrid / timeSeriesQuantileVaryingToGrid, which take the varying value as a 3rd Array(Float64) argument instead of a fixed aggregate parameter (ClickHouse aggregate parameters are bound once per instance and can't vary per row). They're isolated from AggregateFunctionTimeseriesBase (shared by ~10 other timeSeries*ToGrid functions) to avoid regression risk to those.

Since these are public SQL aggregate functions, not just an internal translator detail, they validate that the 3rd-argument array is identical across every row/merged state and throw BAD_ARGUMENTS otherwise, rather than silently using whichever array was seen first.

Scope note: the varying value is normalized to Array(Float64) in the translator so it works for Float32-valued TimeSeries tables too, not just Float64. However, the PromQL scalar's own grid representation (fromFunctionTime.cpp's SCALAR_GRID output for time()) is cast to Array(scalar_data_type), which is the table's value type — for a Float32-valued table, that means time()'s own raw values (Unix timestamps, ~1.7e9) already lose precision (~128-unit rounding at that magnitude) before my code ever sees them. This is a pre-existing property of scalar_data_type being shared between value-precision and timestamp-scalar-precision, not something this change introduces, but this change is what makes it reachable for predict_offset/phi. It only matters when the varying value is derived from time() on a non-Float64 table. A bare time() (also inside scalar()/vector()) is rebuilt at native timestamp precision and works; any arithmetic around it (e.g. predict_linear(m[5m], time() - 60) or a phi normalized from time()) would see the already-rounded evaluation time, so makeVaryingScalarPrecisionSafe rejects it with CANNOT_EXECUTE_PROMQL_QUERY instead of returning silently wrong results — this is documented in the supported-functions tables. Fixing the root cause would mean changing fromFunctionTime.cpp's shared SCALAR_GRID representation, which has ~15 other callers — out of scope here.


Workflow [PR]
Sync PR [sync-upstream/pr/112842]

Version info

  • Merged into: 26.9.1.1564 (included in 26.9 and later)

@nikitamikhaylov nikitamikhaylov added can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Aug 3, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 3, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa79b65]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR adds present_over_time, absent_over_time, quantile_over_time, and predict_linear support to the PromQL TimeSeries path. The remaining blocker is that predict_linear and quantile_over_time still accept time-derived scalar carriers on TimeSeries(Float32) after those values have already been rounded through scalar_data_type, so some valid queries now return silently wrong results; the table-function docs are also back out of sync with the real contract.

Findings

❌ Blockers

  • [src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionPredictLinear.cpp:89-103, src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionQuantileOverTime.cpp:96-101] predict_linear and quantile_over_time now accept SINGLE_SCALAR / SCALAR_GRID horizons or phi values without any precision check, but those carriers are still built through context.scalar_data_type in src/Storages/TimeSeries/PrometheusQueryToSQL/toVectorGrid.cpp:67-75 and src/Storages/TimeSeries/PrometheusQueryToSQL/fromFunctionTime.cpp:46-53. On TimeSeries(Float32), time()-derived values are already rounded before they reach these functions: for example 1700000001 becomes 1700000000, so quantile_over_time(time() - 1700000000, up[3m]) can evaluate both range steps at phi = 0, and scalar(sum(vector(time()))) can shift predict_linear's horizon by 16 seconds at the 2026-02-08 epochs already used elsewhere in the suite. Suggested fix: either preserve native timestamp precision for these scalar carriers (the same way applyDateTimeFunction rebuilds time() through makeTimeQueryPieceNative) or reject lossy time-derived SINGLE_SCALAR / SCALAR_GRID inputs on non-Float64 tables instead of evaluating them.

⚠️ Majors

  • [src/TableFunctions/TableFunctionTimeSeries.cpp:269-279, 348-358] The supported-functions tables still advertise quantile_over_time and predict_linear without the caveats discussed earlier, but the current implementation still rejects quantile_over_time(time(), m[5m] @ T) in src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionQuantileOverTime.cpp:159-168, and the current head no longer has the documented makeVaryingScalarPrecisionSafe rejection path for non-Float64 time-derived scalar formulas. Users will only discover these contract gaps at runtime. Suggested fix: re-add the missing caveat for fixed-@ plus varying phi, and if the non-Float64 time()-derived limitation is meant to stay, document the actual current behavior after the code is corrected.
Tests
  • ⚠️ The new PromQL coverage still does not exercise these scalar carriers on a TimeSeries(Float32) table at an epoch that is not exactly representable in Float32 (for example 1700000001 or the 2026-02-08 timestamps already used in test_evaluation.py). That is why the remaining quantile_over_time / predict_linear precision bug is still silent here.
Final Verdict

❌ Not ready to merge: the current head can still return silently wrong results for time()-derived predict_linear / quantile_over_time scalars on TimeSeries(Float32), and the table-function docs are again out of sync with the actual supported subset.

LLVM Coverage Report

Measured on commit fa79b65.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 80.50% 80.60% +0.10%

Changed lines: Changed C/C++ lines covered: 828/942 (87.90%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 4, 2026
@vitlibar vitlibar self-assigned this Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit fa79b657c0d99d1d2f4f72fedbb2b0b4066b0020 with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 5, 2026
predict_linear(v range-vector, t scalar) rejected every `t` that was not
a literal constant (StoreMethod::CONST_SCALAR), even though `t` is
advertised as a general PromQL scalar. A query like
predict_linear(up[3m], scalar(sum(vector(60)))) type-checks as a scalar
and is represented as StoreMethod::SINGLE_SCALAR elsewhere in the
translator (see applyFunctionScalar.cpp), but still failed with
NOT_IMPLEMENTED on the guard in applyFunctionPredictLinear.cpp.

The prediction horizon is only ever used to build the fifth (constant)
parameter of the `timeSeriesPredictLinearToGrid` aggregate function, so
there is no need for its value to be known at translation time — it only
needs to be a single constant-foldable SQL expression. Extend the guard
to accept StoreMethod::SINGLE_SCALAR too, and for that case materialize
the scalar subquery as a named scalar CTE (`WITH (SELECT ...) AS name`)
referenced via `assumeNotNull(name)`, mirroring the existing
StoreMethod::SINGLE_SCALAR handling for the `phi` parameter of
quantile_over_time in applyFunctionQuantileOverTime.cpp.

Add a regression test exercising predict_linear() with a genuinely
non-literal scalar `t` argument.

Addresses review comment on PR ClickHouse#112842.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 15, 2026
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Update: the SINGLE_SCALAR precision hole is closed by rejecting time()-derived single-row scalar horizons on non-Float64 tables, mirroring makeVaryingScalarPrecisionSafe (da86e35), with a compile fix for the traits FORMAT_VERSION forward (54da8df) and the 04700 regression.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Dear @vitlibar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@vitlibar
vitlibar force-pushed the promql/phase3-range-functions branch from 98d9307 to ce94de1 Compare September 15, 2026 13:59
… quantile_over_time and predict_linear

Co-Authored-By: Claude Opus 5 <[email protected]>
@vitlibar
vitlibar force-pushed the promql/phase3-range-functions branch from ce94de1 to c99ab7f Compare September 15, 2026 14:14
- `timeSeriesQuantileToGrid` takes the quantile level as an argument after the samples
  (a number or an array with one level per grid point) instead of a parameter, keeps the
  window's values sorted in a running summary, and computes the Prometheus edge cases of the
  level (-Inf, +Inf, NaN) itself.
- New `timeSeriesLinearRegressionToGrid` returns `(intercept, slope)` for every grid point.
  `predict_linear` is built on it and applies the horizon in SQL, so the horizon may vary per
  step, and under a fixed `@` modifier it is evaluated at every step like in Prometheus.
- The base class lets a derived class add arguments after the samples and extend the state.
  `timeSeriesPredictLinearVaryingToGrid` and `timeSeriesQuantileVaryingToGrid` are removed.
- `absent` and `absent_over_time` share one translator; a neutral row added with UNION ALL makes
  the result independent of `empty_result_for_aggregation_by_empty_set`.
- The precision machinery for time()-derived scalar arguments on Float32 tables is removed.
- The stateless tests are organized per function and use `prometheusQuery` instead of shell
  scripts; the integration test cases are merged into `test_function_over_time`.
@vitlibar
vitlibar force-pushed the promql/phase3-range-functions branch from c99ab7f to fa79b65 Compare September 15, 2026 15:40
@vitlibar

vitlibar commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

I reworked the solution of this PR, my changes:

  • timeSeriesQuantileToGrid takes the quantile level as an argument after the samples
    (a number or an array with one level per grid point) instead of a parameter, keeps the
    window's values sorted in a running summary, and computes the Prometheus edge cases of the
    level (-Inf, +Inf, NaN) itself.
  • New timeSeriesLinearRegressionToGrid returns (intercept, slope) for every grid point.
    predict_linear is built on it and applies the horizon in SQL, so the horizon may vary per
    step, and under a fixed @ modifier it is evaluated at every step like in Prometheus.
  • absent and absent_over_time share one translator; a neutral row added with UNION ALL makes
    the result independent of empty_result_for_aggregation_by_empty_set.
  • The base class lets a derived class add arguments after the samples and extend the state.
  • The stateless tests are organized per function and use prometheusQuery instead of shell
    scripts; the integration test cases are merged into test_function_over_time.
  • timeSeriesPredictLinearVaryingToGrid and timeSeriesQuantileVaryingToGrid are removed.
  • The precision machinery for Float32 tables is removed.

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 27e094c82

Metric Baseline Current Δ
Score 84.23% 96.47% +12.24%
Passed 454 520 +66
Failed 3 3 +0
Unsupported 82 16 -66

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 96.47% vs master baseline 84.23% (27e094c82). Merging to master will publish a new S3 object from the integration job that runs test_promql_compliance, which becomes the baseline for later PRs.

@vitlibar

Copy link
Copy Markdown
Member

@groeneai Analyze CI failures

@groeneai

Copy link
Copy Markdown
Collaborator

Analyzed the CI of the current head fa79b657: all 172 check runs are completed, and nothing failing on it comes from this PR.

The only red is Build profile diff, and it is a CI infrastructure outage. The job log shows ERROR: No connection to LogCluster for the whole retry window (21:08:19 to 21:10:39 UTC), then RuntimeError: CI logs cluster query failed raised out of has_pr_data() (ci/jobs/build_profile_diff_job.py:723), which fails the job. In CIDB that job has errored on 129 distinct PRs since 13:14 UTC today (most recent 21:49 UTC) while every run before 13:00 UTC was green, so it is not specific to this branch and needs no change here: the job can only pass once that cluster is reachable again. I have #120121 open to make that read non-fatal instead of failing the check.

The one real test failure in this PR's history is already fixed by your rework. Fast test / 05214_timeseries_linear_regression_to_grid failed on c99ab7f7 (14:23 UTC) on a reference mismatch: the result type printed as

Array(Tuple(
    intercept Nullable(Float64),
    slope Nullable(Float64)))

against the single-line spelling in the reference, because print_pretty_type_names defaults to true. c99ab7f7 and fa79b657 share the parent 1cd2022236f3 and differ only in the two toTypeName queries gaining SETTINGS print_pretty_type_names = 0, and 05214 now passes Fast test, the targeted stateless run and the 50x flaky check. That failure was deterministic rather than flaky (print_pretty_type_names is not in the randomized set in tests/clickhouse-test), and 05210 is the only other new test that prints a type, with Array(Nullable(Float64)) / Array(Nullable(Float32)), so nothing else needs the pin.

Everything else on the head is green, including the jobs that were red before the rework: no failing test rows in CIDB, and 7 AST fuzzer variants, 4 BuzzHouse variants, 10 Stress test variants, Upgrade check, Build (arm_tidy), Docs examples and the integration shards that own test_prometheus_protocols (plus the flaky integration check) all finished green; the compliance report on this head moves 84.23% to 96.47% with the failed count unchanged at 3. Of the pre-rework reds, the two Stress logical errors are repo-wide families (154 and 199 distinct PRs in the last 30 days, master runs included), and the AST fuzzer Equal values are not contiguous within the range assumed to be sorted and the stress offsets_column has data inconsistent with nested_column were reported on 11 and 3 other PRs in the same window. A single fuzzer or stress pass does not prove a nondeterministic finding gone, but there is nothing branch-specific left to chase.

Full report for fa79b657

@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Sep 15, 2026
Merged via the queue into ClickHouse:master with commit 3a43db4 Sep 15, 2026
516 of 520 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 Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Master release builds are red on this PR's merge commit

Build (amd_release) and Build (arm_release) both fail on master at 3a43db4d688f, the merge
commit of this PR, in the programs/clickhouse link step. The gate that rejects it is
utils/check-large-objects.sh:

  56842736 .../clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTimeseriesHelpers.cpp.o
^ It's not allowed to have so large translation units.
  To bypass this check, configure the build with -DCHECK_LARGE_OBJECT_SIZES=0

arm_release reports 55326124 for the same object. The limit is 50000000 bytes, so that
translation unit is 13.7% over on amd and 10.7% over on arm, and
AggregateFunctionTimeseriesHelpers is not in the script's TU_EXCLUDES. Every other flavour at
the same SHA built fine (amd_binary, arm_binary, debug, asan_ubsan, tsan, msan, tidy); only the
release flavours reach that gate.

This PR's own release builds passed at head fa79b657 at 18:03Z, against a master base about 24
commits older than the one it merged into, so the TU was already close to the limit before the
merge and crossed it in the merged tree.

Consequences on master at that SHA: Post Hooks
(ci/jobs/scripts/job_hooks/build_master_head_hook.py) fails on both arches too, because there is
no clickhouse binary to publish, so the master-head reference binary is missing; and the
release-dependent jobs were dropped rather than run, including all Stateless tests (*_release),
both ClickBench, all 12 Performance Comparison (*, master_head), Stress test (arm_release),
AST fuzzer (amd_release, oracle), SQLTest, SQLLogic test, SQLStorm test, Docs examples,
Install packages, Compatibility check, and the Docker server and keeper images.

AggregateFunctionTimeseriesHelpers.cpp is unchanged on master since this merge, so the next master
commit that triggers a release build will fail the same way.

Logs:

Two shapes of fix: split the file so no single object exceeds 50 MB, or add
AggregateFunctionTimeseries to TU_EXCLUDES. I can open the split PR if that is the shape you
want; otherwise I will stay out of the way of a revert or your own fix.

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... manual approve Manual approve required to run CI 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.

5 participants