ronantakizawa/codereview-bench huggingface dataset:
Repository: prometheus/prometheus
File: tsdb/agent/db.go (Go)

Code before:
		a.pendingHistograms = append(a.pendingHistograms, record.RefHistogramSample{
			Ref: series.ref,
			T:   ct,
			H:   zeroHistogram,
		})
		a.histogramSeries = append(a.histogramSeries, series)
	case fh != nil:
		zeroFloatHistogram := &histogram.FloatHistogram{}
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  zeroFloatHistogram,
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

func (a *appender) AppendCTZeroSample(ref storage.SeriesRef, l labels.Labels, t, ct int64) (storage.SeriesRef, error) {
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		series, _ = a.getOrCreate(l)
	}

	series.Lock()
	defer series.Unlock()

	if t <= a.minValidTime(series.lastTs) {
		a.metrics.totalOutOfOrderSamples.Inc()
		return 0, storage.ErrOutOfOrderSample
	}

	// NOTE: always modify pendingSamples and sampleSeries together.
	a.pendingSamples = append(a.pendingSamples, record.RefSample{
		Ref: series.ref,
		T:   t,

Review comment (suggestion):
nit
```suggestion
		a.pendingHistograms = append(a.pendingHistograms, record.RefHistogramSample{
			Ref: series.ref,
			T:   ct,
			H:   &histogram.Histogram{},
		})
		a.histogramSeries = append(a.histogramSeries, series)
```

Code after:
		}
	}

	series.Lock()
	defer series.Unlock()

	if ct <= a.minValidTime(series.lastTs) {
		return 0, storage.ErrOutOfOrderCT
	}

	if ct > series.lastTs {
		series.lastTs = ct
	} else {
		// discard the sample if it's out of order.
		return 0, storage.ErrOutOfOrderCT
	}

	switch {
	case h != nil:
		zeroHistogram := &histogram.Histogram{}
		a.pendingHistograms = append(a.pendingHistograms, record.RefHistogramSample{
			Ref: series.ref,
			T:   ct,
			H:   zeroHistogram,
		})
		a.histogramSeries = append(a.histogramSeries, series)
	case fh != nil:
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  &histogram.FloatHistogram{},
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

func (a *appender) AppendCTZeroSample(ref storage.SeriesRef, l labels.Labels, t, ct int64) (storage.SeriesRef, error) {
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}
Repository: prometheus/prometheus
File: tsdb/agent/db.go (Go)

Code before:
	case fh != nil:
		zeroFloatHistogram := &histogram.FloatHistogram{}
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  zeroFloatHistogram,
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

func (a *appender) AppendCTZeroSample(ref storage.SeriesRef, l labels.Labels, t, ct int64) (storage.SeriesRef, error) {
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		series, _ = a.getOrCreate(l)
	}

	series.Lock()
	defer series.Unlock()

	if t <= a.minValidTime(series.lastTs) {
		a.metrics.totalOutOfOrderSamples.Inc()
		return 0, storage.ErrOutOfOrderSample
	}

	// NOTE: always modify pendingSamples and sampleSeries together.
	a.pendingSamples = append(a.pendingSamples, record.RefSample{
		Ref: series.ref,
		T:   t,
		V:   0,
	})
	a.sampleSeries = append(a.sampleSeries, series)

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeFloat).Inc()


Review comment (suggestion):
nit
```suggestion
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  &histogram.FloatHistogram{},
		})
```

Code after:
	if ct <= a.minValidTime(series.lastTs) {
		return 0, storage.ErrOutOfOrderCT
	}

	if ct > series.lastTs {
		series.lastTs = ct
	} else {
		// discard the sample if it's out of order.
		return 0, storage.ErrOutOfOrderCT
	}

	switch {
	case h != nil:
		zeroHistogram := &histogram.Histogram{}
		a.pendingHistograms = append(a.pendingHistograms, record.RefHistogramSample{
			Ref: series.ref,
			T:   ct,
			H:   zeroHistogram,
		})
		a.histogramSeries = append(a.histogramSeries, series)
	case fh != nil:
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  &histogram.FloatHistogram{},
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

func (a *appender) AppendCTZeroSample(ref storage.SeriesRef, l labels.Labels, t, ct int64) (storage.SeriesRef, error) {
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		newSeries, created := a.getOrCreate(l)
		if created {
Repository: prometheus/prometheus
File: tsdb/agent/db.go (Go)

Code before:
			FH:  zeroFloatHistogram,
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

func (a *appender) AppendCTZeroSample(ref storage.SeriesRef, l labels.Labels, t, ct int64) (storage.SeriesRef, error) {
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		series, _ = a.getOrCreate(l)
	}

	series.Lock()
	defer series.Unlock()

	if t <= a.minValidTime(series.lastTs) {
		a.metrics.totalOutOfOrderSamples.Inc()
		return 0, storage.ErrOutOfOrderSample
	}

	// NOTE: always modify pendingSamples and sampleSeries together.
	a.pendingSamples = append(a.pendingSamples, record.RefSample{
		Ref: series.ref,
		T:   t,
		V:   0,
	})
	a.sampleSeries = append(a.sampleSeries, series)

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeFloat).Inc()

	return storage.SeriesRef(series.ref), nil
}

// Commit submits the collected samples and purges the batch.
func (a *appender) Commit() error {

Review comment (suggestion):
Any reason to throw away the `created` boolean?

I believe we want to add the series to `a.pendingSeries` and increase the `activeSeries` counter if it's a new one. 

Code after:
		series.lastTs = ct
	} else {
		// discard the sample if it's out of order.
		return 0, storage.ErrOutOfOrderCT
	}

	switch {
	case h != nil:
		zeroHistogram := &histogram.Histogram{}
		a.pendingHistograms = append(a.pendingHistograms, record.RefHistogramSample{
			Ref: series.ref,
			T:   ct,
			H:   zeroHistogram,
		})
		a.histogramSeries = append(a.histogramSeries, series)
	case fh != nil:
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  &histogram.FloatHistogram{},
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

func (a *appender) AppendCTZeroSample(ref storage.SeriesRef, l labels.Labels, t, ct int64) (storage.SeriesRef, error) {
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		newSeries, created := a.getOrCreate(l)
		if created {
			a.pendingSeries = append(a.pendingSeries, record.RefSeries{
				Ref:    newSeries.ref,
				Labels: l,
			})
			a.metrics.numActiveSeries.Inc()
Repository: prometheus/prometheus
File: tsdb/agent/db.go (Go)

Code before:
	a.pendingSamples = append(a.pendingSamples, record.RefSample{
		Ref: series.ref,
		T:   t,
		V:   0,
	})
	a.sampleSeries = append(a.sampleSeries, series)

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeFloat).Inc()

	return storage.SeriesRef(series.ref), nil
}

// Commit submits the collected samples and purges the batch.
func (a *appender) Commit() error {
	if err := a.log(); err != nil {
		return err
	}

	a.clearData()
	a.appenderPool.Put(a)

	if a.writeNotified != nil {
		a.writeNotified.Notify()
	}
	return nil
}

// log logs all pending data to the WAL.
func (a *appender) log() error {
	a.mtx.RLock()
	defer a.mtx.RUnlock()

	var encoder record.Encoder
	buf := a.bufPool.Get().([]byte)
	defer func() {
		a.bufPool.Put(buf) //nolint:staticcheck
	}()

	if len(a.pendingSeries) > 0 {
		buf = encoder.Series(a.pendingSeries, buf)
		if err := a.wal.Log(buf); err != nil {
			return err
		}
		buf = buf[:0]
	}

	if len(a.pendingSamples) > 0 {
		buf = encoder.Samples(a.pendingSamples, buf)
		if err := a.wal.Log(buf); err != nil {
			return err
		}

Review comment (suggestion):
```suggestion
	if ct <= a.minValidTime(series.lastTs) {
		return 0, storage.ErrOutOfOrderSample
	}
```

Out of order CT is a very common scenario since it repeats for almost every scrape after the first one. I wouldn't increase the counter here

Code after:
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		newSeries, created := a.getOrCreate(l)
		if created {
			a.pendingSeries = append(a.pendingSeries, record.RefSeries{
				Ref:    newSeries.ref,
				Labels: l,
			})
			a.metrics.numActiveSeries.Inc()
		}

		series = newSeries
	}

	series.Lock()
	defer series.Unlock()

	if t <= a.minValidTime(series.lastTs) {
		a.metrics.totalOutOfOrderSamples.Inc()
		return 0, storage.ErrOutOfOrderSample
	}

	if ct > series.lastTs {
		series.lastTs = ct
	} else {
		// discard the sample if it's out of order.
		return 0, storage.ErrOutOfOrderCT
	}

	// NOTE: always modify pendingSamples and sampleSeries together.
	a.pendingSamples = append(a.pendingSamples, record.RefSample{
		Ref: series.ref,
		T:   ct,
		V:   0,
	})
	a.sampleSeries = append(a.sampleSeries, series)

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeFloat).Inc()

	return storage.SeriesRef(series.ref), nil
}

// Commit submits the collected samples and purges the batch.
func (a *appender) Commit() error {
	if err := a.log(); err != nil {
		return err
Repository: prometheus/prometheus
File: tsdb/agent/db.go (Go)

Code before:
		// Ensure no empty labels have gotten through.
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		var created bool
		series, created = a.getOrCreate(l)
		if created {
			a.pendingSeries = append(a.pendingSeries, record.RefSeries{
				Ref:    series.ref,
				Labels: l,
			})
			a.metrics.numActiveSeries.Inc()
		}
	}

	series.Lock()
	defer series.Unlock()

	if ct <= a.minValidTime(series.lastTs) {
		a.metrics.totalOutOfOrderSamples.Inc()
		return 0, storage.ErrOutOfOrderCT
	}

	switch {
	case h != nil:
		zeroHistogram := &histogram.Histogram{}
		a.pendingHistograms = append(a.pendingHistograms, record.RefHistogramSample{
			Ref: series.ref,
			T:   ct,
			H:   zeroHistogram,
		})
		a.histogramSeries = append(a.histogramSeries, series)
	case fh != nil:
		zeroFloatHistogram := &histogram.FloatHistogram{}
		a.pendingFloatHistograms = append(a.pendingFloatHistograms, record.RefFloatHistogramSample{
			Ref: series.ref,
			T:   ct,
			FH:  zeroFloatHistogram,
		})
		a.floatHistogramSeries = append(a.floatHistogramSeries, series)
	}

	a.metrics.totalAppendedSamples.WithLabelValues(sampleMetricTypeHistogram).Inc()
	return storage.SeriesRef(series.ref), nil
}

Review comment (suggestion):
```suggestion
```

Out of order CT is a very common scenario since it repeats for almost every scrape after the first one. I wouldn't increase the counter here

Code after:
			return 0, err
		}
	}
	if fh != nil {
		if err := fh.Validate(); err != nil {
			return 0, err
		}
	}
	if ct >= t {
		return 0, storage.ErrCTNewerThanSample
	}

	series := a.series.GetByID(chunks.HeadSeriesRef(ref))
	if series == nil {
		// Ensure no empty labels have gotten through.
		l = l.WithoutEmpty()
		if l.IsEmpty() {
			return 0, fmt.Errorf("empty labelset: %w", tsdb.ErrInvalidSample)
		}

		if lbl, dup := l.HasDuplicateLabelNames(); dup {
			return 0, fmt.Errorf(`label name "%s" is not unique: %w`, lbl, tsdb.ErrInvalidSample)
		}

		var created bool
		series, created = a.getOrCreate(l)
		if created {
			a.pendingSeries = append(a.pendingSeries, record.RefSeries{
				Ref:    series.ref,
				Labels: l,
			})
			a.metrics.numActiveSeries.Inc()
		}
	}

	series.Lock()
	defer series.Unlock()

	if ct <= a.minValidTime(series.lastTs) {
		return 0, storage.ErrOutOfOrderCT
	}

	if ct > series.lastTs {
		series.lastTs = ct
	} else {
		// discard the sample if it's out of order.
		return 0, storage.ErrOutOfOrderCT
	}

	switch {
	case h != nil:
Repository: prometheus/prometheus
File: tsdb/agent/db_test.go (Go)

Code before:

	_, err = app.AppendHistogramCTZeroSample(0, lset, 100, 100, tsdbutil.GenerateTestHistograms(1)[0], nil)
	require.Error(t, err)

	_, err = app.AppendHistogram(0, lset, 100, tsdbutil.GenerateTestHistograms(1)[0], nil)
	require.NoError(t, err)
	err = app.Commit()
	require.NoError(t, err)

	lbls = labelsForTest(t.Name(), 1)
	lset = labels.New(lbls[0]...)
	_, err = app.AppendCTZeroSample(0, lset, 100, 70)
	require.NoError(t, err)

	// not allow when CT is newer or equal to the sample timestamp
	_, err = app.AppendCTZeroSample(0, lset, 100, 100)
	require.Error(t, err)

	_, err = app.Append(0, lset, 100, 0)
	require.NoError(t, err)
	err = app.Commit()
	require.NoError(t, err)

	m := gatherFamily(t, reg, "prometheus_agent_samples_appended_total")
	require.Equal(t, float64(2), m.Metric[0].Counter.GetValue(), "agent wal mismatch of total appended samples")
	require.Equal(t, float64(2), m.Metric[1].Counter.GetValue(), "agent wal mismatch of total appended histograms")
}

