Repository navigation
Conversation
Reduce per-span heap allocations on the core StartSpan/Finish/flush path: - Inline initialSpans array inside trace to avoid make([]*Span, 0, traceStartSize). - Co-allocate non-pooled Span, SpanContext, and trace into spanAlloc/rootSpanAlloc. - Reuse prebuilt immutable decision-maker maps in propagating_tags and cache the per-second 128-bit upper hex string in traceID.UpperHex. - Pool msgp.Writer in payloadV04.push to avoid interface boxing in msgp.Encode. - Embed finalChunk on trace (guarded by finalChunkUsed for late child spans) and lazily allocate the stats slice in submitChunk. - Include trace-level tag headroom (+4) in root-span SpanMeta sizing hints. Benchmarks (5-run medians, Apple M5 Pro, Go 1.27.4): - BenchmarkSpanLifecycle/Minimal: 2589 -> 2392 ns/op (-7.6%), 7094 -> 6471 B/op (-8.8%), 77 -> 68 allocs/op (-11.7%) - BenchmarkSpanLifecycle/TagHeavy: 3372 -> 2922 ns/op (-13.3%), 8709 -> 7668 B/op (-12.0%), 97 -> 86 allocs/op (-11.3%) - BenchmarkSpanLifecycle/MultiService: 2757 -> 2491 ns/op (-9.6%), 6433 -> 6030 B/op (-6.3%), 74 -> 66 allocs/op (-10.8%) - BenchmarkStartSpanManyTags/9-tags: 1079 -> 1054 ns/op (-2.3%), 19 -> 16 allocs/op (-15.8%)
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Config Audit |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 472a51cc24
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| t.finalChunk = chunk{spans: spans, willSend: willSend, spansToRelease: spansToRelease, filterRejected: filterRejected} | ||
| ch = &t.finalChunk |
There was a problem hiding this comment.
Release the embedded chunk's span references after processing
With span pooling disabled, retaining any span or SpanContext after a trace finishes now retains every span in its first full-flush chunk, including their tags and events. Previously, setting t.spans = nil allowed those child spans to be collected once the worker consumed the standalone chunk; now t.finalChunk.spans and t.finalChunk.spansToRelease remain reachable through the trace indefinitely. processOutChunk never clears these fields, and releaseSpans(false, ...) does nothing. Applications retaining contexts for background work can therefore retain large completed traces unnecessarily. Clear the embedded chunk's references once processing completes, including paths where submission is dropped.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Two production-impacting issues stand out: a data race / potential nil-dereference when initialSpans is cleared while a queued chunk still holds ownership of it (line 1036), and a memory leak where finalChunk.spansToRelease is never cleared after processing or on drop paths (line 1183). A third issue causes stale span references to be retained in the inline array after the active slice grows beyond ten spans (line 673).
🤖 Bits Code Review · Commit 472a51c
| // capacity is reached, we will not be able to complete this trace. | ||
| t.full = true | ||
| t.spans = nil // allow our spans to be collected by GC. | ||
| clear(t.initialSpans[:]) // drop inline references to spans. |
There was a problem hiding this comment.
Preserve inline buffers still owned by queued chunks
If a trace of at most ten spans fully flushes, then late children exceed traceMaxSize before the worker consumes that first chunk, the queued chunk still owns initialSpans. Clearing this array replaces its entries with nil while the worker can read them, introducing a data race and a possible process-crashing nil dereference in sampleChunk. Preserve the array once a full flush has transferred its ownership.
| clear(t.initialSpans[:]) // drop inline references to spans. | |
| if !t.finalChunkUsed { | |
| clear(t.initialSpans[:]) | |
| } |
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
| var ch *chunk | ||
| if !t.finalChunkUsed { | ||
| t.finalChunkUsed = true | ||
| t.finalChunk = chunk{spans: spans, willSend: willSend, spansToRelease: spansToRelease, filterRejected: filterRejected} |
There was a problem hiding this comment.
Release embedded chunk references after processing
With span pooling disabled, the default, retaining a SpanContext after a full flush now retains every span and its metadata from the first fully flushed chunk through finalChunk.spansToRelease. processOutChunk never clears that slice, and dropped chunks have no cleanup either. Previously the standalone chunk became collectible after processing. Release embedded chunk references on both processing and drop paths, coordinating cleanup with inline-buffer ownership.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
| spans []*Span | ||
| // inline backing array for the initial span slice to avoid a separate heap allocation | ||
| // +checklocks:mu | ||
| initialSpans [defaultTraceStartSize]*Span |
There was a problem hiding this comment.
Drop stale inline references when the span slice grows
With partial flushing enabled, growing a trace beyond ten spans moves t.spans to another backing array, but initialSpans retains its original pointers. Partial-flush tail clearing then clears only the new array, keeping already-flushed children and their metadata alive for the trace's remaining lifetime. Clear stale inline references when growth moves the active slice off that array, while preserving arrays owned by queued chunks.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
- 👍 Useful: correct, and you're fixing it or will.
- 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
- 😕 Unclear: you can't tell what it means or why it matters.
- 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.
🤖 Bits Code Review · Open Bits AI session
❌ ErrorsYour PR has failed checks. Please review the issues below and take necessary action before merging. 🚦 4 Pipeline jobs failed
ℹ️ InfoNo other issues found (see more)❄️ No new flaky tests detected 🎯 Code Coverage (details) Useful? React with 👍 / 👎 This comment will be updated automatically if new data arrives.🔗 Commit SHA: 472a51c | Docs | View more details | Give us feedback! |
❌ ErrorsYour PR has failed checks. Please review the issues below and take necessary action before merging. 🚦 11 Pipeline jobs failed
ℹ️ InfoNo other issues found (see more)❄️ No new flaky tests detected 🎯 Code Coverage (details) Useful? React with 👍 / 👎 This comment will be updated automatically if new data arrives.🔗 Commit SHA: 472a51c | Docs | View more details | Give us feedback! |
BenchmarksBenchmark execution time: 2026-11-25 16:08:09 Comparing candidate commit 472a51c in PR branch Found 63 performance improvements and 15 performance regressions! Performance is the same for 338 metrics, 0 unstable metrics.
|
| // finalChunk holds the chunk submitted on the first full flush of this trace, | ||
| // avoiding a separate heap allocation for &chunk{...}. If late child spans | ||
| // trigger a second full flush after finalChunkUsed is set, a fresh chunk is | ||
| // allocated so the worker's read of finalChunk never races. | ||
| // +checklocks:mu | ||
| finalChunk chunk |
There was a problem hiding this comment.
After the first full flush, finalChunk.spans/spansToRelease (and initialSpans) keep every span of that chunk reachable while anything holds a span or SpanContext of this trace, for example a background goroutine with the request ctx. Before this change, only the root stayed alive. Consider clearing the chunk slices in processOutChunk after releaseSpans.
| return &Span{} | ||
| } | ||
|
|
||
| func acquireSpanWithContext(poolEnabled, needsNewTrace bool) (*Span, *SpanContext, *trace) { |
There was a problem hiding this comment.
acquireSpan no longer has a production caller. Only span_pool_test.go:903 uses it, so those tests exercise a copy of this logic, not the code that runs in production. Remove acquireSpan and change the tests to use acquireSpanWithContext.
| m = make(map[string]string, 4) | ||
| t.propagatingTags.Store(m) | ||
| } else if len(m) == 1 { | ||
| // Copy if m could be a shared prebuilt DM snapshot. |
There was a problem hiding this comment.
The doc comment of setPropagatingTagUnsafe (lines 147-153) still says that a new map is allocated only when the atomic.Value holds nil. Update it to mention this prebuilt-DM copy as well.
| // msgpWriterPool recycles msgp.Writer instances used by payloadV04.push so | ||
| // encoding spanList avoids both the msgp.Encodable interface-boxing allocation | ||
| // of msgp.Encode and per-payload writer buffer allocations. |
There was a problem hiding this comment.
msgp.Encode already reuses writers through msgp's internal pool (msgp/write.go popWriter/freeW). The only allocation this saves is the Encodable boxing, so the comment overstates the gain.
| // msgpWriterPool recycles msgp.Writer instances used by payloadV04.push so | |
| // encoding spanList avoids both the msgp.Encodable interface-boxing allocation | |
| // of msgp.Encode and per-payload writer buffer allocations. | |
| // msgpWriterPool recycles msgp.Writer instances used by payloadV04.push. | |
| // Calling spanList.EncodeMsg directly avoids the msgp.Encodable | |
| // interface-boxing allocation of msgp.Encode. |
What does this PR do?
Reduces per-span heap allocations and latency on the core
ddtrace/tracerspan lifecycle and v0.4 flush path:initialSpansinsidetrace(ddtrace/tracer/spancontext.go) to avoid a separatemake([]*Span, 0, traceStartSize)heap allocation on every root trace.Span,SpanContext, andtraceintospanAllocandrootSpanAlloc(ddtrace/tracer/span_pool.go,ddtrace/tracer/spancontext.go,ddtrace/tracer/tracer.go). Pooled spans stay independent.ddtrace/tracer/propagating_tags.goand caches the per-second upper hex string for locally generated 128-bit trace IDs intraceID.UpperHex(ddtrace/tracer/spancontext.go).*msgp.Writerinddtrace/tracer/payload_v04.goto avoid per-pushmsgp.Encodableinterface boxing inmsgp.Encode.finalChunkontrace(guarded byfinalChunkUsedso late child spans allocate a fresh chunk safely) and lazily allocates thestatsslice insubmitChunk(ddtrace/tracer/tracer.go).SpanMeta.ReserveIfLargeEnoughfor tagged root spans to avoid an immediate 8-to-16 slot map rehash.Motivation
Production Go Continuous Profiler data (
language:go env:prod, ~807M spans/sec, ~2.06 traces per flush) showsstartSpan,spanStart,Finish,finishedOneLocked,SpanMeta,acquireSpan,newSpanContext, andnewTraceas the largest core tracer CPU and allocation hotspots.Benchmarks (5-run medians, Apple M5 Pro, Go 1.27.4):
BenchmarkSpanLifecycle/MinimalBenchmarkSpanLifecycle/TagHeavyBenchmarkSpanLifecycle/MultiServiceBenchmarkStartSpanManyTags/9-tagsBenchmarkStartSpanManyTags/7-tags-childBenchmarkConcurrentTracingVerified with
go test -race ./ddtrace/tracer/...,make apidiff/incompatible, andmake lint/errlog.Reviewer Checklist