fix(ddtrace/tracer): cache trace ID hex encoding#4481
fix(ddtrace/tracer): cache trace ID hex encoding#4481gh-worker-dd-mergequeue-cf854d[bot] merged 10 commits into
Conversation
|
Linting issues - coming from |
Codecov Report❌ Patch coverage is
Additional details and impacted files
🚀 New features to boost your workflow:
|
BenchmarksBenchmark execution time: 2026-03-12 10:16:07 Comparing candidate commit a0f636b in PR branch Found 2 performance improvements and 0 performance regressions! Performance is the same for 154 metrics, 8 unstable metrics.
|
… hex encoding retrieval
|
✅ Tests 🎉 All green!❄️ No new flaky tests detected 🎯 Code Coverage (details) 🔗 Commit SHA: a0f636b | Docs | Datadog PR Page | Was this helpful? React with 👍/👎 or give us feedback! |
kakkoyun
left a comment
There was a problem hiding this comment.
I have one suggestion, otherwise LGTM
|
/merge |
|
View all feedbacks in Devflow UI.
The expected merge time in
Tests failed on this commit d3bb9b1: What to do next?
|
|
/merge |
|
View all feedbacks in Devflow UI.
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.
devflow unqueued this merge request: It did not become mergeable within the expected time |
|
/merge |
|
View all feedbacks in Devflow UI.
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.
devflow unqueued this merge request: It did not become mergeable within the expected time |
…#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]>
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
make lintlocally.make testlocally.make generatelocally.make fix-moduleslocally.Unsure? Have a question? Request a review!