func BenchmarkCreateSeries(b *testing.B) {
	s := createTestAgentDB(b, nil, DefaultOptions())
	defer s.Close()

	app := s.Appender(context.Background()).(*appender)
	lbls := make([]labels.Labels, b.N)

	for i, l := range labelsForTest("benchmark", b.N) {
		lbls[i] = labels.New(l...)
	}

	b.ResetTimer()

	for _, l := range lbls {
		app.getOrCreate(l)
	}
}


Review comment (bug):
urgh, it's so unfortunate that we need to check metrics to understand if things were appended or not :/ 

Checking metrics doesn't tell us what values/timestamps were appended, and therefore it doesn't catch the bugs that I've seen in the current code 😬 

Code after:

	type appendableSample struct {
		t            int64
		ct           int64
		v            float64
		lbls         labels.Labels
		h            *histogram.Histogram
		expectsError bool
	}

	testHistogram := tsdbutil.GenerateTestHistograms(1)[0]
	zeroHistogram := &histogram.Histogram{}

	lbls := labelsForTest(t.Name(), 1)
	defLbls := labels.New(lbls[0]...)

	testCases := []struct {
		name                string
		inputSamples        []appendableSample
		expectedSamples     []*walSample
		expectedSeriesCount int
	}{
		{
			name: "in order ct+normal sample/floatSamples",
			inputSamples: []appendableSample{
				{t: 100, ct: 1, v: 10, lbls: defLbls},
				{t: 101, ct: 1, v: 10, lbls: defLbls},
			},
			expectedSamples: []*walSample{
				{t: 1, f: 0, lbls: defLbls},
				{t: 100, f: 10, lbls: defLbls},
				{t: 101, f: 10, lbls: defLbls},
			},
		},
		{
			name: "CT+float && CT+histogram samples",
			inputSamples: []appendableSample{
				{
					t:    100,
					ct:   30,
					v:    20,
					lbls: defLbls,
				},
				{
					t:    300,
					ct:   230,
					h:    testHistogram,
					lbls: defLbls,
				},
			},
			expectedSamples: []*walSample{
Repository: prometheus/prometheus
File: model/textparse/interface_test.go (Go)

Code before:
		et, err := p.Next()
		if errors.Is(err, io.EOF) {
			break
		}
		require.NoError(t, err)

		var got parsedEntry
		var m []byte
		switch et {
		case EntryInvalid:
			t.Fatal("entry invalid not expected")
		case EntrySeries, EntryHistogram:
			if et == EntrySeries {
				m, got.t, got.v = p.Series()
				got.m = string(m)
			} else {
				m, got.t, got.shs, got.fhs = p.Histogram()
				got.m = string(m)
			}

			p.Metric(&got.lset)
			for e := (exemplar.Exemplar{}); p.Exemplar(&e); {
				got.es = append(got.es, e)
			}
			// Parser reuses int pointer.
			if ct := p.CreatedTimestamp(); ct != nil {
				got.ct = int64p(*ct)
			}
		case EntryType:
			m, got.typ = p.Type()
			got.m = string(m)

		case EntryHelp:
			m, h := p.Help()
			got.m = string(m)
			got.help = string(h)

		case EntryUnit:
			m, u := p.Unit()
			got.m = string(m)
			got.unit = string(u)

		case EntryComment:
			got.comment = string(p.Comment())
		}
		ret = append(ret, got)
	}
	return ret
}


Review comment (suggestion):
Note to reviewers: this reordering is done to trigger #15137. And also means the tests use the same order that scrape.go actually does things.

Code after:
		et, err := p.Next()
		if errors.Is(err, io.EOF) {
			break
		}
		require.NoError(t, err)

		var got parsedEntry
		var m []byte
		switch et {
		case EntryInvalid:
			t.Fatal("entry invalid not expected")
		case EntrySeries, EntryHistogram:
			if et == EntrySeries {
				m, got.t, got.v = p.Series()
				got.m = string(m)
			} else {
				m, got.t, got.shs, got.fhs = p.Histogram()
				got.m = string(m)
			}

			p.Metric(&got.lset)
			// Parser reuses int pointer.
			if ct := p.CreatedTimestamp(); ct != nil {
				got.ct = int64p(*ct)
			}
			for e := (exemplar.Exemplar{}); p.Exemplar(&e); {
				got.es = append(got.es, e)
			}
		case EntryType:
			m, got.typ = p.Type()
			got.m = string(m)

		case EntryHelp:
			m, h := p.Help()
			got.m = string(m)
			got.help = string(h)

		case EntryUnit:
			m, u := p.Unit()
			got.m = string(m)
			got.unit = string(u)

		case EntryComment:
			got.comment = string(p.Comment())
		}
		ret = append(ret, got)
	}
	return ret
}
Repository: prometheus/prometheus
File: discovery/kubernetes/endpoints.go (Go)

Code before:

				a := net.JoinHostPort(pe.pod.Status.PodIP, strconv.FormatUint(uint64(cport.ContainerPort), 10))
				ports := strconv.FormatUint(uint64(cport.ContainerPort), 10)

				isInit := i >= len(pe.pod.Spec.Containers)
				target := model.LabelSet{
					model.AddressLabel:            lv(a),
					podContainerNameLabel:         lv(c.Name),
					podContainerImageLabel:        lv(c.Image),
					podContainerPortNameLabel:     lv(cport.Name),
					podContainerPortNumberLabel:   lv(ports),
					podContainerPortProtocolLabel: lv(string(cport.Protocol)),
					podContainerIsInit:            lv(strconv.FormatBool(isInit)),
				}
				tg.Targets = append(tg.Targets, target.Merge(podLabels(pe.pod)))
			}
		}
	}

	return tg
}

var objKeyPool = sync.Pool{}

func generateObjKey(namespace, name string) (string, *strings.Builder) {
	var sb *strings.Builder

	b := objKeyPool.Get()
	if b == nil {
		sb = &strings.Builder{}
	} else {
		sb = b.(*strings.Builder)
	}

	sb.Reset()
	if namespace == "" {
		_, _ = sb.WriteString(name)
		return sb.String(), sb
	}

	_, _ = sb.WriteString(namespace)
	_, _ = sb.WriteRune('/')
	_, _ = sb.WriteString(name)
	return sb.String(), sb
}

func (e *Endpoints) resolvePodRef(ref *apiv1.ObjectReference) *apiv1.Pod {
	if ref == nil || ref.Kind != "Pod" {
		return nil
	}


Review comment (suggestion):
I'm afraid a builder would be an overkill here and we can do without its overhead, we just want to return `namespace/name` (endpoints are namespaced)
You can use `namespacedName` from `kubernetes.go`

Code after:
				target := model.LabelSet{
					model.AddressLabel:            lv(a),
					podContainerNameLabel:         lv(c.Name),
					podContainerImageLabel:        lv(c.Image),
					podContainerPortNameLabel:     lv(cport.Name),
					podContainerPortNumberLabel:   lv(ports),
					podContainerPortProtocolLabel: lv(string(cport.Protocol)),
					podContainerIsInit:            lv(strconv.FormatBool(isInit)),
				}
				tg.Targets = append(tg.Targets, target.Merge(podLabels(pe.pod)))
			}
		}
	}

	return tg
}

func (e *Endpoints) resolvePodRef(ref *apiv1.ObjectReference) *apiv1.Pod {
	if ref == nil || ref.Kind != "Pod" {
		return nil
	}

	obj, exists, err := e.podStore.GetByKey(namespacedName(ref.Namespace, ref.Name))
	if err != nil {
		e.logger.Error("resolving pod ref failed", "err", err)
		return nil
	}
	if !exists {
		return nil
	}
	return obj.(*apiv1.Pod)
}

func (e *Endpoints) addServiceLabels(ns, name string, tg *targetgroup.Group) {
	obj, exists, err := e.serviceStore.GetByKey(namespacedName(ns, name))
	if err != nil {
		e.logger.Error("retrieving service failed", "err", err)
		return
	}
	if !exists {
		return
	}
	svc := obj.(*apiv1.Service)

	tg.Labels = tg.Labels.Merge(serviceLabels(svc))
}

func addNodeLabels(tg model.LabelSet, nodeInf cache.SharedInformer, logger *slog.Logger, nodeName *string) model.LabelSet {
	if nodeName == nil {
		return tg
	}