Skip to content

Commit

Permalink
trace: fix span leak in batchSpanProcessor
Browse files Browse the repository at this point in the history
  • Loading branch information
korniltsev committed Jun 18, 2024
1 parent 478f85b commit 223a389
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions sdk/trace/batch_span_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ func (bsp *batchSpanProcessor) exportSpans(ctx context.Context) error {
//
// It is up to the exporter to implement any type of retry logic if a batch is failing
// to be exported, since it is specific to the protocol and backend being sent to.
clear(bsp.batch)
bsp.batch = bsp.batch[:0]

if err != nil {
Expand Down
30 changes: 30 additions & 0 deletions sdk/trace/batch_span_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import (
"errors"
"fmt"
"os"
"reflect"
"sync"
"testing"
"time"
"unsafe"

ottest "go.opentelemetry.io/otel/sdk/internal/internaltest"

Expand Down Expand Up @@ -627,6 +629,34 @@ func TestBatchSpanProcessorConcurrentSafe(t *testing.T) {
wg.Wait()
}

func TestBatchSpanLeak(t *testing.T) {
ctx := context.Background()

getBatch := func(bsp sdktrace.SpanProcessor) []sdktrace.ReadOnlySpan {
batchField := reflect.ValueOf(bsp).Elem().FieldByName("batch")
require.True(t, batchField.IsValid())
return unsafe.Slice((*sdktrace.ReadOnlySpan)(batchField.UnsafePointer()), batchField.Cap())[:batchField.Len()]
}
bsp := sdktrace.NewBatchSpanProcessor(tracetest.NewInMemoryExporter(), []sdktrace.BatchSpanProcessorOption{}...)
tp := sdktrace.NewTracerProvider(
sdktrace.WithSpanProcessor(bsp),
)

_, span := tp.Tracer("tracer").Start(ctx, "leaked_span")
span.End()

err := tp.ForceFlush(ctx)
assert.NoError(t, err)

batch := getBatch(bsp)
assert.Equal(t, 0, len(batch))
batch = batch[:cap(batch)]

for _, span := range batch {
require.Nil(t, span)
}
}

func BenchmarkSpanProcessor(b *testing.B) {
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(
Expand Down

0 comments on commit 223a389

Please sign in to comment.