Skip to content

fix(ddtrace/tracer): make traceID hex cache safe for concurrent reads#4726

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 12 commits into
mainfrom
dario.castane/incident-53951/repro
Jun 25, 2026
Merged

fix(ddtrace/tracer): make traceID hex cache safe for concurrent reads#4726
gh-worker-dd-mergequeue-cf854d[bot] merged 12 commits into
mainfrom
dario.castane/incident-53951/repro

Conversation

@darccio

@darccio darccio commented May 5, 2026

Copy link
Copy Markdown
Member

What does this PR do?

Makes the lazy traceID.hexEncoded cache (introduced in #4481) safe under concurrent reads. (*traceID).HexEncoded no longer writes the cache from a read path; the cache is now populated eagerly at construction finalization for the context-extraction paths, and HexEncoded falls back to a non-caching hex.EncodeToString if the cache is empty (so concurrent readers can never race on the string write).

Concrete changes:

  • (*traceID).HexEncoded is now a pure read with a non-caching fallback.
  • Renamed computeAndCacheHexcacheHex, with a doc comment stating it must be called at construction finalization, before the enclosing SpanContext is shared.
  • Call cacheHex() at the trace-ID extraction finalization sites, where the resulting SpanContext is about to be returned and may then be injected concurrently:
    • FromGenericCtx (all three return paths)
    • extractTextMap (Datadog propagator)
    • extractTraceID128 (covers B3 single/multi and W3C parseTraceparent)
    • spanContextFromTraceComment (sqlcomment Extract)
  • newSpanContext (the local StartSpan path) intentionally does not call cacheHex(): caching there would add an allocation to every span creation, including spans that are never injected. Local spans rely on the non-caching HexEncoded fallback instead, which is race-free because the fallback performs no write.
  • Test helpers traceIDFrom64Bits / traceIDFrom128Bits finalize via cacheHex.
  • New regression test TestConcurrentInjectTraceIDHex reproduces the race under -race (fan-out Inject on a shared SpanContext with an empty hex cache); fails on main, passes with this fix.

Motivation

PR #4481 cached the hex form of traceID to avoid millions of hex.EncodeToString allocations per second on the propagation hot path. The cache used a check-then-act lazy write with no synchronization:

func (t *traceID) HexEncoded() string {
    if t.hexEncoded == "" {
        t.computeAndCacheHex()
    }
    return t.hexEncoded
}

A KafkaWriter fan-out crashed with panic: runtime error: invalid memory address or nil pointer dereference in isValidPropagatableTag. Two goroutines call Inject on the same SpanContext; both see an empty cache, both write to t.hexEncoded, and a torn read of the Go string header ({ptr,len} is 16 bytes, not atomic) yields {nil, 16}. The downstream for _, ch := range v then dereferences the nil pointer.

Stack from the crash: tracer/util.go:41textmap.go:481propagating_tags.go:95textmap.go:463 (injectTextMapsetPropagatingTag(ctx, keyTraceID128, ctx.traceID.UpperHex())).

-race confirmed the same race directly: Read at spancontext.go:52 (check) vs. Previous write at spancontext.go:106 (computeAndCacheHex).

All traceID mutation sites are construction-time (before the SpanContext is shared across goroutines), so the read path can be made a pure, race-free read: extracted contexts populate the cache eagerly at finalization (keeping the inject hot path zero-alloc for propagated spans), while locally created spans fall back to a non-caching computation that performs no write. Affected released versions: v2.8.0-dev, v2.8.0-rc.1, v2.8.0-rc.2, and v2.8.0.

Note on the local-span path: because newSpanContext does not populate the cache, HexEncoded/UpperHex on a locally started span allocates on each call (e.g. per Inject, and once at span finish via setTraceTagsLocked). This is a deliberate trade to keep span creation allocation-free.

Reviewer's 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. You can check this by running make lint locally.
  • New code doesn't break existing tests. You can check this by running make test locally.
  • 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. You can check this by running make generate locally.
  • Non-trivial go.mod changes, e.g. adding new modules, are reviewed by @DataDog/dd-trace-go-guild. Make sure all nested modules are up to date by running make fix-modules locally.

@darccio
darccio requested review from a team as code owners May 5, 2026 14:30
@darccio darccio added the AI Generated Largely based on code generated by an AI or LLM. This label is the same across all dd-trace-* repos label May 5, 2026
@darccio darccio changed the title Dario.castane/incident 53951/repro fix(ddtrace/tracer): make traceID hex cache safe for concurrent reads May 5, 2026
@datadog-prod-us1-4

datadog-prod-us1-4 Bot commented May 5, 2026

Copy link
Copy Markdown

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
Patch Coverage: 88.89%
Overall Coverage: 62.88% (+3.93%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 01957d8 | Docs | Datadog PR Page | Give us feedback!

@pr-commenter

pr-commenter Bot commented May 5, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-06-25 10:44:31

Comparing candidate commit 01957d8 in PR branch dario.castane/incident-53951/repro with baseline commit 2f4d3ca in branch main.

Found 0 performance improvements and 2 performance regressions! Performance is the same for 295 metrics, 2 unstable metrics, 1 flaky benchmarks without significant changes.

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:BenchmarkInjectW3C

  • 🟥 allocated_mem [+64 bytes; +64 bytes] or [+6.400%; +6.400%]
  • 🟥 allocations [+2; +2] or [+28.571%; +28.571%]

Known flaky benchmarks

These benchmarks are marked as flaky and will not trigger a failure. Modify FLAKY_BENCHMARKS_REGEX to control which benchmarks are marked as flaky.

Known flaky benchmarks without significant changes:

  • scenario:BenchmarkOTLPTraceWriterFlush

@codecov

codecov Bot commented May 5, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 62.54%. Comparing base (080bac9) to head (7df48d1).

Files with missing lines Patch % Lines
ddtrace/tracer/spancontext.go 85.71% 1 Missing ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
ddtrace/tracer/sqlcomment.go 86.45% <100.00%> (-5.76%) ⬇️
ddtrace/tracer/textmap.go 84.44% <100.00%> (-4.79%) ⬇️
ddtrace/tracer/spancontext.go 93.52% <85.71%> (-2.57%) ⬇️

... and 280 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@kakkoyun

Copy link
Copy Markdown
Member

@rarguelloF could you have a look at this?

@kakkoyun

Copy link
Copy Markdown
Member

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented May 19, 2026

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-05-19 11:10:18 UTC ℹ️ Start processing command /merge


2026-05-19 11:10:28 UTC ℹ️ MergeQueue: waiting for PR to be ready

This pull request is not mergeable according to GitHub. Common reasons include pending required checks, missing approvals, or merge conflicts — but it could also be blocked by other repository rules or settings.
It will be added to the queue as soon as checks pass and/or get approvals. View in MergeQueue UI.
Note: if you pushed new commits since the last approval, you may need additional approval.
You can remove it from the waiting list with /remove command.


2026-05-19 16:03:13 UTC ⚠️ MergeQueue: This merge request was unqueued

devflow unqueued this merge request: It did not become mergeable within the expected time

@darccio

darccio commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

@codex review

darccio added 3 commits June 25, 2026 11:38
Split TestConcurrentInjectTraceIDHex into cold-cache (local span) and
hot-cache (extracted context) sub-tests. The cold-cache case now asserts
hexEncoded is empty as a precondition instead of forcing it, so the test
fails loudly if newSpanContext ever starts populating the cache. The new
hot-cache case round-trips through Inject/Extract so extractTextMap
finalizes the traceID via cacheHex, exercising the cached branch of
HexEncoded under -race.
…ests

Use the public HexEncoded() accessor instead of reaching into the
unexported traceID.value field. This compares trace IDs by their
semantic hex value regardless of hex-cache state (a local span has a
cold cache, an extracted context a hot one), which is more
intention-revealing than a raw byte-field comparison.
newSpanContext deliberately does not finalize the traceID hex cache, so
locally started spans use the non-caching HexEncoded fallback and allocate
on each HexEncoded/UpperHex call (e.g. per Inject). This is an intentional
choice to keep span creation allocation-free at the cost of per-call hex
allocation on the propagation path. Document it at newSpanContext and
correct the HexEncoded doc so the cold-cache path is described as the normal
state for local spans rather than an edge case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI Generated Largely based on code generated by an AI or LLM. This label is the same across all dd-trace-* repos mergequeue-status: done performance/ignore-performance-regression team:apm-go

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants