Skip to content

fix(telemetry): make the metric recorder lock reentrant - #22033

Open
dubloom wants to merge 2 commits into
mainfrom
louis.tricot/telemetry-recorder-rlock
Open

dubloom wants to merge 2 commits into
mainfrom
louis.tricot/telemetry-recorder-rlock

Conversation

@dubloom

@dubloom dubloom commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Why

  • Some integrations finish spans from a garbage-collection callback (weakref.finalize): grpc, google_adk, openai realtime.
  • Finishing a span records a telemetry metric, which takes _recorder_lock.
  • The garbage collector can run that callback on a thread that already holds _recorder_lock.
  • The lock was not reentrant, so that thread would wait on itself forever (deadlock).

What

Customer impact

Removes a rare hang of an application thread. No hang has been reported. Release note added.

Testing

  • New test: take the lock, then record a metric. It runs in a subprocess with a timeout.
    • Old lock: times out (deadlock).
    • New lock: passes.
  • tests/telemetry/ passes locally.

Risks

Low. Only the lock type changes. It is still reset in the child after a fork.

🤖 Generated with Claude Code

Span finish records telemetry metrics through _recorder_lock, and
integrations finish spans from weakref.finalize callbacks. The cyclic GC
can run such a finalizer on a thread that already holds the lock, which
deadlocked that thread on the non-reentrant lock. Use forksafe.RLock().
@dubloom dubloom added the changelog/no-changelog A changelog entry is not required for this PR. label Nov 23, 2026
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/internal/telemetry/metrics.py                                   @DataDog/apm-python
releasenotes/notes/fix-telemetry-recorder-lock-deadlock-bde085679499a81b.yaml  @DataDog/apm-python
tests/telemetry/test_telemetry_metrics.py                               @DataDog/apm-core-python @DataDog/apm-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 22 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 22 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=103)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.internal.span_bus -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=35)
ddtrace.llmobs._llmobs -×-> ddtrace._trace.span  (product:llmobs -> product:tracing, score=33)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@datadog-prod-us1-4

datadog-prod-us1-4 Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 1ecc5ea | Docs | View more details | Give us feedback!

@dubloom dubloom removed the changelog/no-changelog A changelog entry is not required for this PR. label Nov 23, 2026
@dubloom
dubloom marked this pull request as ready for review November 23, 2026 16:46
@dubloom
dubloom requested review from a team as code owners November 23, 2026 16:46
@dubloom
dubloom requested review from emmettbutler and removed request for a team November 23, 2026 16:46
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T16:47:57.611479Z 1ecc5ea 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.

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

Bits Code Review: FAIL

The reentrant lock lets a GC finalizer finish a span without waiting on its own thread. If the callback reenters recorder creation or first-write registration for the same metric, span counts can split across duplicate native contexts.

Open Bits AI session

🤖 Bits Code Review · Commit 1ecc5ea

# Guards the registry and every transition of a recorder's binding.
_recorder_lock = forksafe.Lock()
# Reentrant: GC finalizers that finish spans can record metrics on a thread already holding it.
_recorder_lock = forksafe.RLock()

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 Keep first writes on one metric context during GC reentry

If cyclic GC finishes another span for the same integration during the first write to a pending spans_finished recorder, the reentrant lock lets the nested write enter while the recorder still points to the pending worker. Both writes then register a native context for the same metric and send their points under different context keys, splitting telemetry that should aggregate together. The static reviewer reproduced the two registrations with a fake worker. The fix needs to handle nested writes during registration while preserving both points.

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

# Guards the registry and every transition of a recorder's binding.
_recorder_lock = forksafe.Lock()
# Reentrant: GC finalizers that finish spans can record metrics on a thread already holding it.
_recorder_lock = forksafe.RLock()

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 recorder deduplication when GC reenters creation

If a GC finalizer requests the same spans_finished metric after the outer registry lookup misses and before it inserts a recorder, the nested call can create and use its own recorder. The outer call then overwrites the registry entry with a second recorder. With an active worker, both recorders can register distinct contexts for the same metric and split its span counts. The static reviewer reproduced the duplicate creation with a fake worker. Recorder creation needs to preserve the entry installed by the nested call.

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

@pr-commenter

pr-commenter Bot commented Nov 23, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-23 17:08:51

Comparing candidate commit 1ecc5ea in PR branch louis.tricot/telemetry-recorder-rlock with baseline commit 0b0ac82 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 622 metrics, 10 unstable metrics, 1 flaky benchmarks without significant changes.

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

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-556.059ns; +856.805ns] or [-5.212%; +8.031%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-29.346ns; +44.572ns] or [-4.599%; +6.984%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1461.988ns; +2211.719ns] or [-7.380%; +11.164%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1953.176ns; +1589.879ns] or [-9.988%; +8.130%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-193.423ns; +542.808ns] or [-4.580%; +12.853%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-96.459ns; +345.299ns] or [-3.653%; +13.077%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-85.054ns; +90.357ns] or [-6.161%; +6.546%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4553.876ns; +4468.343ns] or [-9.332%; +9.157%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-900.695ns; +936.296ns] or [-8.712%; +9.056%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-42.921µs; +69.932µs] or [-7.411%; +12.075%]

Known flaky benchmarks

These benchmarks are marked as flaky and will not trigger a failure. Modify FLAKY_BENCHMARKS_REGEX to control which benchmarks are marked as flaky.

Known flaky benchmarks without significant changes:

  • scenario:packagespackageforrootmodulemapping-cache_off

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