Skip to content

storage: make AppenderV2.AppendExemplars mandatory, drop it from Append - #19455

Closed
krajorama wants to merge 4 commits into
mainfrom
krajo/appenderv2-mandatory-exemplars
Closed

krajorama wants to merge 4 commits into
mainfrom
krajo/appenderv2-mandatory-exemplars

Conversation

@krajorama

@krajorama krajorama commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

TL;DR; Exemplars are not associated with samples in a pull model on a conceptual level. When we scrape a sample at timestamp T, the exemplar scraped at the same time might have timestamp T-3h or whatever.

I'm testing if making this change makes AppenderV2 easier to adopt in RW1, RW2. See #19250, #19251, #19252 without this change.

Summary

AppenderV2.Append currently accepts exemplars inline via AppendV2Options.Exemplars, which means every implementation also has to carry the AppendPartialError plumbing needed to report per-exemplar failures out of a call whose primary job is appending one sample.

This moves exemplars to their own mandatory method on AppenderV2:

AppendExemplars(ref SeriesRef, ls labels.Labels, exemplars []exemplar.Exemplar) (SeriesRef, error)

mirroring how AppenderV1 already separates AppendExemplar from Append, but keeping it batched (a slice, not one exemplar at a time) so the scrape hot path doesn't regress to one extra interface call per exemplar.

Making it mandatory (rather than an optional capability interface with a runtime type-assertion) removes the need for that capability-check plumbing entirely — every AppenderV2 implementation must support it, same as V1's AppendExemplar.

Changes

  • storage/interface_append.go: add AppendExemplars to AppenderV2, drop Exemplars from AppendV2Options, retarget AppendPartialError's docs from Append to AppendExemplars.
  • tsdb/head_append_v2.go, tsdb/agent/db_append_v2.go: implement AppendExemplars, drop exemplar handling from Append.
  • storage/fanout.go: dispatch AppendExemplars to primary + secondaries (same pattern Append used for exemplar partial errors before).
  • scrape/scrape_append_v2.go + scrape/scrape.go: call AppendExemplars after a successful Append; split the old checkAddError's exemplar-partial-error branch into its own checkExemplarsAddError.
  • storage/remote/otlptranslator/prometheusremotewrite/{helper,histograms,number_data_points}.go: attach exemplars via AppendExemplars after Append instead of inline (including the histogram-bucket exemplar-distribution loop in helper.go).
  • storage/remote/write_otlp_handler.go: move the partial-error-hiding logic from the Append wrapper to a new AppendExemplars wrapper.
  • storage/remote/write.go: timestampTrackerV2 counts exemplars via AppendExemplars instead of opts.Exemplars.
  • cmd/prometheus/main.go: notReadyAppenderV2 gets an AppendExemplars stub.
  • Test/mock updates across util/teststorage, storage/fanout_test.go, tsdb/head_append_v2_test.go, tsdb/head_bench_test.go, tsdb/agent/db_append_v2_test.go, storage/remote/write_otlp_handler_test.go, storage/remote/otlptranslator/prometheusremotewrite/metrics_to_prw_test.go.

Test plan

  • go build ./... passes
  • go vet ./... clean (aside from pre-existing, unrelated Seek stdmethods warnings)
  • go test ./... passes across the whole module
NONE

sl.cache.updateRef(ce, ref)
}
if len(exemplars) > 0 {
_, exErr := app.AppendExemplars(ref, lset, exemplars)

@bwplotka bwplotka Aug 19, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was worried that this will get rid of benefits for OpenTelemetry Collector, but turns out on collector side the benefits were not really taken -- as is, it was still buffering exemplars in the transaction for the later build. So we should be fine, other than the pain of breaking change again -- and no optimization path forward.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks cc @dashpole

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we just never got very far on the migration. There was someone working on it, but I don't remember where it ended up. I'll prototype and see what impact this change would have on the (potential future) collector usage.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice timing to check how far we can win if we keep inlining instead

Early prototype by @dashpole

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, still working on the PoCs and benchmarks to isolate the impact of splitting exemplars out. AppenderV2 is considerably more efficient (around 50% in some cases) compared to appender v1, but a lot of that is grouped histogram buckets, etc. being more performant.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, so IF the AppendExemplar call always comes immediately after the Append call, we can optimize that case to make them have virtually the same performance. Otherwise, if exemplars are fully split from metric data, there is a 15-20% percent performance hit for having them separate and needing to match them up.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LMK if there are specific things you want me to check, or if that is enough for you to make your decision.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those numbers are great, thanks!

Ok, so IF the AppendExemplar call always comes immediately after the Append call, we can optimize that case to make them have virtually the same performance.

It's quite hacky to depend on this though.

@bwplotka bwplotka Sep 23, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Playing with the alternative: #19811

Generally it's more code lines, more API surface, but allows tight exemplars where we can.

@krajorama
krajorama force-pushed the krajo/appenderv2-mandatory-exemplars branch from 3b0566e to c8fbef3 Compare August 26, 2026 12:51
Exemplars were passed to AppenderV2.Append via AppendV2Options.Exemplars,
requiring every implementation to also carry the AppendPartialError
plumbing needed to report per-exemplar failures out of a call whose
primary purpose is appending one sample. Move exemplars to their own
mandatory AppendExemplars(ref, ls, exemplars) method on AppenderV2,
mirroring how AppenderV1 already separates AppendExemplar from Append.

This keeps the batching behaviour scrape relies on (one call per sample
carrying all of its exemplars, not one call per exemplar), while letting
callers that don't have a natural 1:1 sample/exemplars pairing (e.g. a
remote-write receiver) call it independently. Making it mandatory removes
the need for a separate optional capability interface and its associated
type-assertion/capability-check plumbing.

Signed-off-by: György Krajcsovits <[email protected]>
Rename now-unused opts parameters to _ in timestampTrackerV2.Append and
agent's appenderV2.Append (exemplars moved out to AppendExemplars), and
restructure a nested if into an early continue in teststorage's mock
per gocritic's nestingReduce suggestion.

Signed-off-by: György Krajcsovits <[email protected]>
Factor AppendExemplars into its own named ExemplarAppenderV2 interface,
embedded into AppenderV2, mirroring how AppenderV1's Appender interface
composes ExemplarAppender, HistogramAppender, MetadataUpdater, etc. as
separate named interfaces rather than inlining their methods directly.
AppendExemplars remains a mandatory part of AppenderV2 (embedding still
requires it); this is purely a naming/organization change.

Signed-off-by: György Krajcsovits <[email protected]>
@krajorama
krajorama force-pushed the krajo/appenderv2-mandatory-exemplars branch from c8fbef3 to 89ef560 Compare August 26, 2026 13:18
@krajorama
krajorama marked this pull request as ready for review August 26, 2026 14:58

@aknuds1 aknuds1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAICT, it looks mostly good. But please see my suggestions.

}

// AppendExemplars implements the mandatory AppenderV2.AppendExemplars capability.
// The series identified by ref MUST already exist (it MUST have been appended to

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// The series identified by ref MUST already exist (it MUST have been appended to
// The series identified by ref and/or ls MUST already exist (it MUST have been appended to

}
// Series references and chunk references are identical for agent mode.
s := a.series.GetByID(chunks.HeadSeriesRef(ref))
if s == nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to ExemplarAppenderV2.AppendExemplars, ref should be optional. If not supplied, ls should be used instead.

Suggested change
if s == nil {
if s == nil {
ls = ls.WithoutEmpty()
s = a.series.GetByHash(ls.Hash(), ls)
}
if s == nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's perhaps update the comment instead? We expect series to be present

_, err = app.AppendExemplars(ref, ls, []exemplar.Exemplar{e})
require.NoError(t, err, "should not reject valid exemplars")
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Corresponding regression test:

Suggested change
}
}
func TestDB_AppendExemplarsByLabels_AppendV2(t *testing.T) {
s := createTestAgentDB(t, nil, DefaultOptions())
defer s.Close()
ctx := t.Context()
ls := labels.FromStrings("a", "1", "empty", "")
canonicalLabels := ls.WithoutEmpty()
app := s.AppenderV2(ctx)
ref, err := app.Append(0, ls, 0, 1, 1, nil, nil, storage.AOptions{})
require.NoError(t, err)
require.NoError(t, app.Commit())
e := exemplar.Exemplar{Labels: labels.FromStrings("trace_id", "123"), Value: 1, Ts: 1, HasTs: true}
app = s.AppenderV2(ctx)
gotRef, err := app.AppendExemplars(0, ls, []exemplar.Exemplar{e})
require.NoError(t, err)
require.Equal(t, ref, gotRef)
require.NoError(t, app.Commit())
require.Equal(t, &e, s.series.GetLatestExemplar(chunks.HeadSeriesRef(ref)))
missingLabels := labels.FromStrings("missing", "series")
app = s.AppenderV2(ctx)
_, err = app.AppendExemplars(0, missingLabels, []exemplar.Exemplar{e})
require.EqualError(t, err, "unknown series ref when trying to add exemplars: 0")
require.Nil(t, s.series.GetByHash(missingLabels.Hash(), missingLabels))
require.NotNil(t, s.series.GetByHash(canonicalLabels.Hash(), canonicalLabels))
require.NoError(t, app.Rollback())
}

Comment thread tsdb/head_append_v2.go

s := a.head.series.getByID(chunks.HeadSeriesRef(ref))
if s == nil {
s = a.head.series.getByHash(ls.Hash(), ls)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AppendExemplars should canonicalize ls, same as Append does:

Suggested change
s = a.head.series.getByHash(ls.Hash(), ls)
ls = ls.WithoutEmpty()
s = a.head.series.getByHash(ls.Hash(), ls)


l := labels.FromStrings("trace_id", "123")

ls := labels.FromStrings("a", "b")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest including an empty label, to verify label canonicalization:

Suggested change
ls := labels.FromStrings("a", "b")
ls := labels.FromStrings("a", "b", "empty", "")

})
_, err = app.AppendExemplars(ref, ls, []exemplar.Exemplar{{Labels: l, HasTs: true, Ts: -1000, Value: 1}})
require.NoError(t, err)
require.NoError(t, app.Commit())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest also testing that calling app.AppendExemplars without ref works.

Suggested change
require.NoError(t, app.Commit())
require.NoError(t, app.Commit())
app = head.AppenderV2(ctx)
gotRef, err := app.AppendExemplars(0, ls, []exemplar.Exemplar{{Labels: l, HasTs: true, Ts: -999, Value: 2}})
require.NoError(t, err)
require.Equal(t, ref, gotRef)
require.NoError(t, app.Commit())

@bwplotka bwplotka left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

I am still wondering if we don't want to keep Exemplars on Appender option WHILE adding separate method (potentially optional, not even part of interface) for AppendExemplars for RW receive use. This would be:

  1. Cleaner going forward given all our inputs except RW sends sample with an exemplars 🤔
  2. Not break downstream (collector) and allow optimizations in future

Comment thread tsdb/head_append_v2.go
// The series identified by ref and/or ls MUST already exist (it MUST have been
// appended to via Append in the same or an earlier transaction).
func (a *headAppenderV2) AppendExemplars(ref storage.SeriesRef, ls labels.Labels, exemplars []exemplar.Exemplar) (storage.SeriesRef, error) {
if len(exemplars) == 0 || !a.head.opts.EnableExemplarStorage || a.head.opts.MaxExemplars.Load() <= 0 {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning 0, nil when exemplar storage is disabled or exemplars is empty wipes out the series ref for callers like fanout, and skips checking whether the series exists. Maybe validate the series and return storage.SeriesRef(s.ref), nil?

// via Append in the same or an earlier transaction).
func (a *appenderV2) AppendExemplars(ref storage.SeriesRef, _ labels.Labels, exemplars []exemplar.Exemplar) (storage.SeriesRef, error) {
if len(exemplars) == 0 {
return 0, nil

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: If exemplars is empty, returning 0, nil clobbers the caller's series ref. Should this return ref, nil instead?

Suggested change
return 0, nil
if len(exemplars) == 0 {
return ref, nil
}

}
// Series references and chunk references are identical for agent mode.
s := a.series.GetByID(chunks.HeadSeriesRef(ref))
if s == nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's perhaps update the comment instead? We expect series to be present

@bwplotka

bwplotka commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

Added an alternative #19455 (comment)

As of now we have a decision to make:
A) Add AppendExemplar as the only option (this PR).
B) Add AppendExemplar as a second option, on top of AppendOption.Exemplar -- only for RW receiving (#19811)

Pros of A

  • One way of appending exemplars, especially as we don't plan on improving the exemplar storage for now. Question is, will we want in future (the only reason for now would be compatibility).
    • Interestingly this might allow sharing Otel prometheusreceiver and prometheusremotewritereceiver appender code etc
  • Less code

Pros of B

  • Avoids breaking change to downstream (Otel, anyone else who upgraded already)
  • Allows clean optimizations for Otel Collector (that 15-20% perf number) - they don't leverage that now though.

I am happy to accept the (A) and make it simpler 🤔

@krajorama

Copy link
Copy Markdown
Member Author

With LLMs coding is kind of cheap, so I'm ok with option B. Still better than the current situation with both v1 and v2.

@bwplotka

Copy link
Copy Markdown
Member

Cool, let's do B then if we are less afraid of complexity now (looking on what we merge, that's kind of what we see)

@krajorama

Copy link
Copy Markdown
Member Author

Closing this in favor of #19811

@krajorama krajorama closed this Sep 28, 2026
@krajorama
krajorama removed this pull request from stack #19544 September 28, 2026 15:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants