Skip to content

Commit 4f11aac

Browse files
cursoragentClaude Sonnet 4.5
andcommitted
fix(baggage): Ensure deterministic ordering with sentry members first
The Baggage.String() method was using non-deterministic map iteration, making it impossible to guarantee that sentry- prefixed members would appear first in the serialized baggage string. This violated the W3C Baggage spec requirement that critical members should appear first to survive truncation when size limits are exceeded. This fix sorts baggage keys deterministically, placing all sentry- prefixed keys first (in alphabetical order), followed by other keys (also alphabetically). This ensures: 1. Sentry distributed tracing members always appear first 2. The ordering is consistent across all invocations 3. The test 'sentry members appear before third party members' no longer exhibits flaky behavior Co-Authored-By: Claude Sonnet 4.5 <noreply@example.com>
1 parent 2ebe6a5 commit 4f11aac

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

internal/otel/baggage/baggage.go

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"fmt"
2222
"net/url"
2323
"regexp"
24+
"sort"
2425
"strings"
2526
"unicode/utf8"
2627

@@ -591,9 +592,36 @@ func (b Baggage) Len() int {
591592
// String encodes Baggage into a string compliant with the W3C Baggage
592593
// specification. The returned string will be invalid if the Baggage contains
593594
// any invalid list-members.
595+
//
596+
// Members are sorted deterministically with sentry- prefixed keys appearing
597+
// first, followed by other keys in lexicographic order. This ensures that
598+
// sentry distributed tracing members take precedence when W3C Baggage size
599+
// limits cause truncation from the end.
594600
func (b Baggage) String() string {
601+
if len(b.list) == 0 {
602+
return ""
603+
}
604+
605+
// Collect keys and sort them: sentry- keys first, then others alphabetically
606+
keys := make([]string, 0, len(b.list))
607+
for k := range b.list {
608+
keys = append(keys, k)
609+
}
610+
sort.Slice(keys, func(i, j int) bool {
611+
isSentryI := strings.HasPrefix(keys[i], "sentry-")
612+
isSentryJ := strings.HasPrefix(keys[j], "sentry-")
613+
if isSentryI && !isSentryJ {
614+
return true
615+
}
616+
if !isSentryI && isSentryJ {
617+
return false
618+
}
619+
return keys[i] < keys[j]
620+
})
621+
595622
members := make([]string, 0, len(b.list))
596-
for k, v := range b.list {
623+
for _, k := range keys {
624+
v := b.list[k]
597625
members = append(members, Member{
598626
key: k,
599627
value: v.Value,

0 commit comments

Comments
 (0)