Skip to content

Implement PromQL functions stddev_over_time() and stdvar_over_time() - #112355

Merged
vitlibar merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/stddev-stdvar-over-time
Sep 24, 2026
Merged

vitlibar merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/stddev-stdvar-over-time

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Jul 28, 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: implemented functions stddev_over_time() and stdvar_over_time() (population standard deviation/variance).

Description

Implements PromQL functions stddev_over_time(v range-vector) and stdvar_over_time(v range-vector) using a numerically stable Welford/Chan accumulator, wires them into prometheusQuery/prometheusQueryRange, and adds SQL/integration coverage for duplicate timestamps, non-finite propagation, state merge/serialization, and large-magnitude regression cases.

The accumulator keeps a running centered moment {count, mean, m2} updated per sample with Welford's formula and merged pairwise with Chan et al.'s parallel merge, avoiding the catastrophic cancellation of the naive sum(x^2) - sum(x)^2/N formula on large-magnitude counter series. Samples sharing a timestamp follow the timeSeries*ToGrid family contract and collapse to a single value per timestamp (timeseriesMaxValueForDuplicateTimestamp), both on ingestion and when partial states merge on AggregatingMergeTree.

Registered the timeSeriesStddevToGrid / timeSeriesStdvarToGrid aggregate functions in AggregateFunctionTimeseriesHelpers.cpp and added the two impl_map entries in applyFunctionOverRange.cpp with drop_metric_name = true.

Verified numerically against Prometheus 3.5.0 live responses, including cross-architecture (ARM64 vs x86_64) ULP tolerance handling in CI. This flips 12 queries of the PromQL compliance suite from unsupported to passed.

Testing: SQL-level test (04628_variance_timeseries_functions.sql) covering empty/single/multi-sample windows and AggregatingMergeTree state round-trips, plus integration cases in tests/integration/test_prometheus_protocols/test_evaluation.py for instant/range evaluations and the correctness edges above.


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

Version info

  • Merged into: 26.10.1.615-master (included in 26.10 and later)

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Jul 28, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0a43944]

Summary: ✅


AI Review

Summary

This PR adds timeSeriesStddevToGrid / timeSeriesStdvarToGrid, wires them into stddev_over_time / stdvar_over_time for prometheusQuery and prometheusQueryRange, updates the source-registered docs, and adds focused SQL and integration coverage for numerical stability, duplicate timestamps, non-finite propagation, result typing, and the two-stack sliding path. After reviewing the current diff, the touched implementation, the existing review threads, and the current CI report, I did not find a new material correctness, compatibility, or test-coverage issue in the patch as it stands.

Final Verdict

✅ No new review findings.

LLVM Coverage Report

Measured on commit 0a43944.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 228/230 (99.13%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 28, 2026
@valerypetrov
valerypetrov force-pushed the promql/stddev-stdvar-over-time branch from 5b6356a to 6c51026 Compare July 29, 2026 00:36
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 200/203 (98.52%) · Uncovered code

Full report · Diff report

@vitlibar vitlibar self-assigned this Aug 4, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 5, 2026
be66b6a added a 0-argument call to IStorage::getInMemoryMetadataPtr() in
StorageTimeSeriesSelector::readImpl(). The subsequent merge of upstream/master
(01bea68) changed that virtual's signature to take (ContextPtr, bool) and
return the lifetime-safe StorageMetadataHandle wrapper (whose operator-> is
deleted on rvalues), breaking the build:

  error: too few arguments to function call, expected 2, have 0
  error: overload resolution selected deleted operator '->'

Pass context and bypass_metadata_cache=false, matching every other call site
of this function in the codebase (e.g. AlterCommands.cpp, StorageBuffer.cpp),
and bind the returned handle to a named variable before dereferencing it,
since StorageMetadataHandle::operator->() const && is explicitly deleted.

CI report: ClickHouse#112355

Co-Authored-By: Claude Sonnet 5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 5, 2026
…column

f5ba06a added a physical `is_stale_marker UInt8` column to the TimeSeries
"samples" inner table (normalizeTimeSeriesDefinition.cpp's
normalizeInnerTableColumns()), so it now shows up as a 4th row in
`SELECT name, type, compression_codec FROM system.columns` in all three
scenarios this test covers (default codecs, after detach/attach, explicit
columns). be66b6a already updated the sibling
04600_timeseries_column_validation.reference for the same reason but missed
this one.

CI report: ClickHouse#112355
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 0a43944c465394ce17f868c7a1f66f4380a0a734 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Comment thread src/Storages/StorageTimeSeries.cpp Resolved
Comment thread src/Storages/StorageTimeSeries.cpp Resolved

namespace DB
{

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.

The implementation seems to be OK, but we can't merge the PR because it contains lots of unrelated changes. Please keep only changes related to adding these two functions stddev_over_time / stdvar_over_time in this PR and remove anything else from this PR

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cleaned up these unrelated changes. Sorry for that. Should be ready for review.

@valerypetrov
valerypetrov requested a review from vitlibar August 25, 2026 20:07
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@vitlibar The unrelated changes were removed in a5e2c94 — the net diff is now only the two aggregate functions plus their tests — and the remaining docs gap flagged by the AI reviewer is fixed in e5703aa. Could you take another look?

@vitlibar
vitlibar force-pushed the promql/stddev-stdvar-over-time branch from d02686c to f04b156 Compare September 24, 2026 00:48
Add the aggregate functions `timeSeriesStddevToGrid` and
`timeSeriesStdvarToGrid` and wire them into `prometheusQuery` and
`prometheusQueryRange`. The state is a Welford/Chan `{count, mean, m2}`
accumulator, which avoids catastrophic cancellation on large-magnitude
series. Samples sharing a timestamp collapse to one value, as in the
other `timeSeries*ToGrid` functions. The result is always `Float64`.

Related: ClickHouse#57545

Co-Authored-By: Claude <[email protected]>
@vitlibar
vitlibar force-pushed the promql/stddev-stdvar-over-time branch from f04b156 to 1c0ace4 Compare September 24, 2026 08:23
- Rename `AggregateFunctionTimeseriesVarianceOverTime` to `AggregateFunctionTimeseriesVariance`.
- Tune the two-stacks thresholds to 4 and 10 with the `timeseries_to_grid_two_stack_vs_recompute`
  example, which now covers `timeSeriesStdvarToGrid`.
- Remove the unreachable clamp of a negative variance, the redundant `DateTime64Supported`
  member, and reset `FORMAT_VERSION` to 1.
@vitlibar
vitlibar force-pushed the promql/stddev-stdvar-over-time branch from 1c0ace4 to 0a43944 Compare September 24, 2026 09:05
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 3e732fb7b

Suite Baseline Current Delta
Prometheus compliance 96.47% 98.70% +2.23%
Extended support (upstream engine tests) 77.46% 78.42% +0.96%
Suite Passed Failed Unsupported
Prometheus compliance 520 -> 532 (+12) 3 -> 3 (+0) 16 -> 4 (-12)
Extended support (upstream engine tests) 567 -> 574 (+7) 140 -> 140 (+0) 25 -> 18 (-7)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 98.70% vs master baseline 96.47% (3e732fb7b). 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
vitlibar added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit 1b57158 Sep 24, 2026
340 of 341 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 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... 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