Skip to content

feat(opentelemetry): export runtime metrics over OTLP - #21610

Draft
MilanGarnier wants to merge 1 commit into
mainfrom
milan.garnier/otlp-runtime-metrics
Draft

MilanGarnier wants to merge 1 commit into
mainfrom
milan.garnier/otlp-runtime-metrics

Conversation

@MilanGarnier

Copy link
Copy Markdown
Contributor

Description

When both DD_RUNTIME_METRICS_ENABLED=true and DD_METRICS_OTEL_ENABLED=true are set, Python runtime metrics are now exported over OTLP through the OpenTelemetry metrics API instead of being sent over DogStatsD.

The instruments are registered on the meter datadog.python.runtime and follow the names, units and attributes of opentelemetry-instrumentation-system-metrics:

Instrument Name Unit Attributes
ObservableCounter process.cpu.time s type: system/user
ObservableGauge process.cpu.utilization 1
ObservableCounter process.context_switches {context_switch} type: voluntary/involuntary (unsupported types omitted)
ObservableUpDownCounter process.memory.usage By
ObservableUpDownCounter process.thread.count {thread}
ObservableCounter cpython.gc.collections {collection} cpython.gc.generation
ObservableCounter cpython.gc.collected_objects {object} cpython.gc.generation
ObservableCounter cpython.gc.uncollectable_objects {object} cpython.gc.generation
ObservableCounter process.runtime.cpython.gc_count {object} count

How it works:

  • RuntimeWorker still starts at bootstrap. In OpenTelemetry mode its first periodic run (not bootstrap) calls otlp_runtime_metrics.start(), which sets up the ddtrace MeterProvider (once, through the new ensure_otel_meter_provider()) and registers the instruments. Deferring to the worker thread keeps the OpenTelemetry SDK and exporter out of the preload phase, so they are not unloaded by the bootstrap module cleanup and are imported after an application's gevent patch_all().
  • If ddtrace could not configure a provider (exporter missing, provider set by the application), the instruments go on the application's MeterProvider when one is installed. If there is no usable provider at all, the worker keeps sending the existing DogStatsD metrics.
  • Once OTLP export starts, the DogStatsD collectors are stopped and dogstatsd_url is ignored (logged at debug level). DogStatsD flushes are skipped while the OTLP start is pending, so the two paths never both report.
  • CPU time and context switch totals are accumulated from per-read deltas, and their baseline resets after fork. The counters therefore never decrease in a forked child, which the SDK's delta temporality would otherwise turn into negative deltas.
  • RuntimeWorker.disable() makes the callbacks observe nothing; re-enabling reuses the registered instruments.

Testing

New tests in tests/opentelemetry/test_metrics.py:

  • end-to-end export under ddtrace-run over gRPC and HTTP/protobuf, checking the metric names, the meter scope, the absence of runtime.python.* names, and that the SDK is not imported at bootstrap;
  • instrument kinds, units, monotonicity and attributes through an InMemoryMetricReader, plus disable/re-enable and dogstatsd_url being ignored;
  • gating over DD_RUNTIME_METRICS_ENABLED × DD_METRICS_OTEL_ENABLED × OTEL_METRICS_EXPORTER=none;
  • the DogStatsD fallback when the OTLP exporter is not installed;
  • counters staying monotonic across fork with delta temporality;
  • export after a gevent patch_all().

The OpenTelemetry suite passes across the OpenTelemetry SDK versions in the test matrix. One tracer suite test (test_runtime_worker_flush_keeps_automatic_gc_running) fails locally on a DogStatsD "Connection refused" stderr line; it fails the same way on main.

Risks

  • process.runtime.cpython.gc_count is reported as an ObservableCounter, as upstream does, but gc.get_count() drops after each collection, so cumulative-to-delta conversion can produce negative values for it.
  • GC pause time metrics (runtime.python.gc.pause*) have no OpenTelemetry equivalent and are not exported in OTLP mode.
  • The OTLP start happens on the worker's first run (about 10 s after startup). An application that calls gevent patch_all() later than that would import the SDK before patching.
  • OTEL_SDK_DISABLED=true is not handled here. It will be addressed in a separate change.

Additional Notes

The upstream system metrics instrumentation is not used directly because it depends on psutil; the values come from the existing native process metrics collector and gc.

🤖 Generated with Claude Code

@cit-pr-commenter-54b7da

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/bootstrap/preload.py                                            @DataDog/python-guild @DataDog/apm-core-python
ddtrace/internal/opentelemetry/metrics.py                               @DataDog/apm-sdk-capabilities
ddtrace/internal/runtime/otlp_runtime_metrics.py                        @DataDog/apm-sdk-capabilities
ddtrace/internal/runtime/runtime_metrics.py                             @DataDog/apm-sdk-capabilities
docs/configuration.rst                                                  @DataDog/python-guild
releasenotes/notes/otlp-runtime-metrics-cee27a1d10138402.yaml           @DataDog/apm-python
tests/opentelemetry/test_metrics.py                                     @DataDog/apm-sdk-capabilities

@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Dependency direction analysis

🚨 New dependency direction violations detected 🚨

1 new violation(s) of the dependency direction rules have been introduced by this PR:

ddtrace.internal.runtime.otlp_runtime_metrics -×-> ddtrace.internal.opentelemetry.metrics  (product:runtime -> product:opentelemetry, score=3)

ddtrace.internal and ddtrace.contrib must not depend on product code, and products must not depend on each other directly. See the dependency-direction-analysis skill for how to fix this.

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 83 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=120)
ddtrace.llmobs._integrations.vllm -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.litellm -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._evaluators.runner -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.openai -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)

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

datadog-prod-us1-3 Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

✨ Unblock PR with BitsAI

❌ Errors

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

🚦 2 Pipeline jobs failed

DDCI - DataDog/dd-trace-py | detect_layering_violations — 🔧 Needs a code fix, caused by this PR

View more details · View in DDCI

DataDog/apm-reliability/dd-trace-py | detect_layering_violations — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

Useful? React with 👍 / 👎

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

@pr-commenter

pr-commenter Bot commented Nov 9, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-09 17:27:12

Comparing candidate commit fd9c5dc in PR branch milan.garnier/otlp-runtime-metrics with baseline commit 046db0a in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 606 metrics, 9 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 [-730.811ns; +688.560ns] or [-6.804%; +6.411%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1867.169ns; +1830.391ns] or [-9.311%; +9.127%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1870.683ns; +1664.021ns] or [-9.595%; +8.535%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-347.239ns; +375.044ns] or [-8.036%; +8.679%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-215.895ns; +223.710ns] or [-7.926%; +8.213%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-92.154ns; +86.271ns] or [-6.168%; +5.775%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4828.298ns; +4649.079ns] or [-9.497%; +9.145%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-929.879ns; +998.549ns] or [-8.679%; +9.320%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-51.860µs; +59.682µs] or [-8.936%; +10.284%]

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