From beb33bd9cbb1c45b31ca77a9d3bd6a0d7a002fcc Mon Sep 17 00:00:00 2001 From: SungJin1212 Date: Wed, 25 Mar 2026 08:30:24 +0900 Subject: [PATCH] Optimize ts v2 pool Signed-off-by: SungJin1212 --- pkg/cortexpb/timeseriesv2.go | 9 ++++----- pkg/cortexpb/timeseriesv2_test.go | 32 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/pkg/cortexpb/timeseriesv2.go b/pkg/cortexpb/timeseriesv2.go index 291ac32789e..10050315edf 100644 --- a/pkg/cortexpb/timeseriesv2.go +++ b/pkg/cortexpb/timeseriesv2.go @@ -77,6 +77,10 @@ func ReuseWriteRequestV2(req *PreallocWriteRequestV2) { req.data = nil } req.Source = 0 + + for i := range req.Symbols { + req.Symbols[i] = "" + } req.Symbols = req.Symbols[:0] if req.Timeseries != nil { ReuseSliceV2(req.Timeseries) @@ -121,11 +125,6 @@ func ReuseTimeseriesV2(ts *TimeSeriesV2) { ts.Metadata.UnitRef = 0 ts.Metadata.HelpRef = 0 - // clear exemplar label refs - for i := range ts.Exemplars { - ts.Exemplars[i].LabelsRefs = ts.Exemplars[i].LabelsRefs[:0] - } - for i := range ts.Histograms { ts.Histograms[i].Reset() } diff --git a/pkg/cortexpb/timeseriesv2_test.go b/pkg/cortexpb/timeseriesv2_test.go index 270a8597111..1ddc96631ab 100644 --- a/pkg/cortexpb/timeseriesv2_test.go +++ b/pkg/cortexpb/timeseriesv2_test.go @@ -52,6 +52,38 @@ func TestTimeseriesV2FromPool(t *testing.T) { }) } +func TestReuseWriteRequestV2(t *testing.T) { + req := PreallocWriteRequestV2FromPool() + + // Populate req with some data. + req.Source = RULE + req.Symbols = append(req.Symbols, "", "__name__", "test") + + tsSlice := PreallocTimeseriesV2SliceFromPool() + tsSlice = append(tsSlice, PreallocTimeseriesV2{TimeSeriesV2: TimeseriesV2FromPool()}) + req.Timeseries = tsSlice + + // Put the request back into the pool + ReuseWriteRequestV2(req) + + // Retrieve it from the pool again + reused := PreallocWriteRequestV2FromPool() + + // Source is reset to default + assert.Equal(t, API, reused.Source) + // The symbol length is properly reset to 0. + assert.Len(t, reused.Symbols, 0) + // Timeseries slice is nil + assert.Nil(t, reused.Timeseries) + + // The underlying array's string pointers are cleared to "" to prevent memory leak. + if cap(reused.Symbols) > 0 { + underlyingArray := reused.Symbols[:cap(reused.Symbols)] + assert.Equal(t, "", underlyingArray[0]) + assert.Equal(t, "", underlyingArray[1]) + } +} + func BenchmarkMarshallWriteRequestV2(b *testing.B) { ts := PreallocTimeseriesV2SliceFromPool()