Skip to content

storage: convert exponential native histograms to classic in NHCBAsClassicQuerier - #19886

Draft
bwplotka wants to merge 10 commits into
bwplotka/pr-18048-nhe-label-controlfrom
bwplotka/pr-18048-nhe-as-classic
Draft

bwplotka wants to merge 10 commits into
bwplotka/pr-18048-nhe-label-controlfrom
bwplotka/pr-18048-nhe-as-classic

Conversation

@bwplotka

@bwplotka bwplotka commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Stacked on #19905 (base branch bwplotka/pr-18048-nhe-label-control). Part of #18048.

This extends NHCBAsClassicQuerier so that promql-nhcb-as-classic also serves _bucket, _count and _sum queries from exponential (standard schema) native histograms, not only NHCB. The previous PRs made NHCB conversion lossless and streaming and added __opt_classic_from / __stored_as__ per-selector control; exponential histograms are harder because they have no fixed bucket layout. Below is what breaks if you convert them naively, and what this PR does about it.

What is problematic

NHCB samples carry CustomValues, the full list of classic le bounds, even for empty buckets, so conversion is a straight loop. Exponential samples carry only sparse, data dependent spans on an implicit base 2 grid. Converting one sample at a time by emitting the buckets that happen to be populated breaks classic queries in several ways:

  1. le selectors. Bounds like 0.1, 2.5, 5, 10 never exist on an exponential grid (only 1 is a boundary in every schema, powers of two are boundaries for schemas >= 0, and all sub-buckets in schema 1..8 are irrational), so rate(x_bucket{le="0.1"}[5m]) finds nothing. Even le="1.0" is missing whenever bucket index 0 had no observations. On top of that, classic Prometheus text format spells it le="1" while the converter emits OpenMetrics le="1.0", so an equality matcher fails on string comparison (this already affected NHCB), and the usual le=~"0.1|0.5" spelling is not a literal set for SetMatches() because of the unescaped dots.
  2. histogram_quantile with missing lower anchors. BucketQuantile interpolates from the previous emitted le to the current one. If only (1,2] is populated and le="1.0" is not emitted, it interpolates across [0,2] instead of (1,2], and the same happens across gaps between spans.
  3. rate() over dynamic spans. A bucket that gets its first observation at t2 has no sample at t1, so rate() has no baseline and loses the observation; a bucket that empties after a counter reset would get a StaleNaN from classicSeriesBuilder.endStep.
  4. sum by (le) across series with different spans. If pod a only populates (0.5,1] and pod b only (1,2], le="2.0" is missing pod a's cumulative count, the sum is non monotonic, BucketQuantile clamps it (HistogramQuantileForcedMonotonicityInfo) and pod b's observations get pushed into (2,+Inf].
  5. Cardinality. Schema 8 has 256 buckets per power of two; materialising 1ms..64s densely for 1,000 series is millions of _bucket series.

Mitigations in this PR

_count and _sum need no bounds and are converted directly, keeping the streaming fast path.

