Skip to content

Fix Netty HTTP client context propagation on pooled connections - #13862

Open
mcculls wants to merge 3 commits into
masterfrom
mcculls/fix-netty-pooled-request-context
Open

mcculls wants to merge 3 commits into
masterfrom
mcculls/fix-netty-pooled-request-context

Conversation

@mcculls

@mcculls mcculls commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

What Does This Do

Preserve each request's context across Netty 4.1 HTTP client callbacks and prevent pooled connections from restoring context captured for an earlier request.

Response callbacks restore the full request context, including baggage, with the parent span active. Once an exchange completes, its context is cleared so later idle-channel callbacks no longer inherit the completed request's context.

Motivation

Pooled connections in the native ZIO HTTP client can propagate an earlier request's baggage and trace parent. The reproducer for #6772 exposed both connection-creation context overriding the current request and stale exchange state surviving connection reuse.

Additional Notes

Connection-creation context remains a fallback when the caller has only root or the bare noop span. Informational responses keep the exchange open, and WebSocket callbacks retain context across frames and recoverable errors. A new HTTP request resets the upgrade marker if HTTP resumes after a rejected handshake.

The hasAttr guards avoid creating empty attributes during cleanup. Netty's attr(key) creates an entry when absent, so an unconditional attr(key).getAndRemove() or attr(key).remove() would allocate and immediately discard an entry when no connection continuation or WebSocket upgrade marker exists. Checking presence first avoids this churn on reused requests and ordinary HTTP channels, at the cost of an extra lookup when the attribute is present.

Local validation covers baseline/latest Netty lifecycle tests, connection failures and WebSocket clients, plus a rebuilt-agent pooled ZIO reproducer checking legacy/W3C baggage and trace IDs with sequential and concurrent requests.

Netty 4.0 is outside this change's scope.

@mcculls mcculls added type: bug fix Bug fix inst: netty Netty instrumentation tag: ai generated Largely based on code generated by an AI or LLM labels Dec 5, 2026
@mcculls
mcculls marked this pull request as ready for review December 5, 2026 22:30
@mcculls
mcculls requested review from a team as code owners December 5, 2026 22:30
@mcculls
mcculls requested review from AlexeyKuznetsov-DD and ygree and removed request for a team December 5, 2026 22:30
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 5, 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-12-05T22:32:14.790375Z f85595a 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.

@mcculls
mcculls requested a review from amarziali December 5, 2026 22:30
@datadog-datadog-us1-prod

datadog-datadog-us1-prod Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 68.82% (+6.87%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: d3be3ff | Docs | Give us feedback!

@dd-octo-sts

dd-octo-sts Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

🟢 Java Benchmark SLOs — All performance SLOs passed

Suite Status
Startup 🟢 pass

SLO thresholds are defined here based on automatically generated metrics. A warning is raised when results are within 5% of the threshold.

PR vs. master results
Scenario Candidate master Δ (95% CI of mean)
startup:insecure-bank:iast:Agent 14.13 s 14.09 s [-0.4%; +1.0%] (no difference)
startup:insecure-bank:tracing:Agent 13.05 s 13.12 s [-1.4%; +0.3%] (no difference)
startup:petclinic:appsec:Agent 17.34 s 16.67 s [-0.3%; +8.4%] (no difference)
startup:petclinic:iast:Agent 17.15 s 17.26 s [-1.4%; +0.1%] (no difference)
startup:petclinic:profiling:Agent 16.80 s 16.21 s [-0.7%; +8.0%] (no difference)
startup:petclinic:sca:Agent 17.27 s 17.12 s [+0.0%; +1.7%] (maybe worse)
startup:petclinic:tracing:Agent 16.32 s 15.93 s [-1.8%; +6.7%] (no difference)

Commit: d3be3ff5 · CI Pipeline · Benchmarking Platform UI


Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion.

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

Informational-response callbacks reactivate the HTTP client span through Netty’s fire-method instrumentation, overriding the intended request-parent context and incorrectly parenting work started by those callbacks.

Open Bits AI session

🤖 Bits Code Review · Commit f85595a

@datadog-datadog-us1-prod datadog-datadog-us1-prod 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: PASS

More details

The PR preserves per-request context and baggage on pooled Netty 4.1 connections, clears completed exchanges, and retains WebSocket/CONNECT context as needed. The new callback marker fixes the earlier informational-response parenting defect while keeping the client span open for completion; no findings remain open.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 4c7171b

Prefer the current request context over connection-creation context and
clear completed exchanges before callbacks can reuse a channel. Restore
the full callback context while retaining unfinished client spans across
informational responses.

Preserve context through CONNECT tunnel setup and WebSocket callbacks,
and reset protocol state when HTTP requests resume. Cover request
precedence, terminal callbacks, reentrant writes, informational
responses, proxy tunnels, and WebSocket lifecycles.
@mcculls
mcculls force-pushed the mcculls/fix-netty-pooled-request-context branch 2 times, most recently from 9006e92 to 684d144 Compare December 5, 2026 23:20
Check whether a connection-continuation attribute exists before taking
or cancelling it. Netty's attr(key) creates an entry when absent, so the
presence check avoids creating and immediately removing an empty
attribute.
@mcculls
mcculls force-pushed the mcculls/fix-netty-pooled-request-context branch from 684d144 to afcf500 Compare December 5, 2026 23:22

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

Shared Netty callback advice can discard baggage added by server handlers when they forward events with a child span active, causing downstream callbacks and outbound requests to lose that baggage.

Open Bits AI session

🤖 Bits Code Review · Commit afcf500

Keep baggage added by server handlers while restoring the server span.
Continue restoring the captured request context for client events such
as TLS completion, which may arrive without that context active.

Cover downstream handler and outbound request baggage propagation when
a server handler forwards an event with a child span active.

@datadog-datadog-us1-prod datadog-datadog-us1-prod 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: PASS

More details

The PR fixes stale request context on pooled Netty 4.1 clients and restores callback baggage. Completed HTTP exchanges clear their context. The latest commit preserves handler-added baggage during server forwarding and adds regression coverage. No review findings remain open. Validation was static; tests were not executed and production telemetry was excluded.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit d3be3ff

}
if (finishSpan) {
// Keep the parent context for body chunks arriving after the client span finishes.
contextAttr.set(callbackContext);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Preserve handler-added baggage when forwarding streamed responses

When a 200 OK arrives as separate headers and body, this stores the request-parent context on the channel. A downstream handler can then add baggage, activate a child span, and forward the headers:

try (ContextScope ignored = Context.current().with(baggage).with(child).attach()) {
  ctx.fireChannelRead(msg);
}

FireAdvice sees the child span differ from the stored parent and attaches the entire saved context. The next handler sees no baggage added by the forwarding handler. This reproduced in both Netty test and latestDepTest with a DefaultHttpResponse followed by LastHttpContent. Could we preserve the live context while handlers forward a response, while still restoring the captured context for events such as TLS completion?

--- found with Codex

final Context storedContext = contextAttr.get();
final AgentSpan span = AgentSpan.fromContext(storedContext);
final boolean hasClientSpan = span != null && span != parent;
final Context callbackContext = storedContext == null ? parent : storedContext.with(parent);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 · Preserve active baggage when the channel has no stored exchange

With no stored exchange, attaching the fallback span as the entire context drops baggage already active on the caller. On a fresh client channel, I attached baggage and separately delivered an untracked response, fired an exception, and fired channelInactive. In both Netty test and latestDepTest, all three callbacks saw the expected noop span but read null for baggage.

Could we use Context.current().with(parent) when storedContext is absent, here and in finishExchange? That preserves the caller's baggage and still gives a bare noop span when the current context is root.

--- found with Codex

return null;
}
return activateSpan(channelSpan);
if (ServerRequestContext.currentRequest(ctx.channel()) != null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance · Avoid allocating a server request attribute on client channels

When a client event reaches this branch, currentRequest reads the server request queue through attr(key).get(). On a fresh client-only channel, Netty creates an entry even though there is no server request. I checked hasAttr(AttributeKey.valueOf("datadog.server.request.contexts")) before and after forwarding the first client response. It changed from false to true in both Netty test and latestDepTest.

Could we check hasAttr before looking up the server request queue so the client path avoids creating the empty attribute?

--- found with Codex

@AlexeyKuznetsov-DD AlexeyKuznetsov-DD left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pre-approving. Added couple of issues found by Codex.

This branch has not been deployed

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

Labels

inst: netty Netty instrumentation tag: ai generated Largely based on code generated by an AI or LLM type: bug fix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants