Skip to content

Implement PromQL functions sum_over_time(), avg_over_time() and count_over_time() - #112353

Merged
vitlibar merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/sum-avg-count-over-time
Sep 4, 2026
Merged

vitlibar merged 2 commits into
ClickHouse:masterfrom
valerypetrov:promql/sum-avg-count-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 sum_over_time(), avg_over_time() and count_over_time().

Description

Implements three PromQL range-vector functions previously reported as not implemented. sum_over_time, avg_over_time and count_over_time are three different projections of the same (sum, count) accumulator, so they share one new header (AggregateFunctionTimeseriesSumCountAvg.h) with a single invertible Summary{sum, count} monoid (merge adds both fields, unmerge subtracts them), plugged into the existing generic AggregateFunctionTimeseriesSlidingSum sliding-window fast path — the same infrastructure already proven by rate/increase/delta. No changes were needed to the generic grid/bucket machinery (AggregateFunctionTimeseriesBase.h) or to checkArgumentTypes (all three take a single range-vector argument, the existing default).

Registered timeSeriesSumToGrid/timeSeriesAvgToGrid/timeSeriesCountToGrid in AggregateFunctionTimeseriesHelpers.cpp and added the three impl_map entries in applyFunctionOverRange.cpp with drop_metric_name = true, matching rate/increase/delta's convention.

Verified against Prometheus 3.5.0.

Testing: new SQL-level test (04628_timeseries_sum_avg_count_over_time.sql) plus cases in tests/integration/test_prometheus_protocols/test_evaluation.py covering all three functions, an empty-window case, a window narrower than the step (grid points with no sample must be absent/NULL, not zero), and a nested avg_over_time(rate(...)[2m:10s]) case. This flips 19 queries of the PromQL compliance suite from unsupported to passed.


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

@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 [96509c1]

Summary: ✅


AI Review

Summary

This PR wires PromQL sum_over_time, avg_over_time, and count_over_time through new timeSeries*ToGrid helpers, but the current head still has correctness blockers. The shared compensated-summary path makes sum_over_time / avg_over_time depend on internal bucket grouping again, avg_over_time knowingly returns Inf for finite averages, and both count surfaces narrow counts back to the table sample type on Float32 tables.

Findings

❌ Blockers

  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesCount.h:25-26,74-82] count_over_time is still projected to ValueType, so a Float32 TimeSeries table rounds counts once the window exceeds 16777216 samples. The new 04628 reference also pins that wrong contract. Suggested fix: keep timeSeriesCountToGrid at Float64 end-to-end and update the direct helper docs/tests accordingly.
  • [src/Storages/TimeSeries/PrometheusQueryToSQL/applyOneArgumentAggregationOperator.cpp:87-102] The new CAST(... Array(Nullable(<scalar_data_type>))) makes PromQL count(...) lose the same exact-count guarantee on Float32 tables. That fixes the nested-subquery type error by converting counts to floats, but it also makes large series counts round in user-visible results. Suggested fix: cast countForEach results to Array(Nullable(Float64)) here, and keep that type through finalization.
  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesCompensatedSum.h:52-56,78-98,124-127] sum_over_time is back on AggregateFunctionTimeseriesSlidingSum with a bucket summary that is not a valid two-stack monoid. Once BPW_TO_FORCE_TWO_STACKS turns on, the same window can produce different sums depending on how the queue is split between front_stack and back_stack. Suggested fix: keep sum_over_time off the two-stack path unless the summary combine is actually associative for that regrouping.
  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesCompensatedSum.h:52-56,78-116] avg_over_time no longer folds raw samples across the live window. The current head is back to merging rounded per-bucket summaries, so the reported average changes when the same timestamp-ordered samples are partitioned into buckets differently. Suggested fix: restore the raw-sample window fold for avg, or another representation whose merge is replay-equivalent.
  • [src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesCompensatedSum.h:113-116; tests/queries/0_stateless/05059_timeseries_sum_avg_non_finite.sql:5-15] avg_over_time now divides an overflowed Float64 sum, so even a finite average such as [1e308, 1e308] becomes Inf. The new test explicitly documents and locks in that Prometheus mismatch. Suggested fix: use an overflow-safe running mean for avg and update 05059 to assert the finite result instead of codifying the bug.
Final Verdict

❌ Request changes. The current arithmetic and count-type behavior is still incorrect for user-visible PromQL results.

LLVM Coverage Report

Measured on commit 96509c1.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.10% +0.10%

Changed lines: Changed C/C++ lines covered: 336/338 (99.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 28, 2026
else if constexpr (kind == TimeSeriesSumCountAvgKind::Avg)
return static_cast<ValueType>(combined.sum / static_cast<Float64>(combined.count));
else
return static_cast<ValueType>(combined.count);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ count_over_time promises an exact sample count, but the shared template still casts combined.count back to ValueType. TimeSeries tables with Float32 values are explicitly supported, so once a window holds more than 16777216 samples this starts rounding the result, and even smaller counts are still limited to Float32 precision. The new SQL helper documentation also says Array(Nullable(Float64)), which this implementation does not honor on Float32 inputs.

Count needs a fixed Float64 result type instead of inheriting the input sample type.

@valerypetrov
valerypetrov force-pushed the promql/sum-avg-count-over-time branch from 00cc2e9 to 0beac3a Compare July 29, 2026 00:03
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 429/448 (95.76%) · Uncovered code

Full report · Diff report

@nikitamikhaylov

Copy link
Copy Markdown
Member

Please condense all the comments in the code to a single (max two) lines.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Please condense all the comments in the code to a single (max two) lines.

No worries, let me fix that. Thank you for the review!

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 96509c15e with master de1002bf2 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

11 object files changed (+1.53 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/TimeSeries/AggregateFunctionTi… 4.98 MiB 6.43 MiB +1.45 MiB (+29.13%)
src/CMakeFiles/clickhouse_common_io.dir/Common/QueryFuzzer.cpp.o 1.52 MiB 1.55 MiB +28.64 KiB (+1.84%)
src/CMakeFiles/dbms.dir/Storages/RocksDB/StorageEmbeddedRocksDB.cpp.o 807.34 KiB 832.25 KiB +24.91 KiB (+3.09%)
src/Examples/CMakeFiles/clickhouse-examples.dir/__/AggregateFunctions/examples/timeseries_to_grid_t… 63.79 KiB 81.19 KiB +17.40 KiB (+27.28%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper __cxx_global_var_init.809 new 160.62 KiB +160.62 KiB
programs/clickhouse __cxx_global_var_init.809 new 160.62 KiB +160.62 KiB
programs/clickhouse-keeper __cxx_global_var_init.794 160.62 KiB removed -160.62 KiB (-100.00%)
programs/clickhouse __cxx_global_var_init.794 160.62 KiB removed -160.62 KiB (-100.00%)

Job report

@vitlibar vitlibar self-assigned this Aug 4, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 5, 2026
- applyFunctionOverRange.cpp: only overwrite `res.value_data_type`
  with `impl_info->value_data_type_override` when the override is
  actually set (currently only `count_over_time`, which always
  returns `Float64`). Previously every other range function (e.g.
  `sum_over_time`, `avg_over_time`) unconditionally cleared the
  inherited `value_data_type`, so nested queries like
  `avg_over_time(count_over_time(x[N s])[1s:1s])` on a `Float32`
  `TimeSeries` table lost `count_over_time`'s `Float64` result type
  and got rounded back through the table's `Float32` scalar type in
  `finalizeSQL`/`getResultColumns`.

- applyDateTimeFunction.cpp: teach the precise-time wrapper detector
  (`findTimeCallThroughScalarVectorWrappers`) to also peel
  `label_replace`/`label_join` wrappers by recursing into their first
  argument, using the existing `isLabelManipulationFunction` predicate.
  These two functions only rewrite labels and preserve sample values,
  so they belong in the value-preserving-wrapper category alongside
  `scalar`, `vector`, unary `+`, and `offset`. Previously, expressions
  like `minute(label_replace(vector(time()), 'a', 'b', '', ''))` fell
  through to the rounded `Float32` carrier for `time` and could report
  the wrong minute/hour/etc. at evaluation time.

Both bugs were flagged by clickhouse-gh in review comments on
ClickHouse#112353 (review)

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

applyFunctionOverRange()'s two StoreMethod::EMPTY early returns (the
compile-time-empty node-range check, and the switch case for an
already-empty argument, e.g. an empty subquery grid) built a fresh
SQLQueryPiece without ever assigning impl_info->value_data_type_override,
so count_over_time() - the only function using this override, since it
always returns Float64 regardless of the table's sample type - silently
lost its Float64 contract whenever its range turned out empty at compile
time, e.g. count_over_time(vector(1)[19:20]) (a 19s window sampled every
20s, which covers no grid point at time 19).

Setting SQLQueryPiece::value_data_type on these EMPTY pieces alone isn't
enough: finalizeSQL()'s two ResultType::INSTANT_VECTOR/RANGE_VECTOR EMPTY
branches (used to build the `SELECT * FROM null(...)` placeholder for an
empty result) hard-coded context.scalar_data_type instead of consulting
result.value_data_type like every other store method in those functions
already does, and Converter::getResultColumns()'s override whitelist
(used by getActualTableStructure(), e.g. for DESCRIBE) didn't include
StoreMethod::EMPTY either. Fixed all three call sites, following the same
value_data_type-or-fallback pattern and getResultColumns()/finalizeSQL()
sync already established for VECTOR_GRID/SINGLE_SCALAR/SCALAR_GRID by an
earlier commit on this branch (e1de1b4).

Added a Float32-table regression checking the declared column type (via
DESCRIBE, since the query itself legitimately returns zero rows and
there's no `value` to run toTypeName() on) is Float64 for
count_over_time(vector(1)[19:20]), through both prometheusQuery() and
prometheusQueryRange().

Flagged by a fresh, more detailed review on
ClickHouse#112353.

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

findTimeCallThroughScalarVectorWrappers() peels label_replace()/
label_join() wrappers to find an inner bare time() call, so that
minute()/hour()/etc. can rebuild it via fromFunctionTimeNative() and
avoid Float32 evaluation-time precision loss. But the caller then used
only the discovered time() node to build the fast-path value, discarding
the label_replace()/label_join() wrapper itself: the fast path replaced
arguments[0] wholesale with the freshly-built native `time` piece,
never re-applying the label rewrite those wrappers perform. As a result,
e.g. minute(label_replace(vector(time()), "a", "b", "", "")) returned an
unlabeled sample instead of one tagged {a="b"} - a regression in this
exact fast path introduced by an earlier fix on this branch (1283523).

Fixed by having findTimeCallThroughScalarVectorWrappers() also collect
the label_replace()/label_join() function nodes it peels through
(innermost first), and, after building the precise native `time` value,
replaying each of them on top of that value via
applyLabelManipulationFunction() - the same function that implements
these two operators outside the fast path - before using the result as
the date/time function's argument. Since label_replace()/label_join()'s
2nd+ PromQL arguments can only be string literals (nothing else in PromQL
produces a ResultType::STRING value), they're re-evaluated directly with
fromLiteral() instead of needing a generic AST-to-SQLQueryPiece visitor.

Added a Float32-table regression for
minute(label_replace(vector(time()), "a", "b", "", "")), checking both
the corrected minute value (the fast native-timestamp path still works)
and that label {a="b"} is present in the output (the rewrite is no
longer dropped), through both prometheusQuery() and prometheusQueryRange().

Flagged by a fresh, more detailed review on
ClickHouse#112353.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 6, 2026
nikitamikhaylov asked on ClickHouse#112353
to condense all code comments to a single (max two) lines. The three most
recent commits on this branch (fixing reviewer-flagged bugs and the
label_replace()/label_join() fast-path regression) added several 3-6 line
explanatory comment blocks that predate that request; this condenses each
to one or two lines while keeping the essential rationale, in both the C++
sources and the integration test.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 6, 2026
A fresh review found the same bug pattern fixed for applyFunctionOverRange()
earlier on this branch (6b6c5a9) recurring in five more places: an EMPTY
fast path builds a brand-new SQLQueryPiece{..., StoreMethod::EMPTY} instead of
forwarding or merging the source argument(s)' value_data_type, so a
fixed-result-type function like count_over_time() (Float64 regardless of the
table's sample type) silently loses that contract whenever the surrounding
expression happens to be empty:

- applySimpleFunction.cpp's per-argument EMPTY case (e.g. abs(count_over_time(...))):
  now merges the value type accumulated so far with the empty argument's, via
  mergeValueDataType(), mirroring the non-empty path below it.
- applySimpleBinaryOperator.cpp's applyOperatorToVectors EMPTY fast path (e.g.
  count_over_time(...) + vector(0)): now merges both operands' value_data_type
  via mergeValueDataType(), same as its non-empty path.
- applyBinaryOperatorAnd.cpp's and applyBinaryOperatorUnless.cpp's left-empty
  EMPTY fast paths (e.g. count_over_time(...) and/unless vector(0)): and/unless
  keep only the left operand's values, so both now forward left_argument's
  value_data_type specifically, not a merge, matching their non-empty paths.
  (applyBinaryOperatorUnless.cpp's right-empty branch was already correct: it
  returns the moved left_argument piece directly.)
- applyOneArgumentAggregationOperator.cpp (sum/min/max/avg/count/stddev/stdvar/group)
  and applyAggregationOperatorQuantile.cpp and applyLimitAggregationOperator.cpp
  (topk/bottomk/limitk): all now forward the vector argument's value_data_type,
  matching their non-empty paths (`res = argument`/`res = vector_arg`).

Also fixed the same pattern found while auditing every StoreMethod::EMPTY
construction site in this directory: applyOffset.cpp's setEvaluationTime()
had its own compile-time-empty node_range early return (structurally the same
bug as applyFunctionOverRange()'s), which dropped `expression`'s
value_data_type, e.g. for count_over_time(...) @ <timestamp>.

Other StoreMethod::EMPTY sites in this directory were audited and left alone:
leaf/no-argument nodes (selectors, literals, pi(), time()) have no source
value_data_type to forward; applyHistogramQuantile.cpp never sets
value_data_type on its non-empty path either, so its EMPTY path isn't a
regression of the same kind; and dropMetricName.cpp, toVectorGrid.cpp,
applyUnaryOperator.cpp, applyFunctionScalar.cpp, applyLabelManipulationFunction.cpp,
and applyBinaryOperatorOr.cpp already forward value_data_type correctly, since
their EMPTY cases move or copy the whole source SQLQueryPiece through rather
than constructing a fresh one.

Flagged by a fresh review on ClickHouse#112353.

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

Extends test_count_over_time_float32_precision() with focused regressions
for the value_data_type-forwarding fixes on the same compile-time-empty
count_over_time(vector(1)[19:20]) case already used for the base
applyFunctionOverRange() regression:

- abs(count_over_time(vector(1)[19:20])) for applySimpleFunction.cpp
- count_over_time(vector(1)[19:20]) + vector(0) for applySimpleBinaryOperator.cpp
- count_over_time(vector(1)[19:20]) and/unless vector(0) for
  applyBinaryOperatorAnd.cpp/applyBinaryOperatorUnless.cpp
- sum(count_over_time(vector(1)[19:20])) for applyOneArgumentAggregationOperator.cpp

Each checks (via DESCRIBE, since the query legitimately returns zero rows)
that the declared column type stays Float64 instead of falling back to the
table's Float32 sample type.

Flagged by a fresh review on ClickHouse#112353.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
};

/// The bucket keeps no raw samples - it accumulates sum/count directly, like `Summary` for the window.
using Bucket = Summary;

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.

Aggregate functions should consider duplicates, so most of them have to keep raw samples

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.

Done in bcd26ce: AggregateFunctionTimeseriesSamples gained a keep_duplicates policy (default off, so Changes/ExtrapolatedValue/LinearRegression keep one-value-per-timestamp), and sum/avg/count opt in - every occurrence is folded now, not the per-timestamp max. The 04628 test pins the multiplicity (sum = 16.5, avg = 16.5/7, count = 7 over two repeated timestamps) instead of asserting the collapse. FORMAT_VERSION bumped 1 -> 2 since an old binary would silently re-collapse the new states on deserialize.


void unmerge(const Summary & leaving, const Summary * /*new_first*/)
{
sum -= leaving.sum;

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.

unmerge will work fine for count here, but for sum and avg it will lose precision (e.g. 1e18+2+3+5 - 1e18 will return 0), so unmerge shouldn't be used for sum and avg.

Also for avg there is a special algorithm named Kahan summation to reduce numerical error

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.

Also after splitting this implementation into 3 separate implementation, it will be better to split AggregateFunctionTimeseriesSumCountAvgTraits into 3 separate Traits in 3 separate files

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.

Both parts are in. The traits are split into SumToGrid/AvgToGrid/CountToGrid with AggregateFunctionTimeseriesSumCountAvg.h deleted (70fd4df), and sum/avg now wire the two-stack queue with the same thresholds as LinearRegression (ed3b82c); count stays on the invertible running sum, which SlidingSum requires to have stack_size 0. On unmerge for sum/avg: agreed and gone since 70fd4df - sum has no unmerge, and avg uses Kahan-Babuska-Neumaier compensated summation, pinned by the 1e16 + 4 case in 04628.

SQLQueryPiece res{offset_node, offset_node->result_type, StoreMethod::EMPTY};
res.value_data_type = expression.value_data_type;
return res;
}

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.

Please keep in this PR only changes related to sum_over_time / avg_over_time / count_over_time 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.

Done in 8495079 (with 397b038 restoring only what the three functions themselves need): the PR now carries just the sum/avg/count_over_time implementations (SumToGrid/AvgToGrid/CountToGrid + the shared SlidingSum), their registration, docs rows and tests. The remaining converter touches exist solely because count_over_time returns Float64 regardless of the table's value type, so the empty-fold paths must not narrow it — the unrelated applyOffset/limit changes are gone.

valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 26, 2026
Same cleanup as ClickHouse#112353. timestamp() is the only producer of a value type
override, and no test in this PR, in 0_stateless, in test_evaluation.py or in
the compliance suite composes timestamp() with and/or/unless, an aggregation,
quantile, limitk, histogram_quantile, label_replace, offset or a range function
-- so carrying the override through those operators was speculative.

Reverted to master: the and/or/unless operators, clamp, offset, the limit,
quantile and one-argument aggregation operators, label manipulation, histogram
quantile, and applyFunctionOverRange's empty and CONST_SCALAR branches.
applySimpleBinaryOperator keeps the vector/vector site the tests cover and loses
the empty one they do not.

What stays is the path the tests exercise: applyFunctionTimestamp itself,
applySimpleFunction, applyFunctionScalar, toVectorGrid, finalizeSQL and the
result schema.

Co-Authored-By: Claude Opus 5 <[email protected]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@vitlibar The two remaining aggregate items are in: buckets keep duplicate timestamps for sum/avg/count (bcd26ce, with FORMAT_VERSION bumped and the 04628 test pinning multiplicity), and sum/avg use the two-stack queue with the same thresholds as LinearRegression (ed3b82c). Could you take another look?

++count;
}

void merge(const Summary & added)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AggregateFunctionTimeseriesSlidingSum only enables the two-stack path for non-invertible summaries when merge is commutative, because front and back stacks combine bucket summaries in a different order than the recompute path. This Summary::merge is not commutative: for real bucket summaries A from [1e16, 1e-16] and B from [3, -1e-16, -1e-16], merge(A, B) and merge(B, A) produce different totals, so the reported average can depend on queue state instead of only the samples once a window spans both stacks.

I think avg_over_time needs to stay on the recompute path until the bucket summary has an order-independent combine, or it needs a truly commutative merge like the centered-moment summary used by AggregateFunctionTimeseriesLinearRegression.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Update on the open items:

  • avg_over_time stays on the recompute path — the two-stack thresholds are removed for avg only (sum keeps them), making the merge order-independent (e12ed60).
  • count()'s Float64 result type is restored on both the non-empty and EMPTY fast paths, and the clamp/or empty fast paths forward the override (397b038). Float32 regressions are restored in test_evaluation.py.
  • The general value_data_type propagation through aggregation wrappers remains reverted per vitlibar's scope cut.

On the older applyOffset.cpp thread (vitlibar's "keep only changes related to sum/avg/count_over_time"): the scope cut is complete at the current head.


/// Two-stacks thresholds for `getStackSizeForTwoStacks`; `Summary::merge` is a pair of Float64 additions, no
/// pricier than `AggregateFunctionTimeseriesLinearRegression`'s, so its tuned crossover applies unchanged.
static constexpr size_t AVG_POPULATED_BPW_TO_ENABLE_TWO_STACKS = 10;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ These thresholds opt sum_over_time into AggregateFunctionTimeseriesSlidingSum's two-stack path, but plain Float64 addition is not associative under the regrouping that queue does. A minimal bucket trace is three one-sample buckets [1], [1], [1e16]: recomputing in time order gives ((1 + 1) + 1e16) = 1e16 + 2, but once the oldest bucket sits in front_stack and the newer two in back_stack, getCurrentSum() combines them as 1 + (1 + 1e16) = 1e16.

That means dense windows can report different sum_over_time values for the same samples depending on the queue split. I think sum_over_time has to stay on the recompute path unless its bucket summary becomes genuinely associative for the two-stack regrouping.

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.

Confirmed, and fixed by dropping the thresholds in 09a15c7 — sum_over_time is back on the recompute path.

Your trace is exactly right, and it reproduces end to end. On the Build (arm_darwin) binary of the previous head, with samples 1, 1, 1e16 in one window and nothing else in the table:

-- window/step = 300/15 = 20 hits BPW_TO_FORCE_TWO_STACKS
WITH 0 AS start, 300 AS end, 15 AS step, 300 AS window
SELECT arrayLast(x -> isNotNull(x), timeSeriesSumToGrid(start, end, step, window)(t, v))
FROM values('t DateTime64(3,\'UTC\'), v Float64', (270,1.0), (285,1.0), (300,1e16));
-- 10000000000000000

-- window/step = 285/15 = 19, one step under the threshold, same three samples
-- 10000000000000002

The root of my mistake is in the comment I had written on the avg traits: I justified the shortcut with "sum's plain additions merge commutatively". Commutativity is not the property the queue needs — regrouping needs associativity, and Float64 addition has the first but not the second. I have corrected that sentence in both files.

Simulating the two-stack splits bit-exactly over random bucketizations, the split matters: on all-positive data the two-stack path disagrees with the time-ordered fold in 71678/300000 cases versus 39064/300000 for recompute, so enabling it roughly doubled the exposure for a pure performance win.

One thing worth recording, since it argues against a stronger claim rather than for one: the recompute path is not a raw in-order fold either, and its worst-case gap is identical to the queue's (8e-16 relative on all-positive data, and total loss under cancellation — the same [1e16, 1e-16, 1e-16], [1e-16, -1.0, -1.0], ... case gives 1e-16 vs -4.0 on both paths). So this change removes a source of variability and restores the documented precondition; it does not make sum_over_time order-independent, and nothing at Float64 can.

I added the failing case to 04628 in the dense-grid-versus-single-point-grid form the avg test already used. It reports 0 on the current build and 1 with the queue disabled.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is back on the current head. src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesCompensatedSum.h:78-98 is again reducing each bucket to a Summary and storing those summaries in AggregateFunctionTimeseriesSlidingSum, and :124-127 re-enable the two-stack thresholds.

That still makes sum_over_time split-dependent once stack_size != 0. A concrete current trace is bucket A = [1e16, 0.001, -1e8] and B = [-0.001, 3]: time-order merge gives 9999999900000002, but the back-stack order gives 9999999900000004.

++count;
}

void merge(const Summary & added)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ This merge is still not equivalent to replaying the later bucket's samples in timestamp order, so avg_over_time now depends on bucketization even though the two-stack queue is disabled. A concrete trace is bucket A = [1] and bucket B = [1e16, 1e-16, 1e-16]: Summary(B) becomes {sum = 1e16, compensation = 2e-16, count = 3}, and merge(A, B) produces total 1e16 + 2, while a straight Kahan fold over [1, 1e16, 1e-16, 1e-16] produces 1e16.

AggregateFunctionTimeseriesSlidingSum::getCurrentSum() on the recompute path still combines one bucket summary at a time, so the same window can change result when samples are partitioned into buckets or partial states. I think this needs a summary with a truly mergeable representation, or avg_over_time has to fold raw samples across the window instead of merging per-bucket summaries.

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.

Your trace is right — I simulated both algorithms bit-exactly and reproduced it: Summary(B) = {sum = 1e16, compensation = 2e-16, count = 3}, merge(A, B) totals 1.0000000000000002e16, and the straight Kahan fold over [1, 1e16, 1e-16, 1e-16] totals 1e16. So merging bucket summaries is genuinely not replay-equivalent, exactly as you say.

Where I land differently is on the remedy, and I would rather show the numbers than argue it.

A truly mergeable representation does not exist here. I implemented the obvious upgrade — a double-double (Knuth two-sum) accumulator, where merge is a real two-sum of both limbs — and it is not better. Over 300k random bucketizations:

accumulator all-positive data mixed-sign data
Kahan-Babuska-Neumaier (current) 2438/300000 disagree, worst 2e-16 rel 6541/300000, worst 1.90 rel
double-double (candidate) 2369/300000 disagree, worst 2e-16 rel 6647/300000, worst 4.44 rel

No fixed-precision accumulator is order-independent; only an exact/superaccumulator representation would be, and that is not proportionate here. So the choice is really between the current summary and folding raw samples.

The residual gap is one ulp on data that does not cancel. Worst relative gap on all-positive data is 2e-16. The large relative numbers in the mixed-sign column are catastrophic cancellation: the worst case is 1.1102230246251565e-16 versus 3.220446049250313e-16 on inputs of ±1e16, where the true value is 0 and both answers are rounding noise. No summation order is "right" there.

Folding raw samples changes the cost class. Per grid point it would go from one merge per bucket in the window to one add per sample in the window, which for a dense PromQL window is the difference the bucket summaries exist to avoid.

There is also a consistency point: ClickHouse's own avg() is order-dependent across parallel merge, so requiring avg_over_time to be bit-identical to a single in-order fold would hold it to a stricter standard than the aggregate it is named after.

So I have not changed the arithmetic. What I did do is stop the comment from overclaiming — it now says plainly that merging bucket summaries is not bit-identical to folding the window's raw samples in timestamp order, because a bucket contributes its own rounded total, and that closing the gap means re-folding every sample at each grid point. If you would rather pay that cost and have avg_over_time match Prometheus's fold exactly, say so and I will make the window keep raw samples — it is a contained change to the Aggregator, and I would want it to be your call rather than mine.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would pay the cost here. The issue is not just that floating-point summation is imperfect in the abstract; the current implementation changes the answer when the same timestamp-ordered window is partitioned into buckets differently, and that bucketization is an internal detail rather than part of the avg_over_time contract.

If the choice is between merging rounded per-bucket summaries and replaying the raw samples for each output window, I think avg_over_time needs the latter.

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.

Understood — that is your call to make and I will implement the raw-sample fold. Your framing is the part my measurements did not answer: I argued about the size of the deviation, but the objection is that bucketization is an internal detail and should not be observable in the result at all, which is a contract question rather than a numerical one.

I am not pushing it in this reply, because it is not a one-line change and I would rather it be right:

  • Summary has to carry the window's samples rather than a rounded total, so merge concatenates instead of folding, and getResult does a single Kahan pass over the whole window in timestamp order. That is what makes the result independent of where bucket boundaries fall.
  • The recompute path already rebuilds the combine per grid point, so this changes its cost from one merge per bucket to one add per sample, and the memory the window holds from one summary per bucket to the samples themselves. That is the cost you said you would pay; I want to make sure removeBefore still releases it promptly rather than holding the whole grid's samples.
  • FORMAT_VERSION needs bumping again, since the serialized aggregate state changes shape and an older binary would otherwise read the new state as a summary.

I will also extend 04628 so the property is pinned rather than argued: the same samples partitioned into different bucket counts must produce a bit-identical avg_over_time, which is a test the current implementation cannot pass and the new one must.

One thing I will keep from the measurements, unless you would rather I did not: nothing here makes the result exact under catastrophic cancellation — a single in-order Kahan fold is still not the true mean. What it does buy is that the answer stops depending on the grid, which is the property you are asking for.

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.

Correction to my previous reply, before I build on a wrong premise: the FORMAT_VERSION bump I listed is not needed.

Summary is never serialized. AggregateFunctionTimeseriesBase::serialize writes the bucket map — entry.getMapped().serialize(buf), where the mapped type is Bucket, which for both of these functions is Samples — and the comment on FORMAT_VERSION says as much: "The serialized state is the set of buckets, so the format version is defined by the traits (which define the bucket type)". The Aggregator, and with it the whole SlidingSum and every Summary, is constructed inside doInsertResultInto (auto aggregator = derived().createAggregator(...)) and dies with it.

So changing how the window is folded is an in-memory change only. The serialized state stays byte-identical, there is no compatibility surface, and an older binary reading a newer state is not a concern. That makes the change meaningfully cheaper than I said, and I would rather you knew that before weighing it.

It also improves the shape of the implementation. aggregator.add() already receives the whole Bucket — the raw samples — not a pre-reduced value, and the bucket map is stable for the lifetime of that aggregator. So the window can hold references to the buckets rather than copies of their samples, and getResult can fold straight through them in timestamp order. The memory cost I warned about mostly disappears; what remains is the extra per-grid-point work of folding samples instead of summaries, which is the real cost and the one you accepted.

The rest of my previous reply stands: this is what makes the result independent of bucket boundaries, and I will add the bucket-count-invariance test to 04628 alongside it.

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.

Implemented in de3770c. avg_over_time now folds the window's raw samples.

The window keeps (bucket_end_timestamp, const Samples *) instead of a per-bucket summary, and getResult runs a single Kahan-Babuska-Neumaier pass over their samples in timestamp order. Because buckets enter in non-decreasing order and each bucket's samples are ordered, that pass sees exactly the window's sample sequence — so the result is a function of the samples alone and cannot depend on where the grid put the boundaries. Summary is gone; there is nothing left to merge.

No copying: the bucket map outlives the aggregator, so the window references buckets. The existing code already relies on that — doInsertResultInto builds a VectorWithMemoryTracking<std::pair<size_t, const Bucket *>> over the same map — so this is not a new lifetime assumption. As established in my previous reply, the serialized state is unchanged and FORMAT_VERSION stays put.

The property is now pinned by a test rather than argued. I searched for a case where the two disagree and then confirmed it on a build of this branch:

-- same 25 samples, same 25-second window, both grids landing on 124
timeSeriesAvgToGrid(124, 124, 1, 25)(ts, vals)[1]   -- 25 one-second buckets
timeSeriesAvgToGrid(104, 124, 5, 25)(ts, vals)[5]   -- 5 five-second buckets

On the current build those give -799999999999999.4 and -799999999999999.5; the first is what a straight fold over the samples produces, so the five-bucket answer is the one bucketization invented. 04628 now asserts they are equal and pins the folded value.

Two things I want to be straight about. The cost is real and is the one you accepted: per grid point the window now costs one add per sample instead of one merge per bucket. And this does not make the answer exact — a single in-order Kahan fold is still not the true mean under cancellation — it makes it independent of the grid, which is the property you asked for.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This fix is no longer present on the current head. src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesCompensatedSum.h:78-98 is back to reducing each bucket to a Summary, and :113-116 computes avg by dividing the merged summary total by count.

So the original issue is live again: the window is no longer replayed in timestamp order, and avg_over_time can change when the same sample sequence is bucketized differently.

valerypetrov and others added 2 commits September 4, 2026 00:06
Implements `timeSeriesSumToGrid`, `timeSeriesAvgToGrid` and `timeSeriesCountToGrid`
and maps the PromQL range functions onto them. Buckets keep duplicate timestamps,
`count_over_time` always returns `Float64`, and the converter carries a value type
override through wrappers so that type survives.

Co-Authored-By: Claude <[email protected]>
- Collapse equal timestamps to the greatest value, as the other grid
  functions do, instead of keeping duplicates in the sample store.
- Compute `timeSeriesSumToGrid` and `timeSeriesAvgToGrid` from one
  compensated summary on the sliding-sum container, with two-stacks enabled.
- Fix compensation for infinite sums, so infinite sums stay infinite.
- Drop the value type override from the PromQL converter: `count_over_time`
  returns the table's value type like every other function.
@vitlibar
vitlibar force-pushed the promql/sum-avg-count-over-time branch from 86916ec to 96509c1 Compare September 4, 2026 08:41
@vitlibar

vitlibar commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

I simplified the code in this PR, also made some changes:

  • Collapse equal timestamps to the greatest value, as the other grid
    functions do, instead of keeping duplicates in the sample buffer.
  • Compute timeSeriesSumToGrid and timeSeriesAvgToGrid from one
    compensated summary on the sliding-sum container, with two-stacks enabled.
  • Fix compensation for infinite sums, so infinite sums stay infinite.
  • Drop the value type override from the PromQL converter: count_over_time
    returns the table's value type like every other function.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 662cac347

Metric Baseline Current Δ
Score 78.29% 81.82% +3.53%
Passed 422 441 +19
Failed 3 3 +0
Unsupported 114 95 -19

Uploaded compliance JSON for this PR commit

Baseline update

This run reports 81.82% vs master baseline 78.29% (662cac347). 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 4, 2026
Merged via the queue into ClickHouse:master with commit 58d6272 Sep 4, 2026
174 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 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