Skip to content

perf(ddtrace/tracer): reduce allocations on span lifecycle hot path - #5987

Open
darccio wants to merge 1 commit into
mainfrom
darccio/perf-tracer-span-lifecycle-allocs
Open

darccio wants to merge 1 commit into
mainfrom
darccio/perf-tracer-span-lifecycle-allocs

Conversation

@darccio

@darccio darccio commented Nov 25, 2026

Copy link
Copy Markdown
Member

What does this PR do?

Reduces per-span heap allocations and latency on the core ddtrace/tracer span lifecycle and v0.4 flush path:

  • Inlines initialSpans inside trace (ddtrace/tracer/spancontext.go) to avoid a separate make([]*Span, 0, traceStartSize) heap allocation on every root trace.
  • Co-allocates non-pooled Span, SpanContext, and trace into spanAlloc and rootSpanAlloc (ddtrace/tracer/span_pool.go, ddtrace/tracer/spancontext.go, ddtrace/tracer/tracer.go). Pooled spans stay independent.
  • Reuses prebuilt immutable single-entry decision-maker maps in ddtrace/tracer/propagating_tags.go and caches the per-second upper hex string for locally generated 128-bit trace IDs in traceID.UpperHex (ddtrace/tracer/spancontext.go).
  • Pools *msgp.Writer in ddtrace/tracer/payload_v04.go to avoid per-push msgp.Encodable interface boxing in msgp.Encode.
  • Embeds finalChunk on trace (guarded by finalChunkUsed so late child spans allocate a fresh chunk safely) and lazily allocates the stats slice in submitChunk (ddtrace/tracer/tracer.go).
  • Adds trace-level tag headroom (+4) to SpanMeta.ReserveIfLargeEnough for 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) shows startSpan, spanStart, Finish, finishedOneLocked, SpanMeta, acquireSpan, newSpanContext, and newTrace as the largest core tracer CPU and allocation hotspots.

Benchmarks (5-run medians, Apple M5 Pro, Go 1.27.4):

Benchmark Latency Bytes Allocs
BenchmarkSpanLifecycle/Minimal 2589 -> 2392 ns/op (-7.6%) 7094 -> 6471 B/op (-8.8%) 77 -> 68 (-11.7%)
BenchmarkSpanLifecycle/TagHeavy 3372 -> 2922 ns/op (-13.3%) 8709 -> 7668 B/op (-12.0%) 97 -> 86 (-11.3%)
BenchmarkSpanLifecycle/MultiService 2757 -> 2491 ns/op (-9.6%) 6433 -> 6030 B/op (-6.3%) 74 -> 66 (-10.8%)
BenchmarkStartSpanManyTags/9-tags 1079 -> 1054 ns/op (-2.3%) 2641 -> 2737 B/op (+3.6%) 19 -> 16 (-15.8%)
BenchmarkStartSpanManyTags/7-tags-child 1140 -> 975 ns/op (-14.4%) 2244 -> 2308 B/op (+2.9%) 19 -> 18 (-5.3%)
BenchmarkConcurrentTracing 1479 -> 1464 us/op (-1.0%) 1755 -> 1819 KB/op (+3.6%) 14302 -> 12802 (-10.5%)

Verified with go test -race ./ddtrace/tracer/..., make apidiff/incompatible, and make lint/errlog.

Reviewer Checklist

  • Changed code has unit tests for its functionality at or near 100% coverage.
  • System-Tests covering this feature have been added and enabled with the va.b.c-dev version tag.
  • There is a benchmark for any new code, or changes to existing code.
  • If this interacts with the agent in a new way, a system test has been added.
  • New code is free of linting errors.
  • New code does not break existing tests.
  • Add an appropriate team label so this PR gets put in the right place for the release notes.
  • All generated files are up to date.
  • Non-trivial go.mod changes, e.g. adding new modules, are reviewed by @DataDog/dd-trace-go-guild.

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%)
@darccio
darccio requested review from a team as code owners November 25, 2026 15:33
@darccio
darccio requested review from Mascarpone and removed request for a team November 25, 2026 15:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T15:37:25.176685Z 472a51c PR opened
🔒 Security Review ✅ Completed 2026-11-25T15:39:54.424054Z 472a51c PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown
Contributor

Config Audit

PACKAGE: contrib/cloud.google.com/go/pubsubtrace
  STATUS      CONFIG                                            CALL_SITES
  UNMIGRATED  DD_GOOGLE_CLOUD_PUBSUB_PROPAGATION_AS_SPAN_LINKS  1

PACKAGE: contrib/confluentinc/confluent-kafka-go/kafkatrace
  STATUS      CONFIG                            CALL_SITES
  UNMIGRATED  DD_TRACE_KAFKA_ANALYTICS_ENABLED  1

PACKAGE: crashtracker
  STATUS      CONFIG                    CALL_SITES
  STILL_READ  DD_API_KEY                1
  STILL_READ  DD_SITE                   1
  STILL_READ  DD_TAGS                   1
  UNMIGRATED  DD_CRASHTRACKING_ENABLED  1

PACKAGE: ddtrace/opentelemetry/log
  STATUS      CONFIG                    CALL_SITES
  STILL_READ  DD_ENV                    1
  STILL_READ  DD_SERVICE                1
  STILL_READ  DD_TAGS                   1
  STILL_READ  DD_TRACE_REPORT_HOSTNAME  1
  STILL_READ  DD_VERSION                1
  UNMIGRATED  DD_HOSTNAME               1
  UNMIGRATED  OTEL_RESOURCE_ATTRIBUTES  1
  UNMIGRATED  OTEL_SERVICE_NAME         1

PACKAGE: ddtrace/opentelemetry/metric
  STATUS      CONFIG                    CALL_SITES
  STILL_READ  DD_ENV                    1
  STILL_READ  DD_METRICS_OTEL_ENABLED   1
  STILL_READ  DD_SERVICE                1
  STILL_READ  DD_TAGS                   1
  STILL_READ  DD_TRACE_REPORT_HOSTNAME  1
  STILL_READ  DD_VERSION                1
  STILL_READ  OTEL_METRICS_EXPORTER     1
  UNMIGRATED  DD_HOSTNAME               1
  UNMIGRATED  OTEL_RESOURCE_ATTRIBUTES  1
  UNMIGRATED  OTEL_SERVICE_NAME         1

PACKAGE: ddtrace/tracer
  STATUS      CONFIG                                    CALL_SITES
  STILL_READ  DD_TRACE_PROPAGATION_BEHAVIOR_EXTRACT     1
  STILL_READ  DD_TRACE_PROPAGATION_EXTRACT_FIRST        1
  STILL_READ  DD_TRACE_PROPAGATION_STYLE_EXTRACT        1
  STILL_READ  DD_TRACE_PROPAGATION_STYLE_INJECT         1
  UNMIGRATED  DD_APM_TRACING_ENABLED                    1
  UNMIGRATED  DD_TRACE_128_BIT_TRACEID_LOGGING_ENABLED  1
  UNMIGRATED  DD_TRACE_DEBUG_SEELOG_WORKAROUND          1
  UNMIGRATED  OTEL_TRACES_SAMPLER_ARG                   1

PACKAGE: instrumentation
  STATUS      CONFIG                                       CALL_SITES
  STILL_READ  DD_DATA_STREAMS_ENABLED                      1
  UNMIGRATED  DD_API_SECURITY_ENDPOINT_COLLECTION_ENABLED  1

PACKAGE: instrumentation/graphql
  STATUS      CONFIG                             CALL_SITES
  UNMIGRATED  DD_TRACE_GRAPHQL_ERROR_EXTENSIONS  1

PACKAGE: instrumentation/httptrace
  STATUS      CONFIG                                                 CALL_SITES
  UNMIGRATED  DD_GOOGLE_CLOUD_PUBSUB_PROPAGATION_AS_SPAN_LINKS       1
  UNMIGRATED  DD_HTTP_SERVER_TAG_QUERY_STRING_SIZE                   1
  UNMIGRATED  DD_TRACE_BAGGAGE_TAG_KEYS                              1
  UNMIGRATED  DD_TRACE_CLIENT_IP_ENABLED                             1
  UNMIGRATED  DD_TRACE_HTTP_SERVER_ERROR_STATUSES                    1
  UNMIGRATED  DD_TRACE_HTTP_URL_QUERY_STRING_ALLOWLIST               1
  UNMIGRATED  DD_TRACE_HTTP_URL_QUERY_STRING_ALLOWLIST_CLIENT        1
  UNMIGRATED  DD_TRACE_HTTP_URL_QUERY_STRING_ALLOWLIST_SERVER        1
  UNMIGRATED  DD_TRACE_HTTP_URL_QUERY_STRING_DISABLED                1
  UNMIGRATED  DD_TRACE_INFERRED_PROXY_SERVICES_ENABLED               1
  UNMIGRATED  DD_TRACE_OBFUSCATION_QUERY_STRING_REGEXP               2
  UNMIGRATED  DD_TRACE_RESOURCE_RENAMING_ALWAYS_SIMPLIFIED_ENDPOINT  1
  UNMIGRATED  DD_TRACE_RESOURCE_RENAMING_ENABLED                     1

PACKAGE: instrumentation/internal/namingschema
  STATUS      CONFIG                                             CALL_SITES
  STILL_READ  DD_SERVICE                                         1
  UNMIGRATED  DD_TRACE_REMOVE_INTEGRATION_SERVICE_NAMES_ENABLED  1

PACKAGE: internal
  STATUS      CONFIG                         CALL_SITES
  STILL_READ  DD_AGENT_HOST                  1
  STILL_READ  DD_TAGS                        1
  STILL_READ  DD_TRACE_AGENT_PORT            1
  STILL_READ  DD_TRACE_AGENT_URL             1
  UNMIGRATED  DD_EXTERNAL_ENV                1
  UNMIGRATED  DD_GIT_COMMIT_SHA              1
  UNMIGRATED  DD_GIT_REPOSITORY_URL          1
  UNMIGRATED  DD_TRACE_GIT_METADATA_ENABLED  1

PACKAGE: internal/appsec
  STATUS      CONFIG           CALL_SITES
  UNMIGRATED  DD_APPSEC_RULES  1

PACKAGE: internal/appsec/config
  STATUS      CONFIG                                                CALL_SITES
  UNMIGRATED  DD_API_SECURITY_DOWNSTREAM_BODY_ANALYSIS_SAMPLE_RATE  1
  UNMIGRATED  DD_API_SECURITY_ENABLED                               1
  UNMIGRATED  DD_API_SECURITY_MAX_DOWNSTREAM_REQUEST_BODY_ANALYSIS  1
  UNMIGRATED  DD_API_SECURITY_PROXY_SAMPLE_RATE                     1
  UNMIGRATED  DD_API_SECURITY_REQUEST_SAMPLE_RATE                   1
  UNMIGRATED  DD_API_SECURITY_SAMPLE_DELAY                          1
  UNMIGRATED  DD_APM_TRACING_ENABLED                                1
  UNMIGRATED  DD_APPSEC_AGENTIC_ONBOARDING                          1
  UNMIGRATED  DD_APPSEC_DISABLE_FEATURES                            1
  UNMIGRATED  DD_APPSEC_ENABLED                                     2
  UNMIGRATED  DD_APPSEC_MAX_STACK_TRACE_DEPTH                       1
  UNMIGRATED  DD_APPSEC_RASP_ENABLED                                1
  UNMIGRATED  DD_APPSEC_RULES                                       1
  UNMIGRATED  DD_APPSEC_SCA_ENABLED                                 1
  UNMIGRATED  DD_APPSEC_STACK_TRACE_ENABLED                         1
  UNMIGRATED  DD_APPSEC_TRACE_RATE_LIMIT                            1
  UNMIGRATED  DD_APPSEC_WAF_TIMEOUT                                 1

PACKAGE: internal/bazel
  STATUS      CONFIG                                  CALL_SITES
  UNMIGRATED  DD_TEST_OPTIMIZATION_MANIFEST_FILE      1
  UNMIGRATED  DD_TEST_OPTIMIZATION_PAYLOADS_IN_FILES  1

PACKAGE: internal/civisibility/envconfig
  STATUS      CONFIG                   CALL_SITES
  STILL_READ  DD_CIVISIBILITY_ENABLED  1

PACKAGE: internal/civisibility/integrations
  STATUS      CONFIG                                               CALL_SITES
  STILL_READ  DD_SERVICE                                           1
  STILL_READ  DD_TRACE_DEBUG                                       1
  UNMIGRATED  DD_CIVISIBILITY_CODE_COVERAGE_REPORT_UPLOAD_ENABLED  1
  UNMIGRATED  DD_CIVISIBILITY_DYNAMIC_ATR_BUCKETS                  1
  UNMIGRATED  DD_CIVISIBILITY_DYNAMIC_ATR_ENABLED                  1
  UNMIGRATED  DD_CIVISIBILITY_EARLY_FLAKE_DETECTION_ENABLED        1
  UNMIGRATED  DD_CIVISIBILITY_EARLY_FLAKE_DETECTION_MAX_RETRIES    1
  UNMIGRATED  DD_CIVISIBILITY_FLAKY_RETRY_COUNT                    1
  UNMIGRATED  DD_CIVISIBILITY_FLAKY_RETRY_ENABLED                  1
  UNMIGRATED  DD_CIVISIBILITY_GIT_UPLOAD_ENABLED                   1
  UNMIGRATED  DD_CIVISIBILITY_IMPACTED_TESTS_DETECTION_ENABLED     1
  UNMIGRATED  DD_CIVISIBILITY_SUBTEST_FEATURES_ENABLED             1
  UNMIGRATED  DD_CIVISIBILITY_TOTAL_FLAKY_RETRY_COUNT              1
  UNMIGRATED  DD_TEST_MANAGEMENT_ATTEMPT_TO_FIX_RETRIES            1
  UNMIGRATED  DD_TEST_MANAGEMENT_ENABLED                           1

PACKAGE: internal/civisibility/integrations/gotesting
  STATUS      CONFIG                                                           CALL_SITES
  UNMIGRATED  DD_CIVISIBILITY_INTERNAL_PARALLEL_EARLY_FLAKE_DETECTION_ENABLED  2
  UNMIGRATED  DD_CIVISIBILITY_RETRY_EXECUTION_MODE                             1
  UNMIGRATED  DD_CIVISIBILITY_RETRY_PROCESS_MAX_CONCURRENCY                    1
  UNMIGRATED  DD_CIVISIBILITY_RETRY_PROCESS_TIMEOUT                            1
  UNMIGRATED  DD_TEST_MANAGEMENT_ENABLED                                       2

PACKAGE: internal/civisibility/integrations/logs
  STATUS      CONFIG                        CALL_SITES
  UNMIGRATED  DD_CIVISIBILITY_LOGS_ENABLED  1

PACKAGE: internal/civisibility/utils
  STATUS      CONFIG                              CALL_SITES
  STILL_READ  DD_SERVICE                          1
  UNMIGRATED  DD_ACTION_EXECUTION_ID              1
  UNMIGRATED  DD_PIPELINE_EXECUTION_ID            1
  UNMIGRATED  DD_TEST_OPTIMIZATION_ENV_DATA_FILE  1
  UNMIGRATED  DD_TEST_SESSION_NAME                1

PACKAGE: internal/civisibility/utils/net
  STATUS      CONFIG                             CALL_SITES
  STILL_READ  DD_API_KEY                         1
  STILL_READ  DD_CIVISIBILITY_AGENTLESS_ENABLED  1
  STILL_READ  DD_CIVISIBILITY_AGENTLESS_URL      1
  STILL_READ  DD_ENV                             1
  STILL_READ  DD_SERVICE                         1
  STILL_READ  DD_SITE                            1
  STILL_READ  DD_TAGS                            1
  STILL_READ  DD_VERSION                         1
  UNMIGRATED  DD_CODE_COVERAGE_FLAGS             1

PACKAGE: internal/civisibility/utils/telemetry
  STATUS      CONFIG                                         CALL_SITES
  UNMIGRATED  DD_CIVISIBILITY_AUTO_INSTRUMENTATION_PROVIDER  1

PACKAGE: internal/clientip
  STATUS      CONFIG                     CALL_SITES
  UNMIGRATED  DD_TRACE_CLIENT_IP_HEADER  1

PACKAGE: internal/globalconfig
  STATUS      CONFIG                           CALL_SITES
  UNMIGRATED  DD_INSTRUMENTATION_INSTALL_ID    1
  UNMIGRATED  DD_INSTRUMENTATION_INSTALL_TIME  1
  UNMIGRATED  DD_INSTRUMENTATION_INSTALL_TYPE  1

PACKAGE: internal/hostname
  STATUS      CONFIG       CALL_SITES
  UNMIGRATED  DD_HOSTNAME  1

PACKAGE: internal/namingschema
  STATUS      CONFIG                                             CALL_SITES
  UNMIGRATED  DD_TRACE_REMOVE_INTEGRATION_SERVICE_NAMES_ENABLED  1

PACKAGE: internal/processtags
  STATUS      CONFIG                                          CALL_SITES
  UNMIGRATED  DD_EXPERIMENTAL_PROPAGATE_PROCESS_TAGS_ENABLED  1

PACKAGE: internal/remoteconfig
  STATUS      CONFIG                                  CALL_SITES
  STILL_READ  DD_ENV                                  1
  UNMIGRATED  DD_RC_TUF_ROOT                          1
  UNMIGRATED  DD_REMOTE_CONFIGURATION_ENABLED         1
  UNMIGRATED  DD_REMOTE_CONFIG_POLL_INTERVAL_SECONDS  1

PACKAGE: internal/telemetry
  STATUS      CONFIG                                             CALL_SITES
  STILL_READ  DD_API_KEY                                         1
  STILL_READ  DD_SITE                                            1
  UNMIGRATED  DD_API_SECURITY_ENDPOINT_COLLECTION_MESSAGE_LIMIT  1
  UNMIGRATED  DD_INSTRUMENTATION_TELEMETRY_ENABLED               1
  UNMIGRATED  DD_TELEMETRY_DEBUG                                 1
  UNMIGRATED  DD_TELEMETRY_DEPENDENCY_COLLECTION_ENABLED         1
  UNMIGRATED  DD_TELEMETRY_EXTENDED_HEARTBEAT_INTERVAL           1
  UNMIGRATED  DD_TELEMETRY_HEARTBEAT_INTERVAL                    1
  UNMIGRATED  DD_TELEMETRY_LOG_COLLECTION_ENABLED                1
  UNMIGRATED  DD_TELEMETRY_METRICS_ENABLED                       1

PACKAGE: openfeature
  STATUS      CONFIG                                                     CALL_SITES
  STILL_READ  DD_ENV                                                     2
  STILL_READ  DD_SERVICE                                                 2
  STILL_READ  DD_VERSION                                                 2
  UNMIGRATED  DD_EXPERIMENTAL_FLAGGING_PROVIDER_SPAN_ENRICHMENT_ENABLED  1
  UNMIGRATED  DD_FLAGGING_EVALUATION_COUNTS_ENABLED                      1

PACKAGE: profiler
  STATUS      CONFIG                                    CALL_SITES
  STILL_READ  DD_API_KEY                                1
  STILL_READ  DD_ENV                                    1
  STILL_READ  DD_SERVICE                                1
  STILL_READ  DD_SITE                                   1
  STILL_READ  DD_TAGS                                   1
  STILL_READ  DD_TRACE_STARTUP_LOGS                     1
  STILL_READ  DD_VERSION                                1
  UNMIGRATED  DD_PROFILING_AGENTLESS                    1
  UNMIGRATED  DD_PROFILING_DEBUG_COMPRESSION_SETTINGS   1
  UNMIGRATED  DD_PROFILING_DELTA                        1
  UNMIGRATED  DD_PROFILING_ENABLED                      3
  UNMIGRATED  DD_PROFILING_ENDPOINT_COUNT_ENABLED       1
  UNMIGRATED  DD_PROFILING_EXECUTION_TRACE_ENABLED      1
  UNMIGRATED  DD_PROFILING_EXECUTION_TRACE_LIMIT_BYTES  1
  UNMIGRATED  DD_PROFILING_EXECUTION_TRACE_PERIOD       1
  UNMIGRATED  DD_PROFILING_FLUSH_ON_EXIT                1
  UNMIGRATED  DD_PROFILING_OUTPUT_DIR                   1
  UNMIGRATED  DD_PROFILING_UPLOAD_TIMEOUT               1
  UNMIGRATED  DD_PROFILING_URL                          1

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +1183 to +1184
t.finalChunk = chunk{spans: spans, willSend: willSend, spansToRelease: spansToRelease, filterRejected: filterRejected}
ch = &t.finalChunk

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@datadog-official datadog-official Bot 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.

Bits Code Review: FAIL

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).

Open Bits AI session

🤖 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.

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.

P1 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.

Suggested change
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}

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.

P1 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

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.

P2 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

@datadog-official

Copy link
Copy Markdown
Contributor

Pipelines  Tests

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 4 Pipeline jobs failed

Orchestrion | Integration Test (macos | stable | DRIVER) — ❌ 4 tests failed · 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

❌ Test from github.com/DataDog/dd-trace-go/v2/internal/orchestrion/_integration/otel_api
Failed

=== RUN   Test
    generated_test.go:17: Running setup
    generated_test.go:17: Running test
    server.go:80: 
        	Error Trace:	/Users/runner/work/dd-trace-go/dd-trace-go/dd-trace-go/internal/orchestrion/_integration/otel_api/server.go:80
        	            				/Users/runner/work/dd-trace-go/dd-trace-go/dd-trace-go/internal/orchestrion/_integration/internal/harness/harness.go:105
        	            				/Users/runner/work/dd-trace-go/dd-trace-go/dd-trace-go/internal/orchestrion/_integration/otel_api/generated_test.go:17
        	Error:      	Should be true
...
❌ TestNested from github.com/DataDog/dd-trace-go/v2/internal/orchestrion/_integration/otel_api
Failed

=== RUN   TestNested
    generated_test.go:21: Running setup
    generated_test.go:21: Running test
    generated_test.go:21: Received 2 spans
    generated_test.go:21: no span found matching the given conditions; collected 2 span(s):
          [0] spanID=3657628786839493724 parentID=0 name="internal" service="otel_api.test" resource="otel.parent" type=""
                FAIL: Operation == "dd.annotated"
                FAIL: Tags["function-name"] == annotated
...
↳ and 2 more — View all
Orchestrion | Integration Test (windows | oldstable | DRIVER) — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

Orchestrion | Integration Test (windows | stable | DRIVER) — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

View all 4 failed jobs.

ℹ️ Info

No other issues found (see more)

❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 92.52%
• Overall Coverage: 73.60% (+6.46%)

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 472a51c | Docs | View more details | Give us feedback!

@datadog-official

datadog-official Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

✨ Unblock PR with BitsAI

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 11 Pipeline jobs failed

Orchestrion | Integration Test (macos | oldstable | DRIVER) — ❌ 4 tests failed · 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

❌ Test from github.com/DataDog/dd-trace-go/v2/internal/orchestrion/_integration/otel_api
Failed

=== RUN   Test
    generated_test.go:17: Running setup
    generated_test.go:17: Running test
    server.go:80: 
        	Error Trace:	/Users/runner/work/dd-trace-go/dd-trace-go/dd-trace-go/internal/orchestrion/_integration/otel_api/server.go:80
        	            				/Users/runner/work/dd-trace-go/dd-trace-go/dd-trace-go/internal/orchestrion/_integration/internal/harness/harness.go:105
        	            				/Users/runner/work/dd-trace-go/dd-trace-go/dd-trace-go/internal/orchestrion/_integration/otel_api/generated_test.go:17
        	Error:      	Should be true
...
❌ TestNested from github.com/DataDog/dd-trace-go/v2/internal/orchestrion/_integration/otel_api
Failed

=== RUN   TestNested
    generated_test.go:21: Running setup
    generated_test.go:21: Running test
    generated_test.go:21: Received 2 spans
    generated_test.go:21: no span found matching the given conditions; collected 2 span(s):
          [0] spanID=1101285810328621411 parentID=0 name="internal" service="otel_api.test" resource="otel.parent" type=""
                FAIL: Operation == "dd.annotated"
                FAIL: Tags["function-name"] == annotated
...
↳ and 2 more — View all
DataDog/apm-reliability/dd-trace-go | pr-performance-gates — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

Orchestrion | Integration Test (macos | stable | DRIVER) — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

View all 11 failed jobs.

ℹ️ Info

No other issues found (see more)

❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 92.52%
• Overall Coverage: 74.21% (+7.07%)

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 472a51c | Docs | View more details | Give us feedback!

@pr-commenter

pr-commenter Bot commented Nov 25, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-25 16:08:09

Comparing candidate commit 472a51c in PR branch darccio/perf-tracer-span-lifecycle-allocs with baseline commit 3fa83b0 in branch main.

📊 Benchmarking dashboard

Found 63 performance improvements and 15 performance regressions! Performance is the same for 338 metrics, 0 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

scenario:BenchmarkExtractW3C

  • 🟥 allocated_mem [+432 bytes; +432 bytes] or [+35.294%; +35.294%]
  • 🟥 allocations [+1; +1] or [+6.250%; +6.250%]
  • 🟥 execution_time [+226.891ns; +244.709ns] or [+13.481%; +14.540%]

scenario:BenchmarkFiberMiddleware/appsec-off

  • 🟩 allocated_mem [-788 bytes; -724 bytes] or [-12.105%; -11.122%]
  • 🟩 allocations [-11; -10] or [-13.172%; -11.942%]
  • 🟩 execution_time [-1144.268ns; -851.132ns] or [-9.362%; -6.964%]

scenario:BenchmarkHttpServeTrace

  • 🟩 allocated_mem [-1.060KB; -1.017KB] or [-15.193%; -14.570%]
  • 🟩 allocations [-11; -11] or [-15.278%; -15.278%]
  • 🟩 execution_time [-1.386µs; -1.236µs] or [-11.233%; -10.020%]

scenario:BenchmarkHttpServeTraceQueryObfuscation/few_params

  • 🟩 allocated_mem [-1.061KB; -1.019KB] or [-14.860%; -14.271%]
  • 🟩 allocations [-11; -11] or [-14.865%; -14.865%]
  • 🟩 execution_time [-1.448µs; -1.100µs] or [-11.562%; -8.788%]

scenario:BenchmarkHttpServeTraceQueryObfuscation/many_params

  • 🟩 allocated_mem [-1.056KB; -1.013KB] or [-14.566%; -13.970%]
  • 🟩 allocations [-11; -11] or [-14.865%; -14.865%]
  • 🟩 execution_time [-1.522µs; -1.145µs] or [-11.559%; -8.697%]

scenario:BenchmarkHttpServeTraceQueryObfuscation/really_long_1

  • 🟩 allocated_mem [-1028 bytes; -947 bytes] or [-10.049%; -9.256%]
  • 🟩 allocations [-11; -11] or [-15.068%; -15.068%]
  • 🟩 execution_time [-1.564µs; -1.004µs] or [-6.204%; -3.984%]

scenario:BenchmarkHttpServeTraceQueryObfuscation/really_long_2

  • 🟩 allocated_mem [-1.026KB; -0.976KB] or [-10.044%; -9.551%]
  • 🟩 allocations [-11; -11] or [-15.068%; -15.068%]
  • 🟩 execution_time [-1.533µs; -1.004µs] or [-6.139%; -4.021%]

scenario:BenchmarkInjectW3C

  • 🟩 allocated_mem [-32 bytes; -32 bytes] or [-3.008%; -3.008%]
  • 🟩 allocations [-1; -1] or [-11.111%; -11.111%]

scenario:BenchmarkOTelApiWithCustomTags/datadog_otel_api

  • 🟩 allocated_mem [-375 bytes; -363 bytes] or [-15.664%; -15.140%]
  • 🟩 allocations [-8; -8] or [-33.333%; -33.333%]
  • 🟩 execution_time [-455.406ns; -408.994ns] or [-9.932%; -8.920%]

scenario:BenchmarkOTelApiWithCustomTags/otel_api

  • 🟩 allocated_mem [-386 bytes; -370 bytes] or [-9.917%; -9.491%]
  • 🟩 allocations [-8; -8] or [-19.512%; -19.512%]
  • 🟩 execution_time [-574.470ns; -489.530ns] or [-8.442%; -7.194%]

scenario:BenchmarkPartialFlushing/Disabled

  • 🟥 allocated_mem [+6.121MB; +6.669MB] or [+3.354%; +3.654%]
  • 🟩 allocations [-100076; -100065] or [-8.334%; -8.333%]

scenario:BenchmarkPartialFlushing/Enabled

  • 🟥 allocated_mem [+4.214MB; +7.268MB] or [+2.447%; +4.220%]
  • 🟩 allocations [-100477; -100459] or [-8.352%; -8.350%]

scenario:BenchmarkPayloadVersions/detailed_1000spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/detailed_100spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/detailed_10spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/detailed_1spans/v0.4

  • 🟩 allocated_mem [-24 bytes; -24 bytes] or [-5.357%; -5.357%]
  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]
  • 🟩 execution_time [-49.214ns; -41.846ns] or [-6.689%; -5.688%]

scenario:BenchmarkPayloadVersions/metastruct_1000spans/v1.0

  • 🟩 execution_time [-13.658µs; -7.628µs] or [-4.353%; -2.431%]

