Repository navigation
Implement PromQL functions sum_over_time(), avg_over_time() and count_over_time() - #112353
Conversation
|
Workflow [PR], commit [96509c1] Summary: ✅
AI ReviewSummaryThis PR wires PromQL Findings❌ Blockers
Final Verdict❌ Request changes. The current arithmetic and count-type behavior is still incorrect for user-visible PromQL results. LLVM Coverage ReportMeasured on commit 96509c1.
Changed lines: Changed C/C++ lines covered: 336/338 (99.41%) · Uncovered code |
| else if constexpr (kind == TimeSeriesSumCountAvgKind::Avg) | ||
| return static_cast<ValueType>(combined.sum / static_cast<Float64>(combined.count)); | ||
| else | ||
| return static_cast<ValueType>(combined.count); |
There was a problem hiding this comment.
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.
00cc2e9 to
0beac3a
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 429/448 (95.76%) · Uncovered code |
|
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! |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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%) |
- 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]>
…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]>
… 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]>
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]>
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]>
…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; |
There was a problem hiding this comment.
Aggregate functions should consider duplicates, so most of them have to keep raw samples
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Also after splitting this implementation into 3 separate implementation, it will be better to split AggregateFunctionTimeseriesSumCountAvgTraits into 3 separate Traits in 3 separate files
There was a problem hiding this comment.
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; | ||
| } |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
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]>
|
@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) |
There was a problem hiding this comment.
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.
|
Update on the open items:
On the older |
|
|
||
| /// 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; |
There was a problem hiding this comment.
❌ 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.
There was a problem hiding this comment.
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
-- 10000000000000002The 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.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
❌ 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
Summaryhas to carry the window's samples rather than a rounded total, somergeconcatenates instead of folding, andgetResultdoes 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
removeBeforestill releases it promptly rather than holding the whole grid's samples. FORMAT_VERSIONneeds 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 bucketsOn 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.
There was a problem hiding this comment.
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.
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.
86916ec to
96509c1
Compare
|
I simplified the code in this PR, also made some changes:
|
PromQL Compliance ReportBaseline: S3 master
Uploaded compliance JSON for this PR commit Baseline updateThis run reports 81.82% vs master baseline 78.29% ( |
Related: #57545
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
PromQL: implemented functions
sum_over_time(),avg_over_time()andcount_over_time().Description
Implements three PromQL range-vector functions previously reported as not implemented.
sum_over_time,avg_over_timeandcount_over_timeare three different projections of the same(sum, count)accumulator, so they share one new header (AggregateFunctionTimeseriesSumCountAvg.h) with a single invertibleSummary{sum, count}monoid (merge adds both fields, unmerge subtracts them), plugged into the existing genericAggregateFunctionTimeseriesSlidingSumsliding-window fast path — the same infrastructure already proven byrate/increase/delta. No changes were needed to the generic grid/bucket machinery (AggregateFunctionTimeseriesBase.h) or tocheckArgumentTypes(all three take a single range-vector argument, the existing default).Registered
timeSeriesSumToGrid/timeSeriesAvgToGrid/timeSeriesCountToGridinAggregateFunctionTimeseriesHelpers.cppand added the threeimpl_mapentries inapplyFunctionOverRange.cppwithdrop_metric_name = true, matchingrate/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 intests/integration/test_prometheus_protocols/test_evaluation.pycovering 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 nestedavg_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]