refactor(promql): fold legacy histogram aggregates through the native accumulator (#10483)

* refactor(promql): fold legacy histogram aggregates through the native accumulator

The legacy prom_native_histogram_agg_sum/_avg accumulators kept their own sum, weighted
mean, incompatibility flag and reset evidence beside the native HistogramAccumulator that
10199 added, so the two could answer the same aggregate differently. The legacy
accumulator now holds that fold and delegates push, merge, state and size to it; only the
state frame still differs, and its layout, field names and order are unchanged.

The legacy frame declares neither a compensation component nor a mean mode, so a state
carries the fold's answer: the running sum with its compensation folded in, or the running
mean of its samples. That is what a reader of the frame adds or weights, and it keeps the
residual of samples already folded into one position. It is not a lossless Kahan state --
folding the compensation back into one f64 rounds again, so a partition holding [1e16, 1]
still exports 1e16 and merging it with [-1e16] answers 0.

An exponential sample meeting custom buckets poisons the whole position, as the legacy
reconcile() returning None did: the position answers null and the evidence says why,
rather than skipping the sample or failing the query. Reset evidence is OR-ed from the
state's two booleans instead of re-observing the merged histogram's hint, which the fold
already accounted for.

Signed-off-by: discord9 <discord9@163.com>
(cherry picked from commit 8fc9c00671)

* fix(promql): read a legacy sum's start timestamp from the fold it exports

The two tests #10420 wrote read `accumulator.value`, which this refactor replaced with the
native fold, so the crate did not build. They read `state_histogram()` now.

That path answers a derived histogram: `finished_histogram` compacts it, which clears the start
timestamp along with the empty buckets. So a single-sample sum no longer republishes the sample's
own timestamp - the timestamp is still inside the fold, but the answer is a derived one and says
so. The test that required the timestamp to survive is renamed and asserts the export instead.

Signed-off-by: discord9 <discord9@163.com>

* fix(promql): drop a position whose histogram cannot be read

A histogram whose spans and buckets disagree is one this crate cannot read. The accumulator this
refactor replaced met that disagreement through `legacy_bridge::add`'s `None` and dropped the
position with a warning; delegating to the native fold turned it into an error for the whole query,
so a table holding one went from answering with the group removed to failing.

The fold now records the position as incompatible and drops it, which is the answer the legacy path
gave. `an_illegally_shaped_histogram_drops_its_position_rather_than_failing_the_query` pins it for
both kinds: the push answers `Ok`, the position's state is empty, and the warning names the
incompatible schemas.

Signed-off-by: discord9 <discord9@163.com>

* fix(promql): drop a state frame whose histogram cannot be read

`merge_batch` reads a partition's exported histogram the same way `push_histogram` reads a sample,
and made the same change: a state frame whose spans and buckets disagree became an error for the
whole statement, where the legacy path recorded the position as incompatible and dropped it. The
merge half now records it the same way, so a partition this crate cannot read is dropped rather
than failing the query.

Signed-off-by: discord9 <discord9@163.com>

* test(promql): pin what a one-sample fold does to an explicit empty bucket

The fold answers through `finished_histogram`, which compacts an explicit zero bucket away, so a
`sum` or `avg` over a single sample answers `[1]` where that sample carried `[1, 0]`. The legacy
accumulator kept the bucket before this refactor, because it handed a one-sample group's histogram
back untouched; the native `Aggregate` node has always answered the compacted form, so the two
paths agree now.

`promql_eq` tells an explicit zero bucket from an absent one, so `sum(h)` is no longer equal to the
single sample `h` it folded. Both tests document that, and the second one takes the answer through
a partial state round trip - `state()` into a fresh accumulator's `merge_batch()` - to show the
boundary does not re-introduce the bucket.

The comments on the three places that drop an unreadable layout now say what the code does rather
than how it differs from the accumulator this replaced: a layout this crate cannot read drops the
position as a whole, with the warning below, instead of failing the query.

Signed-off-by: discord9 <discord9@163.com>

---------

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-24 09:16:36 +00:00
committed by GitHub
parent 82bdd7fd27
commit a6cc055e83
2 changed files with 858 additions and 115 deletions
+51 -28
View File
@@ -624,7 +624,7 @@ fn finish_histogram_group(
/// mean with the compensation folded in; one that never switched divides the sum and the compensation
/// by the sample count and then folds the compensation in, which is what `sum_or_avg` does at the end
/// of both paths.
fn finished_histogram(
pub(crate) fn finished_histogram(
op: AggregateOp,
accumulator: &HistogramAccumulator,
) -> Result<Option<FloatHistogram>> {
@@ -1171,7 +1171,11 @@ struct Group {
/// `histogram_value`, `mean` is its `incremental_mean` mode, `count` is its `count`, and
/// `compensation` is its `histogram_compensation`. A `sum` fold leaves `mean` at `None` and only
/// counts for the average's sake.
struct HistogramAccumulator {
///
/// The legacy `prom_native_histogram_agg_sum`/`_avg` accumulators fold through this one as well, so
/// their arithmetic is this arithmetic; only their state frame differs.
#[derive(Debug)]
pub(crate) struct HistogramAccumulator {
/// The live value: the running sum, or -- once an average switched -- the sum the switch started
/// from, which the mean is derived from.
value: FloatHistogram,
@@ -1185,7 +1189,9 @@ struct HistogramAccumulator {
mean: Option<FloatHistogram>,
/// Samples folded into this position, which is the divisor an average's mean uses.
count: f64,
evidence: HistogramEvidence,
/// The evidence bits this fold recorded. A legacy accumulator keeps its own copy of the bits its
/// state frame can carry and seeds them in before every operation.
pub(crate) evidence: HistogramEvidence,
}
/// The evidence bits a histogram fold records beside its payload.
@@ -1413,16 +1419,10 @@ impl Group {
.saturating_add(backing),
)?;
}
let accumulator = self.histograms.entry(key).or_insert_with(|| {
let compensation = sample.new_compensation();
HistogramAccumulator {
value: sample.clone(),
compensation: Some(compensation),
mean: None,
count: 1.0,
evidence: HistogramEvidence::default(),
}
});
let accumulator = self
.histograms
.entry(key)
.or_insert_with(|| HistogramAccumulator::from_sample(&sample));
// The evidence follows the sample's own reset hint, whether or not the point still folds.
match sample.reset_hint {
CounterResetHint::CounterReset => accumulator.evidence.counter_reset_seen = true,
@@ -1446,12 +1446,10 @@ impl Group {
.saturating_add(before)
.saturating_add(sample.heap_bytes()),
)?;
if accumulator.value.uses_custom_buckets() != sample.uses_custom_buckets() {
if accumulator.uses_custom_buckets() != sample.uses_custom_buckets() {
// Exponential buckets cannot be added to custom ones: the point is removed rather than
// answered, and the evidence says why.
accumulator.evidence.poisoned = true;
accumulator.evidence.incompatible_layout = true;
accumulator.compensation = None;
accumulator.poison();
return Ok(retained);
}
match fold.op {
@@ -1466,8 +1464,36 @@ impl Group {
}
impl HistogramAccumulator {
/// A fold that has taken `sample` and nothing else: the sample is the live value, the
/// compensation is the layout-carrying zero built beside it, and one sample is counted.
pub(crate) fn from_sample(sample: &FloatHistogram) -> Self {
Self {
value: sample.clone(),
compensation: Some(sample.new_compensation()),
mean: None,
count: 1.0,
evidence: HistogramEvidence::default(),
}
}
/// Whether the live value -- the mean once an average switched -- uses custom buckets.
pub(crate) fn uses_custom_buckets(&self) -> bool {
match &self.mean {
Some(mean) => mean.uses_custom_buckets(),
None => self.value.uses_custom_buckets(),
}
}
/// Removes this position: its samples disagreed on their bucket layout, so it answers nothing
/// and the evidence says why.
pub(crate) fn poison(&mut self) {
self.evidence.poisoned = true;
self.evidence.incompatible_layout = true;
self.compensation = None;
}
/// Adds one sample into the running sum, one compensated add into the live value.
fn fold_sum(&mut self, sample: &FloatHistogram) -> Result<()> {
pub(crate) fn fold_sum(&mut self, sample: &FloatHistogram) -> Result<()> {
let (compensation, outcome) = self.value.kahan_add(sample, self.compensation.take())?;
self.compensation = Some(compensation);
self.evidence.custom_bounds_reconciled |= outcome.custom_bounds_reconciled;
@@ -1483,7 +1509,7 @@ impl HistogramAccumulator {
/// `sample / count` weighted by `(count - 1) / count`. Dividing before adding is what keeps a
/// mean of finite inputs finite: two histograms of `1e308` at one observation each average to
/// `1e308`, while `(1e308 + 1e308) / 2` would be `Inf`.
fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> {
pub(crate) fn fold_avg(&mut self, sample: &FloatHistogram) -> Result<()> {
self.count += 1.0;
if self.mean.is_none() {
// The trial runs on a copy, so an overflowing add leaves the sum it started from intact
@@ -1532,7 +1558,7 @@ impl HistogramAccumulator {
///
/// A poisoned position exports the empty placeholders the state layout reserves for it: it
/// answers nothing, and the merge reads its evidence, not its buckets.
fn payload(&self, op: AggregateOp) -> Result<StatePayload> {
pub(crate) fn payload(&self, op: AggregateOp) -> Result<StatePayload> {
if self.evidence.poisoned {
let empty = self.value.empty_like();
return Ok(StatePayload::Histogram(Box::new(HistogramState {
@@ -1579,7 +1605,7 @@ impl HistogramAccumulator {
}
/// The state a decoded payload carries, as the merge keeps it.
fn from_payload(op: AggregateOp, payload: &HistogramState) -> Result<Self> {
pub(crate) fn from_payload(op: AggregateOp, payload: &HistogramState) -> Result<Self> {
let value = decoded_histogram(&payload.value)?;
let compensation = decoded_histogram(&payload.compensation)?;
let switched = op == AggregateOp::Avg && payload.incremental_mean;
@@ -1610,7 +1636,7 @@ impl HistogramAccumulator {
/// into the live value, and an average either adds its sums the same way -- when that stays
/// finite -- or continues in mean mode from the means and the counts, dividing before it adds.
/// Poison is sticky, and both sides' evidence is kept whatever the outcome of the arithmetic.
fn merge_state(&mut self, op: AggregateOp, other: &HistogramState) -> Result<()> {
pub(crate) fn merge_state(&mut self, op: AggregateOp, other: &HistogramState) -> Result<()> {
self.evidence.poisoned |= other.poisoned;
self.evidence.incompatible_layout |= other.incompatible_layout;
self.evidence.custom_bounds_reconciled |= other.custom_bounds_reconciled;
@@ -1626,10 +1652,7 @@ impl HistogramAccumulator {
// buckets, the other custom ones. The fold removes such a point when both layouts meet
// inside one partition, so the merge reports it the same way instead of letting the add
// refuse the layouts and fail the whole statement.
let left_uses_custom = match &self.mean {
Some(mean) => mean.uses_custom_buckets(),
None => self.value.uses_custom_buckets(),
};
let left_uses_custom = self.uses_custom_buckets();
if left_uses_custom != right.uses_custom_buckets() {
self.evidence.poisoned = true;
self.evidence.incompatible_layout = true;
@@ -1745,7 +1768,7 @@ impl HistogramAccumulator {
}
/// One histogram as the frame payload's own one-row batch.
fn histogram_batch(histogram: &FloatHistogram) -> Result<Arc<HistogramBatch>> {
pub(crate) fn histogram_batch(histogram: &FloatHistogram) -> Result<Arc<HistogramBatch>> {
let mut builder = HistogramBatchBuilder::new();
histogram.push_to(&mut builder)?;
builder.finish().map_err(external)
@@ -1789,7 +1812,7 @@ fn evidence_summary(groups: &[Group]) -> HistogramEvidence {
}
/// Bytes one histogram position holds: every histogram it keeps, with buckets, bounds and spans.
fn accumulator_bytes(accumulator: &HistogramAccumulator) -> usize {
pub(crate) fn accumulator_bytes(accumulator: &HistogramAccumulator) -> usize {
size_of::<HistogramAccumulator>()
.saturating_add(accumulator.value.heap_bytes())
.saturating_add(
File diff suppressed because it is too large Load Diff