For _bucket, model/histogram.ConvertExponentialToClassic (model/histogram/convert.go#L223-L264) evaluates the cumulative count at an arbitrary sorted set of classic bounds by walking AllBucketIterator(): buckets fully below a bound are summed exactly, and the single bucket straddling a bound is interpolated with Bucket.FractionBelow after FloatHistogram.InterpolationBounds (model/histogram/float_histogram.go#L69-L94), which is the exact bound adjustment histogram_fraction uses (it was extracted from HistogramFraction so the two cannot drift, and TestConvertExponentialToClassic_HistogramFractionCrossCheck asserts they agree). A bound that coincides with an exponential boundary is therefore exact even when that bucket is absent from the spans, which fixes le="1.0" in (1) and the missing anchors in (2). The +Inf bucket is max(h.Count, sum of buckets): NaN observations count like in classic, and float histograms with a Count below their bucket sum stay monotonic. The bounds themselves are chosen in Select with this precedence:

  • If the le matchers pin literal values (equality, or a regex that is a set of numbers, escaped or not), boundsFromLeMatchers (storage/nhcb_querier.go#L730-L774) evaluates exactly those and the series set keeps streaming. Converted series match le numerically (storage/nhcb_querier.go#L1069-L1105): le="1" and le="1.0" are the same bound, and regexes are tried against both spellings. Stored classic series keep plain string matching, so results do not depend on whether a native series exists for the metric. Non boundary values such as le="0.1" are served as interpolated estimates rather than nothing; this is documented in the feature flag docs.
  • Otherwise Select needs one le set for the whole selector ("exponential mode"): the union of the lower and upper bounds of every populated bucket across all exponential series and samples via AppendExponentialBounds (model/histogram/convert.go#L305-L349), reduced to exponentialAsClassicMaxSchema = 2 (storage/nhcb_querier.go#L153-L159). Emitting both bounds of each populated bucket fixes (2); emitting the same set for every sample and series fixes (3) and (4), because every bucket has a baseline and sum by (le) sees identical layouts, which is the invariant classic histograms give you for free. 4 buckets per power of two means a 1ms..64s distribution yields roughly 64 bounds instead of 4,096 at schema 8, addressing (5).
  • Native series are classified by their first non-stale sample (storage/nhcb_querier.go#L676-L724), as stale markers are schema 0 histograms. The streaming path (no stored classic, PromQL's sortSeries=false) only leaves streaming when it meets the first exponential series and then buffers the remaining ones (storage/nhcb_querier.go#L1232-L1242, storage/nhcb_querier.go#L1286-L1305), so pure-NHCB selections are unaffected and the result does not depend on label order; the grouped path checks every series. Exponential mode decodes each series twice (bounds pass, then conversion).
  • A series that starts as NHCB and switches to an exponential schema mid-way is not seen as exponential by the classification; its exponential samples discover bounds from the series alone (storage/nhcb_querier.go#L1553-L1571). That keeps the le set stable across its samples (3) but cannot unify across series (4); it is a graceful fallback for mid-series migrations rather than the designed path.
  • Per-selector control (__opt_classic_from) and provenance (__stored_as__) from storage: add __opt_classic_from selector control and __stored_as__ debug label #19905 are extended with "nhe", allowing selectors to convert only NHCB (__opt_classic_from="nhcb" / !="nhe"), only exponential histograms (__opt_classic_from="nhe" / !="nhcb"), or both (=~"nhcb|nhe", default), and tagging exponential-converted series with __stored_as__="nhe" in debug mode.

Pure NHCB behaviour is unchanged apart from numeric le matching on converted series; the collision, shadowing and staleness handling from #19881 applies to exponential samples as well.

Commits

  1. model/histogram: compute NHCB cumulative counts before emitting classic series: pure refactor, shared emission and cache.
  2. model/histogram: share histogram_fraction's bucket bound adjustments: extracts FloatHistogram.InterpolationBounds from HistogramFraction, no behaviour change.
  3. model/histogram: add ConvertExponentialToClassic and AppendExponentialBounds: the new API, tests and the histogram_fraction cross-check.
  4. storage: convert exponential native histograms in NHCBAsClassicQuerier: detection, bounds selection, le matching, "nhe" selector control/debug label, tests and benchmark.
  5. docs: describe exponential native histograms under promql-nhcb-as-classic.
  6. model/histogram: use InterpolationBounds for zero bucket in AppendExponentialBounds: aligns AppendExponentialBounds zero-bucket bounds with FloatHistogram.InterpolationBounds.
  7. storage: reuse histogram scratch buffers in exponential bounds collection: makes h and fh value fields on nhcbToClassicSeriesSet and reuses scratch buffers across series and samples.
  8. model/histogram: expand convert and exponential bounds unit tests.
  9. promql: cover one-sided zero buckets in histogram_fraction cross-checks.
  10. storage: expand le matcher and sorted series tests for exponential histograms.

Verification

Unit tests cover exact and interpolated bounds, zero-only, negative-only and NaN histograms, Count below the bucket sum, schema reduction, integer and float exponential series, a leading stale marker, unified bounds across series, samples and across NHCB/exponential mixes on both the streaming and the grouped path, le="1"/le="0.95"/escaped and unescaped regex set pinning, string matching of stored classic le, shadowing by stored classic, both transition directions, and __opt_classic_from="nhe" / __stored_as__="nhe" (storage/nhcb_querier_test.go#L917-L1980).

I also compared the real engine over a TSDB with two pods of growing schema 3 and schema 2 histograms: histogram_quantile(0.9, rate(x_bucket[1m])) was within 0.6% of histogram_quantile(0.9, rate(x[1m])) per pod, histogram_quantile(0.5, sum by (le) (...)) matched the native sum(...), and rate(x_count[1m]) and x_sum were exact.

benchstat against #19881 on its benchmarks (-count 6 -cpu 2) shows no change on the NHCB paths (NHCBAsClassicSelect_{Bucket,Count,Sum} all ~). On BenchmarkExponentialAsClassicSelect (100 schema 3 series x 30 buckets x 180 samples), reusing the FloatHistogram scratch buffer across series and samples (0734e5cc09 before vs b1af778742 after):

goos: linux
goarch: amd64
pkg: github.com/prometheus/prometheus/storage
cpu: Intel(R) Xeon(R) CPU @ 2.20GHz
                                                 │ /tmp/bench_before_19886.txt │     /tmp/bench_after_19886.txt      │
                                                 │           sec/op            │    sec/op     vs base               │
ExponentialAsClassicSelect/suffix=_bucket-2                        84.56m ± 1%   83.85m ±  4%        ~ (p=0.132 n=6)
ExponentialAsClassicSelect/suffix=_bucket,le=1-2                   23.00m ± 2%   24.80m ±  0%   +7.79% (p=0.002 n=6)
ExponentialAsClassicSelect/suffix=_count-2                         2.772m ± 7%   4.485m ± 36%  +61.83% (p=0.004 n=6)
geomean                                                            17.53m        21.05m        +20.05%

                                                 │ /tmp/bench_before_19886.txt │     /tmp/bench_after_19886.txt     │
                                                 │            B/op             │     B/op      vs base              │
ExponentialAsClassicSelect/suffix=_bucket-2                       26.81Mi ± 0%   24.48Mi ± 0%  -8.71% (p=0.002 n=6)
ExponentialAsClassicSelect/suffix=_bucket,le=1-2                  2.557Mi ± 0%   2.557Mi ± 0%  +0.01% (p=0.002 n=6)
ExponentialAsClassicSelect/suffix=_count-2                        380.7Ki ± 0%   380.9Ki ± 0%  +0.06% (p=0.002 n=6)
geomean                                                           2.943Mi        2.856Mi       -2.97%

                                                 │ /tmp/bench_before_19886.txt │     /tmp/bench_after_19886.txt     │
                                                 │          allocs/op          │  allocs/op   vs base               │
ExponentialAsClassicSelect/suffix=_bucket-2                        45.18k ± 0%   27.18k ± 0%  -39.84% (p=0.002 n=6)
ExponentialAsClassicSelect/suffix=_bucket,le=1-2                   10.05k ± 0%   10.05k ± 0%   -0.01% (p=0.002 n=6)
ExponentialAsClassicSelect/suffix=_count-2                         3.038k ± 0%   3.037k ± 0%   -0.03% (p=0.002 n=6)
geomean                                                            11.13k        9.396k       -15.60%

Open points I would like input on: whether schema 2 is the right cap (or should be a flag), whether the data dependent le set in exponential mode is acceptable versus a fixed grid that would emit many empty buckets, and whether a rolling migration with some pods still on classic should reuse the stored classic le grid for the exponential pods (today sum by (le) across such a fleet mixes two grids).

[ENHANCEMENT] PromQL: The `promql-nhcb-as-classic` feature flag now also converts exponential native histograms to classic `_bucket`, `_count` and `_sum` series.

@bwplotka
bwplotka requested review from a team and krajorama as code owners October 1, 2026 23:23
@bwplotka
bwplotka marked this pull request as draft October 1, 2026 23:25
Comment thread docs/feature_flags.md
## NHCB as classic histograms in PromQL
## Native histograms as classic histograms in PromQL

`--enable-feature=promql-nhcb-as-classic`

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ignore naming for now, if we think this make sense, we will evolve feature flag and ensure configuration is more flexible (allows only selecting nhcb or nhe conversions).

Comment thread storage/nhcb_querier.go
// NHCBAsClassicQuerier wraps a Querier and converts native histogram (NHCB and
// exponential) queries to classic histogram format when classic series don't
// exist.
type NHCBAsClassicQuerier struct {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Obviously name would need to change if we want to accept such a feature

Comment thread storage/nhcb_querier.go Resolved
Comment thread storage/nhcb_querier.go Resolved
Comment thread docs/feature_flags.md Resolved
@bwplotka
bwplotka force-pushed the bwplotka/pr-18048-nhe-as-classic branch 2 times, most recently from 0645e10 to 5cb0277 Compare October 3, 2026 18:42
@bwplotka
bwplotka force-pushed the bwplotka/pr-18048-nhe-as-classic branch 2 times, most recently from 13b7f7e to e0f3dbc Compare October 6, 2026 05:26
@bwplotka
bwplotka changed the base branch from bwplotka/pr-18048-resolve-collisions to bwplotka/pr-18048-nhe-label-control October 6, 2026 05:26
…ic series

Pure refactor in preparation for converting exponential native histograms
to classic series: ConvertNHCBToClassic now first turns the NHCB buckets
into cumulative counts and then emits the _bucket/_count/_sum series via a
shared emitClassicSeries helper. ClassicSeriesCache is generalized from
custom values to arbitrary bounds plus a reusable cumulative buffer so that
the same cache can serve both conversions. No behaviour change.

Signed-off-by: Bartek Plotka <[email protected]>
Move the bucket bound adjustments histogram_fraction applies before
interpolating (0 as the lower bound of the first custom bucket, 0 as the
lower or upper bound of the zero bucket for one-sided exponential
histograms, linear vs exponential interpolation) into
FloatHistogram.InterpolationBounds, so that the exponential-to-classic
conversion added next can reuse them and cannot drift from PromQL. No
behaviour change.

Signed-off-by: Bartek Plotka <[email protected]>
…lBounds

ConvertExponentialToClassic evaluates the cumulative count of an
exponential (standard schema) native histogram at a given set of classic
upper bounds and emits _bucket/_count/_sum series through the same
emitClassicSeries path as NHCB. Bounds that are not exponential bucket
boundaries are interpolated exactly like histogram_fraction, via
FloatHistogram.InterpolationBounds; a cross-check test in promql asserts
the two stay identical. The +Inf bucket is max(Count, sum of buckets), as
float histograms are not validated for Count >= bucket sum.

AppendExponentialBounds collects the lower and upper bounds of the
populated buckets after reducing the schema to a cap, which callers use to
derive a data-dependent classic bucket layout.

Signed-off-by: Bartek Plotka <[email protected]>
With promql-nhcb-as-classic, _bucket/_count/_sum selectors now also cover
exponential (standard schema) native histograms, not only NHCB.

Native series are classified by their first non-stale sample (stale
markers are schema 0 histograms and carry no schema information). _count
and _sum convert directly. For _bucket the classic bounds are chosen as
follows:

  - le matchers that pin values (equality, or a regex that is a plain set of
    numbers such as le=~"0.1|0.5", escaped or not) are evaluated exactly at
    those values on every sample, so the streaming path is kept. Converted
    series match le numerically ("1" and "1.0" are the same bound, and
    regexes are tried against both spellings), while stored classic series
    keep plain string matching like the storage fast path.
  - Otherwise the populated bucket bounds of all exponential series of the
    selector, reduced to schema 2, are unified so that every series and
    sample emits the same le set, which is what rate() and sum by (le)
    need. The streaming path switches into this mode when it meets the
    first exponential series, so pure-NHCB selections keep streaming; the
    grouped path (stored classic series present or sortSeries) checks all
    series. A series that switches from NHCB to exponential mid-way falls
    back to bounds derived from its own samples.
  - __opt_classic_from and __stored_as__ are extended with "nhe" so selectors
    can enable/disable NHCB and exponential conversion independently and
    distinguish series converted from exponential histograms in debug mode.

Benchmark for the unpinned _bucket, pinned le and _count paths included.

Signed-off-by: Bartek Plotka <[email protected]>
…tion

Use value fields for h and fh on nhcbToClassicSeriesSet and pass scratch Histogram and FloatHistogram pointers through unifiedExponentialBounds and appendSeriesExponentialBounds so bounds collection reuses buffers across series and samples.

Signed-off-by: Bartek Plotka <[email protected]>
Cover same-length and different-length CustomValues changes on ClassicSeriesCache reuse, ZeroThreshold == 0 with ZeroCount > 0 in ConvertExponentialToClassic, and negative-bucket schema reduction, zero-count negative buckets, and positive-only/zero-only/two-sided zero buckets in AppendExponentialBounds.

Signed-off-by: Bartek Plotka <[email protected]>
Add one-sided positive and one-sided negative exponential histogram test cases with populated zero buckets to fractionCrossCheckCases so both TestTrimBuckets_HistogramFractionCrossCheck and TestConvertExponentialToClassic_HistogramFractionCrossCheck exercise the one-sided zero-bucket bound adjustments in FloatHistogram.InterpolationBounds.

Signed-off-by: Bartek Plotka <[email protected]>
…stograms

Assert the full sorted series output on sortSeries=true when mixing NHCB and exponential histograms, and add test cases for non-pinning regex le matchers, multiple pinning le matchers, and numeric/string MatchNotEqual le matchers.

Signed-off-by: Bartek Plotka <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant