Repository navigation
Conversation
bwplotka
marked this pull request as draft
October 1, 2026 23:25
bwplotka
commented
Oct 1, 2026
| ## NHCB as classic histograms in PromQL | ||
| ## Native histograms as classic histograms in PromQL | ||
|
|
||
| `--enable-feature=promql-nhcb-as-classic` |
Member
Author
There was a problem hiding this comment.
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).
bwplotka
commented
Oct 1, 2026
| // 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 { |
Member
Author
There was a problem hiding this comment.
Obviously name would need to change if we want to accept such a feature
bwplotka
commented
Oct 2, 2026
bwplotka
force-pushed
the
bwplotka/pr-18048-nhe-as-classic
branch
2 times, most recently
from
October 3, 2026 18:42
0645e10 to
5cb0277
Compare
bwplotka
force-pushed
the
bwplotka/pr-18048-nhe-as-classic
branch
2 times, most recently
from
October 6, 2026 05:26
13b7f7e to
e0f3dbc
Compare
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]>
…ssic Signed-off-by: Bartek Plotka <[email protected]>
bwplotka
force-pushed
the
bwplotka/pr-18048-nhe-as-classic
branch
from
October 6, 2026 05:32
e0f3dbc to
0734e5c
Compare
This was referenced Nov 3, 2026
…onentialBounds 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #19905 (base branch
bwplotka/pr-18048-nhe-label-control). Part of #18048.This extends
NHCBAsClassicQuerierso thatpromql-nhcb-as-classicalso serves_bucket,_countand_sumqueries 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 classiclebounds, 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:leselectors. Bounds like0.1,2.5,5,10never exist on an exponential grid (only1is a boundary in every schema, powers of two are boundaries for schemas >= 0, and all sub-buckets in schema 1..8 are irrational), sorate(x_bucket{le="0.1"}[5m])finds nothing. Evenle="1.0"is missing whenever bucket index 0 had no observations. On top of that, classic Prometheus text format spells itle="1"while the converter emits OpenMetricsle="1.0", so an equality matcher fails on string comparison (this already affected NHCB), and the usualle=~"0.1|0.5"spelling is not a literal set forSetMatches()because of the unescaped dots.histogram_quantilewith missing lower anchors.BucketQuantileinterpolates from the previous emittedleto the current one. If only(1,2]is populated andle="1.0"is not emitted, it interpolates across[0,2]instead of(1,2], and the same happens across gaps between spans.rate()over dynamic spans. A bucket that gets its first observation att2has no sample att1, sorate()has no baseline and loses the observation; a bucket that empties after a counter reset would get aStaleNaNfromclassicSeriesBuilder.endStep.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,BucketQuantileclamps it (HistogramQuantileForcedMonotonicityInfo) and pod b's observations get pushed into(2,+Inf]._bucketseries.Mitigations in this PR
_countand_sumneed 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 walkingAllBucketIterator(): buckets fully below a bound are summed exactly, and the single bucket straddling a bound is interpolated withBucket.FractionBelowafterFloatHistogram.InterpolationBounds(model/histogram/float_histogram.go#L69-L94), which is the exact bound adjustmenthistogram_fractionuses (it was extracted fromHistogramFractionso the two cannot drift, andTestConvertExponentialToClassic_HistogramFractionCrossCheckasserts they agree). A bound that coincides with an exponential boundary is therefore exact even when that bucket is absent from the spans, which fixesle="1.0"in (1) and the missing anchors in (2). The+Infbucket ismax(h.Count, sum of buckets): NaN observations count like in classic, and float histograms with aCountbelow their bucket sum stay monotonic. The bounds themselves are chosen inSelectwith this precedence:lematchers 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 matchlenumerically (storage/nhcb_querier.go#L1069-L1105):le="1"andle="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 asle="0.1"are served as interpolated estimates rather than nothing; this is documented in the feature flag docs.Selectneeds oneleset for the whole selector ("exponential mode"): the union of the lower and upper bounds of every populated bucket across all exponential series and samples viaAppendExponentialBounds(model/histogram/convert.go#L305-L349), reduced toexponentialAsClassicMaxSchema = 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 andsum 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).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).leset 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.__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
lematching on converted series; the collision, shadowing and staleness handling from #19881 applies to exponential samples as well.Commits
model/histogram: compute NHCB cumulative counts before emitting classic series: pure refactor, shared emission and cache.model/histogram: share histogram_fraction's bucket bound adjustments: extractsFloatHistogram.InterpolationBoundsfromHistogramFraction, no behaviour change.model/histogram: add ConvertExponentialToClassic and AppendExponentialBounds: the new API, tests and thehistogram_fractioncross-check.storage: convert exponential native histograms in NHCBAsClassicQuerier: detection, bounds selection,lematching,"nhe"selector control/debug label, tests and benchmark.docs: describe exponential native histograms under promql-nhcb-as-classic.model/histogram: use InterpolationBounds for zero bucket in AppendExponentialBounds: alignsAppendExponentialBoundszero-bucket bounds withFloatHistogram.InterpolationBounds.storage: reuse histogram scratch buffers in exponential bounds collection: makeshandfhvalue fields onnhcbToClassicSeriesSetand reuses scratch buffers across series and samples.model/histogram: expand convert and exponential bounds unit tests.promql: cover one-sided zero buckets in histogram_fraction cross-checks.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,
Countbelow 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 classicle, 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% ofhistogram_quantile(0.9, rate(x[1m]))per pod,histogram_quantile(0.5, sum by (le) (...))matched the nativesum(...), andrate(x_count[1m])andx_sumwere exact.benchstatagainst #19881 on its benchmarks (-count 6 -cpu 2) shows no change on the NHCB paths (NHCBAsClassicSelect_{Bucket,Count,Sum}all~). OnBenchmarkExponentialAsClassicSelect(100 schema 3 series x 30 buckets x 180 samples), reusing theFloatHistogramscratch buffer across series and samples (0734e5cc09 before vs b1af778742 after):Open points I would like input on: whether schema 2 is the right cap (or should be a flag), whether the data dependent
leset 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 classiclegrid for the exponential pods (todaysum by (le)across such a fleet mixes two grids).