Skip to content

fix(contrib): keep truncated span tags valid UTF-8 in Elasticsearch, OpenSearch and MongoDB - #5991

Open
ajgajg1134 wants to merge 2 commits into
mainfrom
andrew.glaude/elasticsearch-utf8-truncation
Open

ajgajg1134 wants to merge 2 commits into
mainfrom
andrew.glaude/elasticsearch-utf8-truncation

Conversation

@ajgajg1134

@ajgajg1134 ajgajg1134 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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)

  • It cuts s to at most limit bytes 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.
  • A string of exactly limit bytes may already be the result of a cut, as with a buffered Peek, so an incomplete rune at its end is dropped too.
  • It looks at no more than utf8.UTFMax (4) bytes at the end, the same bounded-tail approach as the Agent's TruncateUTF8 (pkg/util/strings/truncate.go and pkg/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.
  • One deliberate difference from the Agent: malformed trailing bytes that aren't a cut rune are left as they were. The Agent's loop keeps dropping bytes until the tail is valid, so on binary data it can walk back over the whole string.
  • It lives in instrumentation, the public package every contrib already imports for shared helpers, because contrib modules can't import the root module's internal/ packages. contrib/INTEGRATIONS.md now says to use it instead of s[:limit].

Integrations fixed

Integration Tags Before
elastic/go-elasticsearch.v6 (v6, v7 and v8 clients, plus Orchestrion) elasticsearch.body, error.message peek cut at 5 KiB by byte count
olivere/elastic.v5 elasticsearch.body, error.message same peek
opensearch-project/opensearch-go.v4 opensearch.body, error.message same cut in an older copy of peek
go.mongodb.org/mongo-driver and mongo-driver.v2 mongodb.query b[:maxQuerySize], only when WithMaxQuerySize is 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 a followed by € ended in \xe2, and mongo {"find":"café€😀"} cut inside the emoji ended in \xf0\x9f. The WithMaxQuerySize godoc now says a cut query may be up to 3 bytes shorter than the limit.

OpenSearch peek brought up to the Elasticsearch version. OpenSearch's peek was an older copy that never got the fixes the Elasticsearch copy has. This PR ports them:

  • Gzip size cap: decompressed output is now capped at the cutoff. Before, a small gzip-bomb error response inflated without limit into error.message; a test measured 4 MiB in the tag.
  • Header casing: Content-Encoding is matched case-insensitively (RFC 9110 8.4.1). Before, GZip put the raw compressed bytes in the tag.
  • Which header: the error response is decoded using the response's own Content-Encoding, not the request's. Before, a gzip error response to an uncompressed request put the raw compressed bytes in error.message, which is another source of invalid UTF-8.

I checked every other place that truncates and found nothing else at risk:

  • azure/apim-callout cuts base64 text, which is always ASCII.
  • valkey-go and redis/rueidis cut the list of commands, not strings.
  • instrumentation/mcp cuts by character, not by byte.
  • The tracer's baggage helper cuts on character boundaries.
  • The AppSec WAF exception message is already cleaned with strings.ToValidUTF8.
  • internal/appsec/body passes 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:

  • Proven (code and tests): the integrations above produce invalid UTF-8 tags from valid UTF-8 input whenever the byte limit falls inside a multi-byte rune. The tracer's v1.0 encoder (ddtrace/tracer/payload_v1.go, msgp.AppendString) writes tag strings as they are, so these bytes reach the wire unchanged.
  • Not verified: which integration, if any of these, produced the customer's rejected payloads. Their payloads were not available, and any other tag carrying invalid UTF-8 would produce the same rejection. Input that is not valid UTF-8 to begin with (binary bodies, malformed strings) is not repaired by this PR.

Testing

Each new test was run against the code on main to confirm it catches the bug, and against this branch to confirm the fix:

Test On main On this branch
instrumentation TestTruncateUTF8: 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 string (new) pass
go-elasticsearch TestPeekUTF8, TestRoundTripperUTF8BodyCutoff 27 subtests fail (every cut inside a rune) pass
olivere TestPeekUTF8, TestHTTPClientUTF8BodyCutoff 27 fail pass
opensearch TestPeekUTF8 (raw, Content-Length, gzip, not-really-gzip, exact boundary) 27 fail pass
opensearch TestPerformUTF8BodyCutoff (end-to-end through Client.Perform) 6 fail (cuts inside a rune) pass
opensearch TestPeekGzip (bomb inside and beyond the peek window, header casing) 3 fail pass
opensearch TestPerformGzipErrorResponse (gzip response to an uncompressed request, bomb, gzip request with a plain response) 2 fail; the gzip-request case already passed and stays as a guard pass
mongo v1 and v2 TestMaxQuerySizeUTF8 (default, 0 means no tag, a cut inside a rune, every limit) 7 fail in each pass

Benchmarks (benchstat, n=6, Apple M4 Max):

BenchmarkTruncateUTF8/ascii-16       1.775 ns/op   0 B/op   0 allocs/op   (10 KiB input, 5 KiB limit)
BenchmarkTruncateUTF8/multibyte-16   2.001 ns/op   0 B/op   0 allocs/op

go-elasticsearch BenchmarkPeek, main vs this PR:
Peek/ascii-16       1.508µ ± 24%   1.492µ ± 18%   ~ (p=0.937)   10.67Ki → 10.67Ki   6 → 6 allocs
Peek/multibyte-16   1.199µ ±  3%   1.211µ ±  5%   ~ (p=0.619)   10.67Ki → 10.67Ki   6 → 6 allocs

Commands that passed locally. The elastic, olivere and mongo packages skip every test unless INTEGRATION is set, so those runs use filters that exclude the tests needing live services:

go test -race ./instrumentation/
go test -race ./contrib/opensearch-project/opensearch-go.v4/...            # full suite
INTEGRATION=1 go test -race -run 'TestPeek|TestQuantize|TestRoundTripper' ./contrib/elastic/go-elasticsearch.v6/
INTEGRATION=1 go test -race -run 'TestPeek|TestQuantize|TestHTTPClient'   ./contrib/olivere/elastic.v5/
INTEGRATION=1 go test -race -run 'TestMaxQuerySizeUTF8'                   ./contrib/go.mongodb.org/mongo-driver/mongo/ ./contrib/go.mongodb.org/mongo-driver.v2/mongo/
golangci-lint run ./instrumentation/...                                    # v2.15.0: 0 issues
./scripts/lint_go_modules.sh origin/main                                   # 0 issues in all 5 nested modules
go run ./scripts/check_copyright.go

The tests against live Elasticsearch, MongoDB and OpenSearch and the internal/orchestrion/_integration suites 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:ecosystem label.

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. (N/A)
  • 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. (N/A)
  • 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. (no generated files touched)
  • Non-trivial go.mod changes, e.g. adding new modules, are reviewed by DataDog/dd-trace-go-guild. (N/A, no go.mod changes)

🤖 Generated with Claude Code

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>
@ajgajg1134 ajgajg1134 added the apm:ecosystem contrib/* related feature requests or bugs label Nov 25, 2026
@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  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

@datadog-prod-us1-6

datadog-prod-us1-6 Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

❌ Errors

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

🚦 1 Pipeline job failed

Check Pull Request CI Status | all-jobs-are-green

View more details · View in GitHub Actions

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 74.21% (+11.66%)

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>
@ajgajg1134 ajgajg1134 changed the title fix(contrib/elastic): don't split UTF-8 runes when truncating Elasticsearch bodies fix(contrib): keep truncated span tags valid UTF-8 in Elasticsearch, OpenSearch and MongoDB Nov 25, 2026
@dd-octo-sts dd-octo-sts Bot mentioned this pull request Nov 25, 2026
@ajgajg1134
ajgajg1134 marked this pull request as ready for review November 25, 2026 17:37
@ajgajg1134
ajgajg1134 requested review from a team as code owners November 25, 2026 17:37
@ajgajg1134
ajgajg1134 requested review from rarguelloF and removed request for a team November 25, 2026 17:37
@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-25T17:38:24.619200Z 1bd38a8 Draft marked ready
ℹ️ 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.

@pr-commenter

pr-commenter Bot commented Nov 25, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-25 17:42:47

Comparing candidate commit 1bd38a8 in PR branch andrew.glaude/elasticsearch-utf8-truncation with baseline commit 60da1f7 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 416 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 ----------------------------------'

@datadog-prod-us1-6 datadog-prod-us1-6 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.

Bits Code Review: FAIL

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.

Open Bits AI session

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apm:ecosystem contrib/* related feature requests or bugs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant