Skip to content

Calling SetBaggage and ToHeader concurrently on the same Span can terminate the process #44

Open

Description

@hehua01

Version

github.com/coze-dev/cozeloop-go v0.1.23

Problem

Calling SetBaggage and ToHeader concurrently on the same Span can
terminate the process with:

fatal error: concurrent map iteration and map write

Relevant code

internal/trace/span.go:

  • SetBaggageItem (line 844) acquires s.lock.Lock() before writing s.Baggage.
  • toHeaderBaggage (line 972) reads len(s.Baggage) and iterates over
    s.Baggage without acquiring the corresponding read lock.

Trigger

An asynchronous callback updates span baggage while another goroutine
calls ToHeader to propagate the trace context.

This concurrency pattern is present in our integration; a standalone
reproducer has not yet been prepared.

Expected behavior

Baggage updates and header serialization should be concurrency-safe,
or the API should explicitly document the concurrency restriction.

Suggested fix

Protect the entire read in toHeaderBaggage with the existing mutex:

s.lock.RLock()
defer s.lock.RUnlock()

Alternatively, serialize the snapshot returned by the lock-protected
GetBaggage method.

Suggested regression test

Concurrently call SetBaggage and ToHeader on the same Span and run
the test with go test -race.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions