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

Code before:
	seriesLabels := entry.ref.seriesLabels.Bytes(buf[:0])

	idx, ok := ce.index[string(seriesLabels)]
	if !ok {
		idx = entry.ref
		idx.oldest = ce.nextIndex
		ce.index[string(seriesLabels)] = idx
	} else {
		entry.ref = idx
		ce.exemplars[idx.newest].next = ce.nextIndex
	}
	idx.newest = ce.nextIndex

	entry.next = noExemplar
	ce.exemplars[ce.nextIndex] = *entry

	ce.nextIndex = (ce.nextIndex + 1) % len(ce.exemplars)
}

func (ce *CircularExemplarStorage) AddExemplar(l labels.Labels, e exemplar.Exemplar) error {
	var buf [1024]byte
	seriesLabels := l.Bytes(buf[:])

	// TODO(bwplotka): This lock can lock all scrapers, there might high contention on this on scale.
	// Optimize by moving the lock to be per series (& benchmark it).
	ce.lock.Lock()
	defer ce.lock.Unlock()

	if len(ce.exemplars) == 0 {
		return storage.ErrExemplarsDisabled
	}

	idx, ok := ce.index[string(seriesLabels)]
	err := ce.validateExemplar(idx, e, true)
	if err != nil {
		if errors.Is(err, storage.ErrDuplicateExemplar) {
			// Duplicate exemplar, noop.
			return nil
		}
		return err
	}

	if !ok {
		idx = &indexEntry{oldest: ce.nextIndex, seriesLabels: l}
		ce.index[string(seriesLabels)] = idx
	} else {
		ce.exemplars[idx.newest].next = ce.nextIndex
	}

	if prev := &ce.exemplars[ce.nextIndex]; prev.ref != nil {
		// There exists an exemplar already on this ce.nextIndex entry,

Review comment (suggestion):
maybe it's better to move the lock to the beginning instead, to avoid the `buf` allocation when not needed.

Code after:
	seriesLabels := entry.ref.seriesLabels.Bytes(buf[:0])

	idx, ok := ce.index[string(seriesLabels)]
	if !ok {
		idx = entry.ref
		idx.oldest = ce.nextIndex
		ce.index[string(seriesLabels)] = idx
	} else {
		entry.ref = idx
		ce.exemplars[idx.newest].next = ce.nextIndex
	}
	idx.newest = ce.nextIndex

	entry.next = noExemplar
	ce.exemplars[ce.nextIndex] = *entry

	ce.nextIndex = (ce.nextIndex + 1) % len(ce.exemplars)
}

func (ce *CircularExemplarStorage) AddExemplar(l labels.Labels, e exemplar.Exemplar) error {
	// TODO(bwplotka): This lock can lock all scrapers, there might high contention on this on scale.
	// Optimize by moving the lock to be per series (& benchmark it).
	ce.lock.Lock()
	defer ce.lock.Unlock()

	if len(ce.exemplars) == 0 {
		return storage.ErrExemplarsDisabled
	}

	var buf [1024]byte
	seriesLabels := l.Bytes(buf[:])

	idx, ok := ce.index[string(seriesLabels)]
	err := ce.validateExemplar(idx, e, true)
	if err != nil {
		if errors.Is(err, storage.ErrDuplicateExemplar) {
			// Duplicate exemplar, noop.
			return nil
		}
		return err
	}

	if !ok {
		idx = &indexEntry{oldest: ce.nextIndex, seriesLabels: l}
		ce.index[string(seriesLabels)] = idx
	} else {
		ce.exemplars[idx.newest].next = ce.nextIndex
	}

	if prev := &ce.exemplars[ce.nextIndex]; prev.ref != nil {
		// There exists an exemplar already on this ce.nextIndex entry,
Repository: prometheus/prometheus
File: util/annotations/annotations.go (Go)

Code before:
		PositionRange: pos,
		Err:           fmt.Errorf("%w %q", PossibleNonCounterInfo, metricName),
	}
}

// NewHistogramQuantileForcedMonotonicityInfo is used when the input (classic histograms) to
// histogram_quantile needs to be forced to be monotonic.
func NewHistogramQuantileForcedMonotonicityInfo(metricName string, pos posrange.PositionRange) error {
	return annoErr{
		PositionRange: pos,
		Err:           fmt.Errorf("%w %q", HistogramQuantileForcedMonotonicityInfo, metricName),
	}
}

// NewIncompatibleTypesInBinOpInfo is used if binary operators act on a
// combination of types that doesn't work and therefore returns no result.
func NewIncompatibleTypesInBinOpInfo(lhsType, operator, rhsType string, pos posrange.PositionRange) error {
	return annoErr{
		PositionRange: pos,
		Err:           fmt.Errorf("%w %q: %s %s %s", IncompatibleTypesInBinOpInfo, operator, lhsType, operator, rhsType),
	}
}

// NewMixedFloatsHistogramsAggInfo is used when the queried series includes both
// float samples and histogram samples in an aggregation.
func NewMixedFloatsHistogramsAggInfo(aggregation string, pos posrange.PositionRange) error {
	return annoErr{
		PositionRange: pos,
		Err:           fmt.Errorf("%w %s aggregation", MixedFloatsHistogramsInfo, aggregation),
	}
}


Review comment (suggestion):
I don't think this is correctly named and documented. This annotation is also returned if you try to only aggregate histograms (i.e. no floats, so no mix) with an aggregation operator that doesn't like histograms.

How about this:

```suggestion
// NewHistogramIgnoredInAggregationInfo is used when a histogram is ignored by
// an aggregation operator that cannot handle histograms.
func NewHistogramIgnoredInAggregationInfo(aggregation string, pos posrange.PositionRange) error {
```

Code after:
		PositionRange: pos,
		Err:           fmt.Errorf("%w %q", PossibleNonCounterInfo, metricName),
	}
}

// NewHistogramQuantileForcedMonotonicityInfo is used when the input (classic histograms) to
// histogram_quantile needs to be forced to be monotonic.
func NewHistogramQuantileForcedMonotonicityInfo(metricName string, pos posrange.PositionRange) error {
	return annoErr{
		PositionRange: pos,
		Err:           fmt.Errorf("%w %q", HistogramQuantileForcedMonotonicityInfo, metricName),
	}
}

// NewIncompatibleTypesInBinOpInfo is used if binary operators act on a
// combination of types that doesn't work and therefore returns no result.
func NewIncompatibleTypesInBinOpInfo(lhsType, operator, rhsType string, pos posrange.PositionRange) error {
	return annoErr{
		PositionRange: pos,
		Err:           fmt.Errorf("%w %q: %s %s %s", IncompatibleTypesInBinOpInfo, operator, lhsType, operator, rhsType),
	}
}

// NewHistogramIgnoredInAggregationInfo is used when a histogram is ignored by
// an aggregation operator that cannot handle histograms.
func NewHistogramIgnoredInAggregationInfo(aggregation string, pos posrange.PositionRange) error {
	return annoErr{
		PositionRange: pos,
		Err:           fmt.Errorf("%w %s aggregation", HistogramIgnoredInAggregationInfo, aggregation),
	}
}
Repository: prometheus/prometheus
File: scrape/manager_test.go (Go)

Code before:
				model.JobLabel:            "job",
				model.ScrapeIntervalLabel: "1s",
				model.ScrapeTimeoutLabel:  "1s",
			}),
			resOrig: labels.FromMap(map[string]string{
				model.AddressLabel:        "1.2.3.4:443",
				model.SchemeLabel:         "https",
				model.MetricsPathLabel:    "/metrics",
				model.JobLabel:            "job",
				model.ScrapeIntervalLabel: "1s",
				model.ScrapeTimeoutLabel:  "1s",
			}),
		},
	}
	for _, c := range cases {
		in := maps.Clone(c.in)
		lb := labels.NewBuilder(labels.EmptyLabels())
		res, err := PopulateLabels(lb, c.cfg, c.in, nil)
		if c.err != "" {
			require.EqualError(t, err, c.err)
		} else {
			require.NoError(t, err)
		}
		require.Equal(t, c.in, in)
		testutil.RequireEqual(t, c.res, res)
		if err == nil {
			PopulateDiscoveredLabels(lb, c.cfg, c.in, nil)
			testutil.RequireEqual(t, c.resOrig, lb.Labels())
		}
	}
}

func loadConfiguration(t testing.TB, c string) *config.Config {
	t.Helper()

	cfg := &config.Config{}
	err := yaml.UnmarshalStrict([]byte(c), cfg)
	require.NoError(t, err, "Unable to load YAML config.")

	return cfg
}

func noopLoop() loop {
	return &testLoop{
		startFunc: func(interval, timeout time.Duration, errc chan<- error) {},
		stopFunc:  func() {},
	}
}

func TestManagerApplyConfig(t *testing.T) {
	// Valid initial configuration.

Review comment (refactor):
I think we should rely on `c.err` for this, maybe move this just below `require.NoError(t, err)` (line 460)?

Code after:
				model.JobLabel:            "job",
				model.ScrapeIntervalLabel: "1s",
				model.ScrapeTimeoutLabel:  "1s",
			}),
			resOrig: labels.FromMap(map[string]string{
				model.AddressLabel:        "1.2.3.4:443",
				model.SchemeLabel:         "https",
				model.MetricsPathLabel:    "/metrics",
				model.JobLabel:            "job",
				model.ScrapeIntervalLabel: "1s",
				model.ScrapeTimeoutLabel:  "1s",
			}),
		},
	}
	for _, c := range cases {
		in := maps.Clone(c.in)
		lb := labels.NewBuilder(labels.EmptyLabels())
		res, err := PopulateLabels(lb, c.cfg, c.in, nil)
		if c.err != "" {
			require.EqualError(t, err, c.err)
		} else {
			require.NoError(t, err)
			testutil.RequireEqual(t, c.res, res)
			PopulateDiscoveredLabels(lb, c.cfg, c.in, nil)
			testutil.RequireEqual(t, c.resOrig, lb.Labels())
		}
		require.Equal(t, c.in, in) // Check this wasn't altered by PopulateLabels().
	}
}

func loadConfiguration(t testing.TB, c string) *config.Config {
	t.Helper()

	cfg := &config.Config{}
	err := yaml.UnmarshalStrict([]byte(c), cfg)
	require.NoError(t, err, "Unable to load YAML config.")

	return cfg
}

func noopLoop() loop {
	return &testLoop{
		startFunc: func(interval, timeout time.Duration, errc chan<- error) {},
		stopFunc:  func() {},
	}
}

func TestManagerApplyConfig(t *testing.T) {
	// Valid initial configuration.
	cfgText1 := `
scrape_configs:
Repository: prometheus/prometheus
File: storage/remote/dial_context.go (Go)

Code before:
	dialContext config.DialContextFunc
	resolver    hostResolver
}

func newDialContextWithRandomConnections() *dialContextWithRandomConnections {
	return &dialContextWithRandomConnections{
		dialContext: http.DefaultTransport.(*http.Transport).DialContext,
		resolver:    net.DefaultResolver,
	}
}

func (dc *dialContextWithRandomConnections) dialContextFn() config.DialContextFunc {
	return func(ctx context.Context, network, addr string) (net.Conn, error) {
		host, port, err := net.SplitHostPort(addr)
		if err != nil {
			return dc.dialContext(ctx, network, addr)
		}

		addrs, err := dc.resolver.LookupHost(ctx, host)
		if err != nil {
			return dc.dialContext(ctx, network, addr)
		}

		// We deliberately create a connection to a randomly selected IP returned by the lookup.
		// This way we prevent that in case of a certain number of concurrent remote-write requests
		// all requests are sent to the same IP.
		randomAddr := net.JoinHostPort(addrs[rand.Intn(len(addrs))], port)
		return dc.dialContext(ctx, network, randomAddr)
	}
}


Review comment (suggestion):
I think this commentary belongs either in the commit description or in the documentation of the opt-in option you are adding.  Here is too buried to be useful.

Code after:
}

// newDialContextWithRoundRobinDNS creates a new dialContextWithRoundRobinDNS.
// We discourage creating new instances of struct dialContextWithRoundRobinDNS by explicitly setting its members,
// except for testing purposes, and recommend using newDialContextWithRoundRobinDNS.
func newDialContextWithRoundRobinDNS() *dialContextWithRoundRobinDNS {
	return &dialContextWithRoundRobinDNS{
		dialContext: http.DefaultTransport.(*http.Transport).DialContext,
		resolver:    net.DefaultResolver,
		rand:        rand.New(rand.NewSource(time.Now().Unix())),
	}
}

func (dc *dialContextWithRoundRobinDNS) dialContextFn() config.DialContextFunc {
	return func(ctx context.Context, network, addr string) (net.Conn, error) {
		host, port, err := net.SplitHostPort(addr)
		if err != nil {
			return dc.dialContext(ctx, network, addr)
		}

		addrs, err := dc.resolver.LookupHost(ctx, host)
		if err != nil || len(addrs) == 0 {
			return dc.dialContext(ctx, network, addr)
		}

		randomAddr := net.JoinHostPort(addrs[dc.rand.Intn(len(addrs))], port)
		return dc.dialContext(ctx, network, randomAddr)
	}
}
Repository: prometheus/prometheus
File: web/ui/mantine-ui/src/promql/utils.ts (TypeScript)

Code before:
    return true;
  }

  // TODO: Only works for 1 vararg, but PromQL only has functions with either 1 (not 2, 3, ...) or unlimited (-1) varargs in practice, so this is fine for now.
  return node.args.length < node.func.argTypes.length;
};

export const canRemoveVarArg = (node: Call): boolean => {
  return (
    node.func.variadic !== 0 && node.args.length >= node.func.argTypes.length
  );
};

export const humanizedValueType: Record<valueType, string> = {
  [valueType.none]: "none",
  [valueType.string]: "string",
  [valueType.scalar]: "number (scalar)",
  [valueType.vector]: "instant vector",
  [valueType.matrix]: "range vector",
};

const metricNameRe = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
const labelNameCharsetRe = /^[a-zA-Z_][a-zA-Z0-9_]*$/;

export const metricContainsExtendedCharset = (str: string) => {
  return !metricNameRe.test(str);
};

export const labelNameContainsExtendedCharset = (str: string) => {
  return !labelNameCharsetRe.test(str);
};

export const escapeString = (str: string) => {
  return str.replace(/([\\"])/g, "\\$1");
};

export const maybeQuoteLabelName = (str: string) => {
  return labelNameContainsExtendedCharset(str) ? `"${escapeString(str)}"` : str;
};


Review comment (suggestion):
(I opted to add an empty string comparison here rather than to extend the regex, just because I thought that was even clearer and who knows, maybe it's even slightly faster for the very common case of empty metric names)

Code after:
    return true;
  }

  // TODO: Only works for 1 vararg, but PromQL only has functions with either 1 (not 2, 3, ...) or unlimited (-1) varargs in practice, so this is fine for now.
  return node.args.length < node.func.argTypes.length;
};

export const canRemoveVarArg = (node: Call): boolean => {
  return (
    node.func.variadic !== 0 && node.args.length >= node.func.argTypes.length
  );
};

export const humanizedValueType: Record<valueType, string> = {
  [valueType.none]: "none",
  [valueType.string]: "string",
  [valueType.scalar]: "number (scalar)",
  [valueType.vector]: "instant vector",
  [valueType.matrix]: "range vector",
};

const metricNameRe = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/;
const labelNameCharsetRe = /^[a-zA-Z_][a-zA-Z0-9_]*$/;

export const metricContainsExtendedCharset = (str: string) => {
  return str !== "" && !metricNameRe.test(str);
};

export const labelNameContainsExtendedCharset = (str: string) => {
  return !labelNameCharsetRe.test(str);
};

export const escapeString = (str: string) => {
  return str.replace(/([\\"])/g, "\\$1");
};

export const maybeQuoteLabelName = (str: string) => {
  return labelNameContainsExtendedCharset(str) ? `"${escapeString(str)}"` : str;
};
Repository: prometheus/prometheus
File: util/convertnhcb/convertnhcb.go (Go)

Code before:
	if count < 0 {
		h.err = fmt.Errorf("%w: count=%g", errNegativeCount, count)
		return h.err
	}
	h.count = count
	h.hasCount = true
	return nil
}

func (h *TempHistogram) SetSum(sum float64) error {
	if h.err != nil {
		return h.err
	}
	h.sum = sum
	return nil
}

func (h TempHistogram) Convert() (*histogram.Histogram, *histogram.FloatHistogram, error) {
	if h.err != nil {
		return nil, nil, h.err
	}

	if !h.hasCount && len(h.buckets) > 0 {
		// No count, so set count to the highest known bucket's count.
		h.count = h.buckets[len(h.buckets)-1].count
	}

	if len(h.buckets) == 0 || h.buckets[len(h.buckets)-1].le != math.Inf(1) {
		// No +Inf bucket.
		// Let the last bucket be +Inf with the overall count.
		h.buckets = append(h.buckets, tempHistogramBucket{le: math.Inf(1), count: h.count})
	}

	for _, b := range h.buckets {
		intCount := int64(math.Round(b.count))
		if b.count != float64(intCount) {
			return h.convertToFloatHistogram()
		}
	}

	intCount := uint64(math.Round(h.count))
	if h.count != float64(intCount) {
		return h.convertToFloatHistogram()
	}
	return h.convertToIntegerHistogram(intCount)
}

func (h TempHistogram) convertToIntegerHistogram(count uint64) (*histogram.Histogram, *histogram.FloatHistogram, error) {
	rh := &histogram.Histogram{
		Schema:          histogram.CustomBucketsSchema,
		Count:           count,

Review comment (suggestion):
Should `h.hasCount` be set to `true` here? This was previously done on L154 so wondering if it's necessary here as well.

Code after:
	if count < 0 {
		h.err = fmt.Errorf("%w: count=%g", errNegativeCount, count)
		return h.err
	}
	h.count = count
	h.hasCount = true
	return nil
}

func (h *TempHistogram) SetSum(sum float64) error {
	if h.err != nil {
		return h.err
	}
	h.sum = sum
	return nil
}

func (h TempHistogram) Convert() (*histogram.Histogram, *histogram.FloatHistogram, error) {
	if h.err != nil {
		return nil, nil, h.err
	}

	if !h.hasCount && len(h.buckets) > 0 {
		// No count, so set count to the highest known bucket's count.
		h.count = h.buckets[len(h.buckets)-1].count
		h.hasCount = true
	}

	if len(h.buckets) == 0 || h.buckets[len(h.buckets)-1].le != math.Inf(1) {
		// No +Inf bucket.
		// Let the last bucket be +Inf with the overall count.
		h.buckets = append(h.buckets, tempHistogramBucket{le: math.Inf(1), count: h.count})
	}

	for _, b := range h.buckets {
		intCount := int64(math.Round(b.count))
		if b.count != float64(intCount) {
			return h.convertToFloatHistogram()
		}
	}

	intCount := uint64(math.Round(h.count))
	if h.count != float64(intCount) {
		return h.convertToFloatHistogram()
	}
	return h.convertToIntegerHistogram(intCount)
}

func (h TempHistogram) convertToIntegerHistogram(count uint64) (*histogram.Histogram, *histogram.FloatHistogram, error) {
	rh := &histogram.Histogram{
		Schema:          histogram.CustomBucketsSchema,
Repository: prometheus/prometheus
File: tsdb/index/index.go (Go)

Code before:
		return err
	}

	sf, err := fileutil.OpenMmapFile(w.f.name)
	if err != nil {
		return err
	}
	w.symbolFile = sf
	hash := crc32.Checksum(w.symbolFile.Bytes()[w.toc.Symbols+4:hashPos], castagnoliTable)
	w.buf1.Reset()
	w.buf1.PutBE32(hash)
	if err := w.writeAt(w.buf1.Get(), hashPos); err != nil {
		return err
	}

	// Load in the symbol table efficiently for the rest of the index writing.
	w.symbols, err = NewSymbols(realByteSlice(w.symbolFile.Bytes()), FormatV2, int(w.toc.Symbols))
	if err != nil {
		return fmt.Errorf("read symbols: %w", err)
	}
	return nil
}

func (w *Writer) writeLabelIndices() error {
	if err := w.fPO.Flush(); err != nil {
		return err
	}

	// Find all the label values in the tmp posting offset table.
	f, err := fileutil.OpenMmapFile(w.fPO.name)
	if err != nil {
		return err
	}
	defer f.Close()

	d := encoding.NewDecbufRaw(realByteSlice(f.Bytes()), int(w.fPO.pos))
	cnt := w.cntPO
	current := []byte{}
	values := []uint32{}
	for d.Err() == nil && cnt > 0 {
		cnt--
		d.Uvarint()                           // Keycount.
		name := d.UvarintBytes()              // Label name.
		value := yoloString(d.UvarintBytes()) // Label value.
		d.Uvarint64()                         // Offset.
		if len(name) == 0 {
			continue // All index is ignored.
		}

		if !bytes.Equal(name, current) && len(values) > 0 {
			// We've reached a new label name.

Review comment (performance):
@aknuds1 asked about this change.  The reason is that we need to allocate a copy when adding the name to the cache (on line 629), but we don't want to allocate if the entry is already there.
This behaviour is what Go does when presented with a `[]byte` converted to `string()` as a map key.

Code after:
		return fmt.Errorf("read symbols: %w", err)
	}
	return nil
}

func (w *Writer) writeLabelIndices() error {
	if err := w.fPO.Flush(); err != nil {
		return err
	}

	// Find all the label values in the tmp posting offset table.
	f, err := fileutil.OpenMmapFile(w.fPO.name)
	if err != nil {
		return err
	}
	defer f.Close()

	d := encoding.NewDecbufRaw(realByteSlice(f.Bytes()), int(w.fPO.pos))
	cnt := w.cntPO
	current := []byte{}
	values := []uint32{}
	for d.Err() == nil && cnt > 0 {
		cnt--
		d.Uvarint()               // Keycount.
		name := d.UvarintBytes()  // Label name.
		value := d.UvarintBytes() // Label value.
		d.Uvarint64()             // Offset.
		if len(name) == 0 {
			continue // All index is ignored.
		}

		if !bytes.Equal(name, current) && len(values) > 0 {
			// We've reached a new label name.
			if err := w.writeLabelIndex(string(current), values); err != nil {
				return err
			}
			values = values[:0]
		}
		current = name
		sid, ok := w.symbolCache[string(value)]
		if !ok {
			return fmt.Errorf("symbol entry for %q does not exist", string(value))
		}
		values = append(values, sid)
	}
	if d.Err() != nil {
		return d.Err()
	}

	// Handle the last label.
	if len(values) > 0 {
Repository: prometheus/prometheus
File: promql/functions.go (Go)

Code before:
		for _, sample := range floats[1:] {
			current := sample.F
			if current < prev {
				resets++
			}
			prev = current
		}
	}

	if len(histograms) > 1 {
		prev := histograms[0].H
		for _, sample := range histograms[1:] {
			current := sample.H
			if current.DetectReset(prev) {
				resets++
			}
			prev = current
		}
	}

	return append(enh.Out, Sample{F: float64(resets)}), nil
}

// mergeSeries merges the floats and the histograms in a series
// into a slice of Sample sorted by their timestamp.
// it assumes that the floats and histograms are sorted by their timestamp.
func mergeSeries(series Series) []*Sample {
	floats := series.Floats
	histograms := series.Histograms
	samples := make([]*Sample, 0, len(floats)+len(histograms))

	// i for iterating through floats and j for iterating through histograms
	i, j := 0, 0
	for i < len(floats) && j < len(histograms) {
		if floats[i].T < histograms[j].T {
			samples = append(samples, &Sample{
				F: floats[i].F,
			})
			i++
		} else {
			samples = append(samples, &Sample{
				H: histograms[j].H,
			})
			j++
		}
	}
	// Append the remaining samples
	for i < len(floats) {
		samples = append(samples, &Sample{
			F: floats[i].F,
		})

Review comment (suggestion):
```suggestion
// It assumes that the floats and histograms are sorted by their timestamp.
```

Code after:
		for _, sample := range floats[1:] {
			current := sample.F
			if current < prev {
				resets++
			}
			prev = current
		}
	}

	if len(histograms) > 1 {
		prev := histograms[0].H
		for _, sample := range histograms[1:] {
			current := sample.H
			if current.DetectReset(prev) {
				resets++
			}
			prev = current
		}
	}

	return append(enh.Out, Sample{F: float64(resets)}), nil
}

// === changes(Matrix parser.ValueTypeMatrix) (Vector, Annotations) ===
func funcChanges(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) (Vector, annotations.Annotations) {
	floats := vals[0].(Matrix)[0].Floats
	histograms := vals[0].(Matrix)[0].Histograms
	changes := 0
	if len(floats) == 0 && len(histograms) == 0 {
		return enh.Out, nil
	}

	var prevSample, curSample Sample
	for iFloat, iHistogram := 0, 0; iFloat < len(floats) || iHistogram < len(histograms); {
		switch {
		// Process a float sample if no histogram sample remains or its timestamp is earlier.
		// Process a histogram sample if no float sample remains or its timestamp is earlier.
		case iHistogram >= len(histograms) || iFloat < len(floats) && floats[iFloat].T < histograms[iHistogram].T:
			{
				curSample.F = floats[iFloat].F
				curSample.H = nil
				iFloat++
			}
		case iFloat >= len(floats) || iHistogram < len(histograms) && floats[iFloat].T > histograms[iHistogram].T:
			{
				curSample.H = histograms[iHistogram].H
				iHistogram++
			}
		}
		// Skip the comparison for the first sample, just initialize prevSample.
		if iFloat+iHistogram == 1 {