Skip to content

Commit d4e51d5

Browse files
authored
add WrappedHistogram with size limit before unmarshal (#7570)
Signed-off-by: Paurush Garg <paurushg@amazon.com>
1 parent 9fb947d commit d4e51d5

20 files changed

Lines changed: 422 additions & 381 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
* [ENHANCEMENT] Instrument Ingester CPU profile with source for read APIs. #7494
2929
* [ENHANCEMENT] Ingester: Convert expanded postings cache from FIFO to LRU eviction to retain frequently-queried entries under memory pressure. #7510
3030
* [ENHANCEMENT] Querier: Detach series label and chunk data from gRPC unmarshal buffers in store-gateway streaming path, allowing the Go GC to reclaim receive buffers. #7519
31+
* [ENHANCEMENT] Distributor: Add `WrappedHistogram` with configurable size limit (`-validation.max-native-histogram-size-bytes`) to cap native histogram protobuf size before unmarshalling. #7570
3132
* [BUGFIX] Querier: Fix queryWithRetry and labelsWithRetry returning (nil, nil) on cancelled context by propagating ctx.Err(). #7370
3233
* [BUGFIX] Metrics Helper: Fix non-deterministic bucket order in merged histograms by sorting buckets after map iteration, matching Prometheus client library behavior. #7380
3334
* [BUGFIX] Distributor: Return HTTP 401 Unauthorized when tenant ID resolution fails in the Prometheus Remote Write 2.0 path. #7389

‎integration/remote_write_v2_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ func TestIngest_CreatedTimestampFallback(t *testing.T) {
625625
TimeSeriesV2: &cortexpb.TimeSeriesV2{
626626
LabelsRefs: []uint32{1, 2},
627627
CreatedTimestamp: e2e.TimeToMilliseconds(startTs),
628-
Histograms: []cortexpb.Histogram{h},
628+
Histograms: []cortexpb.WrappedHistogram{cortexpb.WrapHistogram(h)},
629629
},
630630
},
631631
},
@@ -778,7 +778,7 @@ func TestIngest_StartAndCreatedTimestampIgnoredWhenDisabled(t *testing.T) {
778778
TimeSeriesV2: &cortexpb.TimeSeriesV2{
779779
LabelsRefs: []uint32{1, 2},
780780
CreatedTimestamp: e2e.TimeToMilliseconds(startTs),
781-
Histograms: []cortexpb.Histogram{h},
781+
Histograms: []cortexpb.WrappedHistogram{cortexpb.WrapHistogram(h)},
782782
},
783783
}},
784784
}

‎pkg/cortexpb/compat.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020

2121
// ToWriteRequest converts matched slices of Labels, Samples, Metadata and Histograms into a WriteRequest proto.
2222
// It gets timeseries from the pool, so ReuseSlice() should be called when done.
23-
func ToWriteRequest(lbls []labels.Labels, samples []Sample, metadata []*MetricMetadata, histograms []Histogram, source SourceEnum) *WriteRequest {
23+
func ToWriteRequest(lbls []labels.Labels, samples []Sample, metadata []*MetricMetadata, histograms []WrappedHistogram, source SourceEnum) *WriteRequest {
2424
req := &WriteRequest{
2525
Timeseries: PreallocTimeseriesSliceFromPool(),
2626
Metadata: metadata,
@@ -44,7 +44,7 @@ func ToWriteRequest(lbls []labels.Labels, samples []Sample, metadata []*MetricMe
4444
return req
4545
}
4646

47-
func (w *WriteRequest) AddHistogramTimeSeries(lbls []labels.Labels, histograms []Histogram) {
47+
func (w *WriteRequest) AddHistogramTimeSeries(lbls []labels.Labels, histograms []WrappedHistogram) {
4848
for i := range lbls {
4949
ts := TimeseriesFromPool()
5050
ts.Labels = append(ts.Labels, FromLabelsToLabelAdapters(lbls[i])...)

‎pkg/cortexpb/cortex.pb.go‎

Lines changed: 117 additions & 153 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pkg/cortexpb/cortex.proto‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ message TimeSeriesV2 {
4747
//
4848
// Samples and histograms are sorted by timestamp (older first).
4949
repeated Sample samples = 2 [(gogoproto.nullable) = false];
50-
repeated Histogram histograms = 3 [(gogoproto.nullable) = false];
50+
repeated Histogram histograms = 3 [(gogoproto.nullable) = false, (gogoproto.customtype) = "WrappedHistogram"];
5151

5252
// exemplars represents an optional set of exemplars attached to this series' samples.
5353
repeated ExemplarV2 exemplars = 4 [(gogoproto.nullable) = false];
@@ -140,7 +140,7 @@ message TimeSeries {
140140
// Sorted by time, oldest sample first.
141141
repeated Sample samples = 2 [(gogoproto.nullable) = false];
142142
repeated Exemplar exemplars = 3 [(gogoproto.nullable) = false];
143-
repeated Histogram histograms = 4 [(gogoproto.nullable) = false];
143+
repeated Histogram histograms = 4 [(gogoproto.nullable) = false, (gogoproto.customtype) = "WrappedHistogram"];
144144
}
145145

146146
message LabelPair {

‎pkg/cortexpb/histograms.go‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
package cortexpb
1515

1616
import (
17+
"fmt"
18+
1719
"github.com/prometheus/prometheus/model/histogram"
1820
"github.com/prometheus/prometheus/prompb"
1921
)
@@ -176,3 +178,51 @@ func (h Histogram) BucketCount() int {
176178
}
177179
return count
178180
}
181+
182+
// MaxWrappedHistogramSizeBytes is the maximum allowed size of a single native histogram in raw protobuf
183+
// bytes before unmarshalling. A value of 0 disables the limit.
184+
var maxWrappedHistogramSizeBytes = 16 * 1024
185+
186+
// WrappedHistogram is a Histogram with a size check on Unmarshal.
187+
// Used only on the ingestion path, not on the query path.
188+
type WrappedHistogram struct {
189+
Histogram
190+
}
191+
192+
// Unmarshal implements proto.Message.
193+
func (p *WrappedHistogram) Unmarshal(dAtA []byte) error {
194+
if maxWrappedHistogramSizeBytes > 0 && len(dAtA) > maxWrappedHistogramSizeBytes {
195+
return fmt.Errorf("native histogram size %d bytes exceeds limit %d bytes", len(dAtA), maxWrappedHistogramSizeBytes)
196+
}
197+
return p.Histogram.Unmarshal(dAtA)
198+
}
199+
200+
// Marshal implements proto.Marshaler.
201+
func (p *WrappedHistogram) Marshal() (dAtA []byte, err error) {
202+
return p.Histogram.Marshal()
203+
}
204+
205+
// MarshalTo implements proto.Marshaler.
206+
func (p *WrappedHistogram) MarshalTo(dAtA []byte) (int, error) {
207+
return p.Histogram.MarshalTo(dAtA)
208+
}
209+
210+
// MarshalToSizedBuffer implements proto.Marshaler.
211+
func (p *WrappedHistogram) MarshalToSizedBuffer(dAtA []byte) (int, error) {
212+
return p.Histogram.MarshalToSizedBuffer(dAtA)
213+
}
214+
215+
// Size implements proto.Sizer.
216+
func (p *WrappedHistogram) Size() int {
217+
return p.Histogram.Size()
218+
}
219+
220+
// Equal implements proto.Equal.
221+
func (p WrappedHistogram) Equal(other WrappedHistogram) bool {
222+
return p.Histogram.Equal(&other.Histogram)
223+
}
224+
225+
// WrapHistogram wraps a Histogram into a WrappedHistogram.
226+
func WrapHistogram(h Histogram) WrappedHistogram {
227+
return WrappedHistogram{Histogram: h}
228+
}

‎pkg/cortexpb/timeseries.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ var (
3535
Labels: make([]LabelAdapter, 0, expectedLabels),
3636
Samples: make([]Sample, 0, expectedSamplesPerSeries),
3737
Exemplars: make([]Exemplar, 0, expectedExemplarsPerSeries),
38-
Histograms: make([]Histogram, 0, expectedHistogramsPerSeries),
38+
Histograms: make([]WrappedHistogram, 0, expectedHistogramsPerSeries),
3939
}
4040
},
4141
}
@@ -59,6 +59,7 @@ func (PreallocConfig) RegisterFlags(f *flag.FlagSet) {
5959
f.IntVar(&expectedTimeseries, "ingester-client.expected-timeseries", expectedTimeseries, "Expected number of timeseries per request, used for preallocations.")
6060
f.IntVar(&expectedLabels, "ingester-client.expected-labels", expectedLabels, "Expected number of labels per timeseries, used for preallocations.")
6161
f.IntVar(&expectedSamplesPerSeries, "ingester-client.expected-samples-per-series", expectedSamplesPerSeries, "Expected number of samples per timeseries, used for preallocations.")
62+
f.IntVar(&maxWrappedHistogramSizeBytes, "validation.max-native-histogram-size-bytes", maxWrappedHistogramSizeBytes, "Maximum size in bytes of a single native histogram in raw protobuf before unmarshalling. 0 to disable.")
6263
}
6364

6465
// PreallocWriteRequest is a WriteRequest which preallocs slices on Unmarshal.

‎pkg/cortexpb/timeseries_test.go‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,63 @@ func BenchmarkMarshallWriteRequest(b *testing.B) {
130130
})
131131
}
132132
}
133+
134+
func TestWrappedHistogram_Unmarshal_SizeLimit(t *testing.T) {
135+
t.Run("rejects oversized histogram", func(t *testing.T) {
136+
original := maxWrappedHistogramSizeBytes
137+
maxWrappedHistogramSizeBytes = 1024 // 1KB for test
138+
defer func() { maxWrappedHistogramSizeBytes = original }()
139+
140+
// Create a histogram that exceeds 1KB when marshalled
141+
h := Histogram{
142+
Schema: 3,
143+
NegativeDeltas: make([]int64, 600),
144+
PositiveDeltas: make([]int64, 600),
145+
}
146+
data, err := h.Marshal()
147+
require.NoError(t, err)
148+
require.Greater(t, len(data), 1024) // confirm it's over limit
149+
150+
p := &WrappedHistogram{}
151+
err = p.Unmarshal(data)
152+
require.Error(t, err)
153+
assert.Contains(t, err.Error(), "exceeds limit")
154+
})
155+
156+
t.Run("allows normal histogram", func(t *testing.T) {
157+
original := maxWrappedHistogramSizeBytes
158+
maxWrappedHistogramSizeBytes = 16 * 1024
159+
defer func() { maxWrappedHistogramSizeBytes = original }()
160+
161+
h := Histogram{
162+
Schema: 3,
163+
NegativeDeltas: make([]int64, 50),
164+
PositiveDeltas: make([]int64, 50),
165+
}
166+
data, err := h.Marshal()
167+
require.NoError(t, err)
168+
169+
p := &WrappedHistogram{}
170+
err = p.Unmarshal(data)
171+
require.NoError(t, err)
172+
assert.Equal(t, int32(3), p.Schema)
173+
assert.Len(t, p.NegativeDeltas, 50)
174+
})
175+
176+
t.Run("allows when limit disabled", func(t *testing.T) {
177+
original := maxWrappedHistogramSizeBytes
178+
maxWrappedHistogramSizeBytes = 0 // disabled
179+
defer func() { maxWrappedHistogramSizeBytes = original }()
180+
181+
h := Histogram{
182+
NegativeDeltas: make([]int64, 5000),
183+
PositiveDeltas: make([]int64, 5000),
184+
}
185+
data, err := h.Marshal()
186+
require.NoError(t, err)
187+
188+
p := &WrappedHistogram{}
189+
err = p.Unmarshal(data)
190+
require.NoError(t, err)
191+
})
192+
}

‎pkg/cortexpb/timeseriesv2.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ var (
2727
return &TimeSeriesV2{
2828
LabelsRefs: make([]uint32, 0, expectedLabels),
2929
Samples: make([]Sample, 0, expectedSamplesPerSeries),
30-
Histograms: make([]Histogram, 0, expectedHistogramsPerSeries),
30+
Histograms: make([]WrappedHistogram, 0, expectedHistogramsPerSeries),
3131
Exemplars: make([]ExemplarV2, 0, expectedExemplarsPerSeries),
3232
Metadata: MetadataV2{},
3333
}

‎pkg/cortexpb/timeseriesv2_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ func TestTimeseriesV2FromPool(t *testing.T) {
4444
ts.LabelsRefs = []uint32{1, 2}
4545
ts.Samples = []Sample{{Value: 1, TimestampMs: 2}}
4646
ts.Exemplars = []ExemplarV2{{LabelsRefs: []uint32{1, 2}, Value: 1, Timestamp: 2}}
47-
ts.Histograms = []Histogram{{}}
47+
ts.Histograms = []WrappedHistogram{{}}
4848
ts.CreatedTimestamp = 12345
4949
ts.Metadata = MetadataV2{Type: 1, HelpRef: 2, UnitRef: 3}
5050
ReuseTimeseriesV2(ts)

0 commit comments

Comments
 (0)