scenario:BenchmarkPayloadVersions/simple_1000spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/simple_1000spans/v1.0

  • 🟥 allocated_mem [+1 bytes; +1 bytes] or [+3.030%; +3.030%]
  • 🟥 execution_time [+3.966µs; +4.551µs] or [+2.856%; +3.276%]

scenario:BenchmarkPayloadVersions/simple_100spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/simple_100spans/v1.0

  • 🟥 execution_time [+338.112ns; +423.488ns] or [+2.286%; +2.864%]

scenario:BenchmarkPayloadVersions/simple_10spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/simple_1spans/v0.4

  • 🟩 allocated_mem [-24 bytes; -24 bytes] or [-5.357%; -5.357%]
  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]
  • 🟩 execution_time [-47.938ns; -42.562ns] or [-9.838%; -8.735%]

scenario:BenchmarkPayloadVersions/spankind_1000spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/spankind_100spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/spankind_10spans/v0.4

  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]

scenario:BenchmarkPayloadVersions/spankind_1spans/v0.4

  • 🟩 allocated_mem [-24 bytes; -24 bytes] or [-5.357%; -5.357%]
  • 🟩 allocations [-1; -1] or [-25.000%; -25.000%]
  • 🟩 execution_time [-46.398ns; -37.822ns] or [-7.717%; -6.291%]

scenario:BenchmarkSetTagStringer

  • 🟩 execution_time [-2.864ns; -2.098ns] or [-3.607%; -2.641%]

scenario:BenchmarkSingleSpanRetention/no-rules

  • 🟥 allocated_mem [+6.399KB; +6.400KB] or [+4.146%; +4.147%]
  • 🟩 allocations [-105; -105] or [-8.592%; -8.592%]

scenario:BenchmarkSingleSpanRetention/with-rules/match-all

  • 🟥 allocated_mem [+6.378KB; +6.407KB] or [+4.130%; +4.148%]
  • 🟩 allocations [-105; -105] or [-8.592%; -8.592%]

scenario:BenchmarkSingleSpanRetention/with-rules/match-half

  • 🟥 allocated_mem [+6.373KB; +6.400KB] or [+4.126%; +4.143%]
  • 🟩 allocations [-105; -105] or [-8.592%; -8.592%]

scenario:BenchmarkStartSpan

  • 🟥 allocated_mem [+64 bytes; +64 bytes] or [+4.224%; +4.224%]
  • 🟩 allocations [-1; -1] or [-7.143%; -7.143%]

scenario:BenchmarkStartSpanConfig/scenario_WithStartSpanConfig

  • 🟩 allocated_mem [-240 bytes; -240 bytes] or [-12.048%; -12.048%]
  • 🟩 allocations [-5; -5] or [-31.250%; -31.250%]
  • 🟩 execution_time [-231.317ns; -194.683ns] or [-8.440%; -7.104%]

scenario:BenchmarkStartSpanConfig/scenario_none

  • 🟩 allocated_mem [-240 bytes; -240 bytes] or [-10.309%; -10.309%]
  • 🟩 allocations [-5; -5] or [-27.778%; -27.778%]
  • 🟩 execution_time [-240.132ns; -200.668ns] or [-8.201%; -6.853%]

scenario:BenchmarkStartSpanManyTags/7-tags-child

  • 🟥 allocated_mem [+63 bytes; +64 bytes] or [+2.848%; +2.871%]
  • 🟩 allocations [-1; -1] or [-5.263%; -5.263%]

scenario:BenchmarkStartSpanManyTags/8-tags-child

  • 🟥 allocated_mem [+63 bytes; +64 bytes] or [+2.828%; +2.864%]
  • 🟩 allocations [-1; -1] or [-5.263%; -5.263%]

scenario:BenchmarkStartSpanManyTags/9-tags

  • 🟥 allocated_mem [+96 bytes; +96 bytes] or [+3.636%; +3.636%]
  • 🟩 allocations [-3; -3] or [-15.789%; -15.789%]

scenario:BenchmarkTracerAddSpans

  • 🟩 allocations [-5; -5] or [-23.810%; -23.810%]
  • 🟩 execution_time [-161.541ns; -126.659ns] or [-2.897%; -2.271%]

@dd-octo-sts dd-octo-sts Bot mentioned this pull request Nov 25, 2026
Comment on lines +727 to +732
// 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

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.

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) {

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.

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.

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.

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.

Comment on lines +18 to +20
// 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.

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.

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.

Suggested change
// 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.

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.

2 participants