Skip to content

fix(ddtrace/tracer): cache trace ID hex encoding#4481

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 10 commits into
mainfrom
dario.castane/langplat-59/upperhex
Mar 12, 2026
Merged

fix(ddtrace/tracer): cache trace ID hex encoding#4481
gh-worker-dd-mergequeue-cf854d[bot] merged 10 commits into
mainfrom
dario.castane/langplat-59/upperhex

Conversation

@darccio

@darccio darccio commented Feb 27, 2026

Copy link
Copy Markdown
Member

What does this PR do?

Introduces "caching" to trace ID hex encoding.

Motivation

Avoid the allocation of million of strings, as it was recreated every time the trace ID was required in its hexadecimal string form.

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.

Unsure? Have a question? Request a review!

@darccio
darccio requested review from a team as code owners February 27, 2026 14:04
@darccio

darccio commented Feb 27, 2026

Copy link
Copy Markdown
Member Author

Linting issues - coming from main - are addressed on #4480.

Comment thread ddtrace/tracer/spancontext.go
@codecov

codecov Bot commented Feb 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.60870% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.97%. Comparing base (7a80388) to head (a0f636b).

Files with missing lines Patch % Lines
ddtrace/tracer/spancontext.go 81.81% 4 Missing ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
ddtrace/tracer/textmap.go 84.04% <100.00%> (ø)
ddtrace/tracer/spancontext.go 87.98% <81.81%> (ø)

... and 387 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.

@pr-commenter

pr-commenter Bot commented Feb 27, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-03-12 10:16:07

Comparing candidate commit a0f636b in PR branch dario.castane/langplat-59/upperhex with baseline commit 7a80388 in branch main.

Found 2 performance improvements and 0 performance regressions! Performance is the same for 154 metrics, 8 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:BenchmarkInjectW3C-25

  • 🟩 allocated_mem [-48 bytes; -48 bytes] or [-4.580%; -4.580%]
  • 🟩 allocations [-2; -2] or [-22.222%; -22.222%]

@darccio
darccio marked this pull request as draft February 27, 2026 14:26
@darccio
darccio marked this pull request as ready for review February 27, 2026 21:32
Comment thread ddtrace/tracer/spancontext.go
@datadog-official

datadog-official Bot commented Mar 3, 2026

Copy link
Copy Markdown
Contributor

✅ Tests

🎉 All green!

❄️ No new flaky tests detected
🧪 All tests passed

🎯 Code Coverage (details)
Patch Coverage: 85.71%
Overall Coverage: 59.25%

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: a0f636b | Docs | Datadog PR Page | Was this helpful? React with 👍/👎 or give us feedback!

@kakkoyun kakkoyun left a comment

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.

I have one suggestion, otherwise LGTM

Comment thread ddtrace/tracer/spancontext.go Outdated
@darccio
darccio requested a review from kakkoyun March 10, 2026 10:18
@darccio

darccio commented Mar 10, 2026

Copy link
Copy Markdown
Member Author

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented Mar 10, 2026

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-03-10 10:58:12 UTC ℹ️ Start processing command /merge


2026-03-10 10:58:17 UTC ℹ️ MergeQueue: pull request added to the queue

The expected merge time in main is approximately 29m (p90).


2026-03-10 11:10:19 UTCMergeQueue: The checks failed on this merge request

Tests failed on this commit d3bb9b1:

What to do next?

  • Investigate the failures and when ready, re-add your pull request to the queue!
  • If your PR checks are green, try to rebase/merge. It might be because the CI run is a bit old.
  • Any question, go check the FAQ.

@darccio

darccio commented Mar 10, 2026

Copy link
Copy Markdown
Member Author

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented Mar 10, 2026

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-03-10 16:03:14 UTC ℹ️ Start processing command /merge


2026-03-10 16:03:21 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-03-10 20:16:19 UTC ⚠️ MergeQueue: This merge request was unqueued

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

@darccio

darccio commented Mar 11, 2026

Copy link
Copy Markdown
Member Author

/merge

@gh-worker-devflow-routing-ef8351

gh-worker-devflow-routing-ef8351 Bot commented Mar 11, 2026

Copy link
Copy Markdown

View all feedbacks in Devflow UI.

2026-03-11 16:01:03 UTC ℹ️ Start processing command /merge


2026-03-11 16:01:11 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-03-11 20:03:10 UTC ⚠️ MergeQueue: This merge request was unqueued

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

@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot merged commit 2693902 into main Mar 12, 2026
207 checks passed
@gh-worker-dd-mergequeue-cf854d
gh-worker-dd-mergequeue-cf854d Bot deleted the dario.castane/langplat-59/upperhex branch March 12, 2026 10:31
darccio added a commit that referenced this pull request May 4, 2026
darccio added a commit that referenced this pull request Jun 25, 2026
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jun 25, 2026
…#4726)

### 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 `computeAndCacheHex` → `cacheHex`, 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:

```go
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:41` ← `textmap.go:481` ← `propagating_tags.go:95` ← `textmap.go:463` (`injectTextMap` → `setPropagatingTag(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

- [x] Changed code has unit tests for its functionality at or near 100% coverage.
- [ ] [System-Tests](https://github.com/DataDog/system-tests/) covering this feature have been added and enabled with the va.b.c-dev version tag.
- [x] 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.
- [x] New code is free of linting errors. You can check this by running `make lint` locally.
- [x] 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.
- [x] All generated files are up to date. You can check this by running `make generate` locally.
- [x] 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.

Co-authored-by: kakkoyun <[email protected]>
Co-authored-by: hannahkm <[email protected]>
Co-authored-by: dario.castane <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants