Skip to content

fix(android): bound the Datadog context read used for tracing headers - #1329

Open
c-tshibas wants to merge 3 commits into
DataDog:developfrom
c-tshibas:corneille/android-bounded-context-read
Open

c-tshibas wants to merge 3 commits into
DataDog:developfrom
c-tshibas:corneille/android-bounded-context-read

Conversation

@c-tshibas

@c-tshibas c-tshibas commented Nov 26, 2026 •

Copy link
Copy Markdown

What and why?

On Android, apps can freeze with an "App Not Responding" (ANR) error when they send
requests to a first-party host:

  1. For each first-party request, the plugin needs the RUM session, user and account IDs for
    the tracing headers.
  2. It asks the Android SDK for them and waits on the main thread, with no time limit.
  3. The Android SDK answers from one background thread that also processes every RUM event,
    one at a time.
  4. On slow devices, especially at app start, that queue can take more than 5 seconds. The main
    thread is still waiting, so Android reports an ANR.
java.util.concurrent.FutureTask.get
com.datadog.android.core.internal.utils.ConcurrencyExtKt.getSafe
com.datadog.android.core.internal.DatadogCore.getDatadogContext
com.datadoghq.flutter.DatadogSdkPlugin$Companion.getCoreContext

Why the fix is in the plugin: an ANR needs a busy SDK thread and a main thread
waiting on it. A busy SDK thread alone doesn't freeze the app. Native Android code never waits
on it from the main thread, and in testing a request to a host that isn't first-party didn't
freeze even with the SDK thread held for 6 s. So this PR limits the wait.

How?

getCoreContext() now goes through a new CoreContextReader. It asks the SDK on a
background thread and waits at most 100 ms for the answer.

What the request gets:

Situation Tracing headers include
Answer arrives within 100 ms Session, user and account IDs (same as before)
Answer is late, but an earlier answer exists Session ID only
Answer is late, and there's no earlier answer No IDs

Two more rules:

  • One question at a time. If a question to the SDK is already waiting, new requests
    don't wait. They use the session ID from the earlier answer right away (no user or account
    IDs), so many requests started at once cost one 100 ms wait, not one each.
  • User and account IDs are never reused. The SDK applies user and account changes on the
    same busy thread, so an earlier answer can still hold a user who has since logged out. This
    keeps the clearUserInfo / clearAccountInfo promise that later traces won't include
    them, including when the change was made from native code.

The method signature doesn't change, so the Dart code and generated bindings stay the same.
The iOS plugin also avoids waiting on the SDK, by keeping a cached context.

Trade-offs

These only apply while the SDK thread is more than 100 ms behind:

  • No user or account IDs: requests sent during a stall have no user or account IDs in
    the baggage header.
  • First request at launch: if no answer has arrived yet, there's no session ID either,
    and the trace is sampled on its own instead of with its session.
  • Session ID can be one session behind: if the RUM session renews during a stall,
    requests use the previous session ID until the SDK catches up.

To consider: the "one question at a time" rule. While a question to the SDK is
waiting, every new request uses the earlier session ID, and the late answer isn't used for
any of them. If the session renewed in that window, those requests carry the previous
session ID, so their traces link to the old session and use its sampling decision.

The alternative is to let each new request also wait up to 100 ms for the pending answer.
That gives a better chance of a current session ID, but the waits add up again: 50
requests started together could block the main thread for about 5 s, which is an ANR. This
PR favours never freezing over an up-to-date session ID during a stall. Happy to revisit
if reviewers see it differently.

  • Timeout value: 100 ms is an estimate. A normal read takes under a millisecond, and the
    native Android tracing integration waits up to 1 s, but off the main thread. Happy to
    change it or make it configurable.
  • One extra thread: it only runs when needed and stops after 30 s idle.

Testing

  • 10 new unit tests in CoreContextReaderTest: normal read, timeouts, fallback without user
    and account IDs, one request at a time, no waiting while a read is in progress, recovery,
    failures, the SDK being stopped, and removing user and account from a real context.
  • All 89 Android plugin unit tests pass. ktlint and detekt are clean on the changed files.
  • Emulator test app with the SDK thread held for 6 s before a first-party request:
    • Before: the main thread froze for about 6 s on every run (12 of 12).
    • After: median 0.1 s, longest 0.8 s, none over 5 s. Tracing headers were still sent.

Related, outside this PR

This PR fixes the freeze by itself. These changes would make the SDK thread faster and could
be raised with the Android SDK team:

  1. Release InternalSdkCore.getDatadogContextFuture(). It's on the Android SDK's develop
    branch and would let callers set their own time limit. This plugin could then use it and
    drop its own thread.
  2. Reuse one SecureRandom in internal log sampling. SdkInternalLogger.sample() creates
    a new one on every call, which can be slow on low-end devices and runs on the same queue.
  3. Stop RUM events from holding the context thread. Each RUM event holds that thread until
    it's fully processed, which is why a burst at launch delays every read. This is a larger
    design change.

A batch addFeatureFlagEvaluations API in Flutter, which Android already has, would also
shorten the queue.

Review checklist

  • This pull request has appropriate unit and / or integration tests
  • This pull request references a Github or JIRA issue

🤖 Generated with Claude Code

Tracing headers for first-party requests read the Datadog context through
DatadogSdkPlugin.getCoreContext(), which waited with no timeout for the
SDK's single context thread. That thread also processes RUM events, so on
slow devices the wait from the Flutter UI thread could exceed the ANR
threshold.

getCoreContext() now uses CoreContextReader, which runs the read on a
background thread, waits at most 100 ms, and otherwise returns the last
context it read. Only one read runs at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@c-tshibas
c-tshibas requested a review from a team as a code owner November 26, 2026 15:48
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 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-26T16:41:07.005647Z 4f5a2aa New commits
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5db958c46f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +49 to +50
} catch (e: TimeoutException) {
lastKnownContext

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Invalidate cached identities when user/account information changes

After an identified context has been cached, calling clearUserInfo() or clearAccountInfo() and then making a first-party request whose context read exceeds 100 ms still returns the pre-clear IDs here. The native clear handlers only update Datadog; they never invalidate this reader. The Dart tracing path subsequently passes those cached IDs to mergeW3CBaggageHeader(), so requests with baggage propagation enabled can continue sending a logged-out user's user.id or cleared account.id. This violates the clear APIs' documented guarantee that following traces omit that information. Invalidate or sanitize cached identity fields on these mutations, and prevent an older in-flight read from restoring them.

Useful? React with 👍 / 👎.

@datadog-official datadog-official 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

The timeout fallback can resend cleared user and account IDs in tracing baggage after logout or an account switch, violating the clearing APIs’ documented behavior.

Open Bits AI session

🤖 Bits Code Review · Commit 5db958c

return try {
pendingRead.get(timeoutMs, TimeUnit.MILLISECONDS)
} catch (e: TimeoutException) {
lastKnownContext

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 Invalidate cleared identities before reusing cached context

After a successful context read, clearUserInfo() and clearAccountInfo() update the SDK without invalidating this cache. If a later context read exceeds 100 ms, the fallback returns the cleared IDs. AndroidDatadogFlutterPlugin.getContext() passes them through to tracing baggage, so requests after logout or an account switch can propagate the previous identity, contrary to the clearing APIs’ documented behavior. Invalidate cached identities when they change and prevent older in-flight reads from restoring them, or omit identity fields from fallback contexts. This requires coordinated cache, API-handler, and test changes.

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

c-tshibas and others added 2 commits November 26, 2026 16:24
When several first-party requests start together, each one reads the
context on the UI thread. After one read times out, later reads now
return the last known context straight away until that read finishes,
so a stalled read costs at most one wait instead of one per request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The SDK applies user and account changes on the context thread, so when
that thread is behind, an earlier context can still hold a user or account
that has since been cleared. A caller now gets user and account IDs only
from a read it started and that finished in time. Fallbacks keep the RUM
context but remove user and account information.

A caller that arrives while a read is in progress now gets the fallback
without waiting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@datadog-official datadog-official 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 caps Android tracing-context waits at 100 ms and returns immediately when another read is pending, preserving cached RUM context for fallback. The latest update removes user/account information from every fallback, fixing the earlier cleared-identity propagation issue; no findings remain open.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 4f5a2aa

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant