Repository navigation
fix(contrib): keep truncated span tags valid UTF-8 in Elasticsearch, OpenSearch and MongoDB - #5991
ajgajg1134 wants to merge 2 commits into
Conversation
peek cut request and error-response bodies at a fixed byte limit (bodyCutoff, 5 KiB). When the limit fell inside a multi-byte rune, the elasticsearch.body and error.message tags ended in a partial rune and were invalid UTF-8 even though the body was valid. Drop a trailing rune that was cut short, inspecting at most utf8.UTFMax bytes at the end. The snippet stays within the byte limit, ASCII and untruncated bodies are unchanged, and the forwarded body is untouched. Applied to both go-elasticsearch.v6 and olivere/elastic.v5, which carry identical copies of peek. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Config Audit |
❌ ErrorsYour PR has failed checks. Please review the issues below and take necessary action before merging. 🚦 1 Pipeline job failed
ℹ️ InfoNo other issues found (see more)🧪 All tests passed 🎯 Code Coverage (details) Useful? React with 👍 / 👎 This comment will be updated automatically if new data arrives.🔗 Commit SHA: 1bd38a8 | Docs | View more details | Give us feedback! |
Add instrumentation.TruncateUTF8, which cuts a string to a byte limit without splitting a multi-byte UTF-8 rune, and use it everywhere an integration cuts a span tag value at a byte limit: - go-elasticsearch.v6 and olivere/elastic.v5 peek now use it instead of their local trimPartialRune copies. - opensearch-go.v4 peek had the same raw byte cut on opensearch.body and error.message. - mongo-driver and mongo-driver.v2 cut mongodb.query with b[:maxQuerySize] when WithMaxQuerySize is set. OpenSearch's peek was an older copy of the Elasticsearch one, so also port the fixes the Elasticsearch copy already has: bound the decompressed gzip snippet by the cutoff, match Content-Encoding case-insensitively, and decode the error response with the response's own Content-Encoding instead of the request's. Without the last one, a gzip error response to an uncompressed request put the raw compressed bytes in error.message. Document the helper in contrib/INTEGRATIONS.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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. |
BenchmarksBenchmark execution time: 2026-11-25 17:42:47 Comparing candidate commit 1bd38a8 in PR branch Found 0 performance improvements and 0 performance regressions! Performance is the same for 416 metrics, 0 unstable metrics.
|
There was a problem hiding this comment.
A memory-retention issue exists in the MongoDB monitor integration where large commands exceeding WithMaxQuerySize are fully allocated as strings before truncation, causing multi-megabyte allocations to be retained per span. The fix requires capping the byte slice before converting to a string, then applying TruncateUTF8, in both the v1 and v2 mongo-driver integrations.
🤖 Bits Code Review · Commit 1bd38a8
| b, _ := bson.MarshalExtJSON(evt.Command, false, false) | ||
| if m.cfg.maxQuerySize > 0 && len(b) > m.cfg.maxQuerySize { | ||
| b = b[:m.cfg.maxQuerySize] | ||
| query := string(b) |
There was a problem hiding this comment.
Bound MongoDB bytes before allocating the query string
With a positive WithMaxQuerySize and a command larger than that limit, string(b) now allocates the entire serialized query before truncation. TruncateUTF8 returns a substring, and the span stores that string without copying it, retaining the full allocation. A multi-megabyte query capped at 1 KiB therefore retains megabytes instead of approximately 1 KiB. Bound the byte slice before converting it to a string, then trim any incomplete rune. Apply the same fix in the mongo-driver.v2 integration.
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
What does this PR do?
Keeps span tags valid UTF-8 when integrations cut them to a byte limit. It adds one shared helper and fixes every integration that cut a tag at a raw byte offset.
New:
instrumentation.TruncateUTF8(s string, limit int) string(instrumentation/truncate.go)sto at mostlimitbytes and drops a rune that the cut would split, so valid UTF-8 stays valid. The result is never longer than before, and is shorter by at most 3 bytes.limitbytes may already be the result of a cut, as with a bufferedPeek, so an incomplete rune at its end is dropped too.utf8.UTFMax(4) bytes at the end, the same bounded-tail approach as the Agent'sTruncateUTF8(pkg/util/strings/truncate.goandpkg/trace/traceutil/normalize/truncate.go, at DataDog/datadog-agent@2491a04). It does not scan the whole string, and takes about 2 ns with no allocations.instrumentation, the public package every contrib already imports for shared helpers, because contrib modules can't import the root module'sinternal/packages.contrib/INTEGRATIONS.mdnow says to use it instead ofs[:limit].Integrations fixed
elastic/go-elasticsearch.v6(v6, v7 and v8 clients, plus Orchestrion)elasticsearch.body,error.messagepeekcut at 5 KiB by byte countolivere/elastic.v5elasticsearch.body,error.messagepeekopensearch-project/opensearch-go.v4opensearch.body,error.messagepeekgo.mongodb.org/mongo-driverandmongo-driver.v2mongodb.queryb[:maxQuerySize], only whenWithMaxQuerySizeis set (off by default)In each case a multi-byte rune straddling the limit left a partial rune at the end of the tag. For example, OpenSearch with 5119
afollowed by€ended in\xe2, and mongo{"find":"café€😀"}cut inside the emoji ended in\xf0\x9f. TheWithMaxQuerySizegodoc now says a cut query may be up to 3 bytes shorter than the limit.OpenSearch
peekbrought up to the Elasticsearch version. OpenSearch'speekwas an older copy that never got the fixes the Elasticsearch copy has. This PR ports them:error.message; a test measured 4 MiB in the tag.Content-Encodingis matched case-insensitively (RFC 9110 8.4.1). Before,GZipput the raw compressed bytes in the tag.Content-Encoding, not the request's. Before, a gzip error response to an uncompressed request put the raw compressed bytes inerror.message, which is another source of invalid UTF-8.I checked every other place that truncates and found nothing else at risk:
azure/apim-calloutcuts base64 text, which is always ASCII.valkey-goandredis/rueidiscut the list of commands, not strings.instrumentation/mcpcuts by character, not by byte.strings.ToValidUTF8.internal/appsec/bodypasses the cut body to the WAF, not straight into a span tag.Motivation
APMS-21104: a customer on dd-trace-go v2.12 with trace protocol v1.0 has payloads rejected with
tracer_payload_invalid_utf8. Switching to protocol v0.4 stops the drops, because the Agent repairs strings on that path.What this PR proves, and what it doesn't:
ddtrace/tracer/payload_v1.go,msgp.AppendString) writes tag strings as they are, so these bytes reach the wire unchanged.Testing
Each new test was run against the code on
mainto confirm it catches the bug, and against this branch to confirm the fix:maininstrumentationTestTruncateUTF8: 2-, 3- and 4-byte runes at every cut position, both as an over-long string and as an already-cut peek; ASCII, exact boundary, empty, zero and negative limit, malformed input unchanged; a check of every limit over a mixed stringTestPeekUTF8,TestRoundTripperUTF8BodyCutoffTestPeekUTF8,TestHTTPClientUTF8BodyCutoffTestPeekUTF8(raw, Content-Length, gzip, not-really-gzip, exact boundary)TestPerformUTF8BodyCutoff(end-to-end throughClient.Perform)TestPeekGzip(bomb inside and beyond the peek window, header casing)TestPerformGzipErrorResponse(gzip response to an uncompressed request, bomb, gzip request with a plain response)TestMaxQuerySizeUTF8(default,0means no tag, a cut inside a rune, every limit)Benchmarks (benchstat, n=6, Apple M4 Max):
Commands that passed locally. The elastic, olivere and mongo packages skip every test unless
INTEGRATIONis set, so those runs use filters that exclude the tests needing live services:The tests against live Elasticsearch, MongoDB and OpenSearch and the
internal/orchestrion/_integrationsuites were not run locally; CI covers them.Release notes: none needed beyond this PR's title. They are generated from PR titles and the
apm:ecosystemlabel.Reviewer's Checklist
make lintlocally.make testlocally.make generatelocally. (no generated files touched)DataDog/dd-trace-go-guild. (N/A, no go.mod changes)🤖 Generated with Claude Code