Skip to content

fix(id): reset OpenTelemetry and runtime metric state - #10343

Draft
litianningdatadog wants to merge 1 commit into
tianning.li/microvm-buffer-reset-04-otel-runtime-baselinefrom
tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets
Draft

litianningdatadog wants to merge 1 commit into
tianning.li/microvm-buffer-reset-04-otel-runtime-baselinefrom
tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets

Conversation

@litianningdatadog

@litianningdatadog litianningdatadog commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Complete the OpenTelemetry and runtime-metrics reset path for MicroVM identity refresh.

Motivation

This is a reviewable slice from the breakdown of monolithic PR #9814, tracked by SVLS-9768. A MicroVM identity refresh must not carry buffered, baseline, or pending exporter state into the next identity.

Changes

  • Reset OpenTelemetry metric instruments and periodic-reader state.
  • Reset OTLP and runtime metric state and cancel pending work.
  • Added coverage for metric reset and cancellation behavior.

Dependency tree

  • origin/master
    • #10338 01-common-exporter-agent-spanstats-reset-and-cancel
      • #10342 02-agentless-exporter-identity
      • #10341 06-datastream-reset-and-cancel
    • #10339 03-dogstatsd-buffer-reset
    • #10340 04-otel-runtime-baseline
      • #10343 05-otel-runtime-metric-resets ← current PR

This PR is intentionally draft and is part of the stacked review sequence above.

@dd-octo-sts

dd-octo-sts Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Overall package size

Self size: 8.97 MB
Deduped: 9.71 MB
No deduping: 9.71 MB

Dependency sizes | name | version | self size | total size | |------|---------|-----------|------------| | import-in-the-middle | 3.5.1 | 127.66 kB | 513.61 kB | | opentracing | 0.14.7 | 194.81 kB | 194.81 kB | | dc-polyfill | 0.1.11 | 25.74 kB | 25.74 kB |

🤖 This report was automatically generated by heaviest-objects-in-the-universe

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

⚠️ Warnings

Your PR has warnings. Tests failed — unable to determine if these are from required jobs.

🚦 4 Pipeline jobs failed

LLMObs | claude-agent-sdk — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

Project | lint — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

Project | lint-windows — 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

View all 4 failed jobs.

🧪 3 Tests failed in 1 job

LLMObs | claude-agent-sdk — ❌ 3 tests failed

View more details · View in GitHub Actions

❌ Plugin claude-agent-sdk with @anthropic-ai/claude-agent-sdk >=0.2.113 (0.3.268) instruments a full agentic call with subagents from with @anthropic-ai/claude-agent-sdk >=0.2.113 (0.3.268)   View in Datadog
Timeout of 15000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/runner/work/dd-trace-js/dd-trace-js/packages/datadog-plugin-claude-agent-sdk/test/index.spec.js)

Error: Timeout of 15000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/runner/work/dd-trace-js/dd-trace-js/packages/datadog-plugin-claude-agent-sdk/test/index.spec.js)
    at listOnTimeout (node:internal/timers:605:17)
    at process.processTimers (node:internal/timers:541:7)
❌ esm with @anthropic-ai/claude-agent-sdk >=0.2.113 (0.3.268) is instrumented named from with @anthropic-ai/claude-agent-sdk >=0.2.113 (0.3.268)   View in Datadog
Timeout of 30000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/runner/work/dd-trace-js/dd-trace-js/packages/datadog-plugin-claude-agent-sdk/test/integration-test/client.spec.js)

Error: Timeout of 30000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/runner/work/dd-trace-js/dd-trace-js/packages/datadog-plugin-claude-agent-sdk/test/integration-test/client.spec.js)
    at listOnTimeout (node:internal/timers:605:17)
    at process.processTimers (node:internal/timers:541:7)
❌ esm with @anthropic-ai/claude-agent-sdk >=0.2.113 (0.3.268) is instrumented named-from-namespace from with @anthropic-ai/claude-agent-sdk >=0.2.113 (0.3.268)   View in Datadog
Timeout of 30000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/runner/work/dd-trace-js/dd-trace-js/packages/datadog-plugin-claude-agent-sdk/test/integration-test/client.spec.js)

Error: Timeout of 30000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/runner/work/dd-trace-js/dd-trace-js/packages/datadog-plugin-claude-agent-sdk/test/integration-test/client.spec.js)
    at listOnTimeout (node:internal/timers:605:17)
    at process.processTimers (node:internal/timers:541:7)

ℹ️ Info

No other issues found (see more)

❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 87.48%

Useful? React with 👍 / 👎

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

@codecov

codecov Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (tianning.li/microvm-buffer-reset-04-otel-runtime-baseline@48c72fc). Learn more about missing BASE report.

Additional details and impacted files
@@                                     Coverage Diff                                      @@
##             tianning.li/microvm-buffer-reset-04-otel-runtime-baseline   #10343   +/-   ##
============================================================================================
  Coverage                                                             ?   87.50%           
============================================================================================
  Files                                                                ?     1015           
  Lines                                                                ?   156250           
  Branches                                                             ?       74           
============================================================================================
  Hits                                                                 ?   136728           
  Misses                                                               ?    19522           
  Partials                                                             ?        0           
Flag Coverage Δ
ai-guard 65.26% <ø> (?)
apm-capabilities 63.79% <100.00%> (?)
apm-integrations 81.58% <ø> (?)
appsec 58.94% <ø> (?)
debugger 70.23% <ø> (?)
instrumentation 54.46% <ø> (?)
llmobs 78.24% <ø> (?)
openfeature 66.51% <ø> (?)
platform 69.34% <0.00%> (?)
profiling 66.86% <ø> (?)
serverless 65.99% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@litianningdatadog litianningdatadog added the aws-microvm AWS MicroVM related features label Sep 15, 2026
@litianningdatadog
litianningdatadog requested a lite review from Copilot September 15, 2026 02:19
@litianningdatadog
litianningdatadog marked this pull request as ready for review September 15, 2026 02:21
@litianningdatadog
litianningdatadog requested review from a team as code owners September 15, 2026 02:21
@litianningdatadog
litianningdatadog requested review from khanayan123 and removed request for a team September 15, 2026 02:21
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-18T18:58:26.406405Z d185b6b New commits
🔒 Security Review ✅ Completed 2026-09-18T18:57:34.590929Z d185b6b 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.

Copilot AI 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.

🟡 Changes recommended

Unflushed aggregation state can cross identity refresh, and shutdown may still invoke observable callbacks.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Completes MicroVM identity-refresh resets for OpenTelemetry and runtime metrics.

Changes:

  • Resets metric reader state and observable baselines.
  • Drains native and GC runtime state.
  • Adds reset and cancellation coverage.
File summaries
File Summary
packages/dd-trace/test/runtime_metrics.spec.js Tests runtime metric reset behavior.
packages/dd-trace/test/opentelemetry/metrics.spec.js Tests OpenTelemetry metric reset behavior.
packages/dd-trace/src/runtime_metrics/runtime_metrics.js Moderate (2 votes): aggregation client state is not reset, allowing unflushed metrics to cross identity refresh.
packages/dd-trace/src/runtime_metrics/otlp_runtime_metrics.js Moderate (2 votes): OTLP aggregation client state is not reset, allowing unflushed metrics to cross identity refresh.
packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js Moderate (1 vote): shutdown retains observable instruments and the refresh subscription, potentially invoking callbacks after shutdown.
packages/dd-trace/src/opentelemetry/metrics/instruments.js Bounds observable metric collection.
Review details

Suppressed comments (1)

packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js:270

  • After shutdown(), #isShutdown remains true but the reader still retains observableInstruments, and the identity-refresh subscription in metrics/index.js is not removed. A refresh after shutdown will therefore execute every user observable callback through this new baseline collection even though the provider is shut down, potentially performing arbitrary user work; guard resetPendingState() for shutdown (or detach the subscription during shutdown).
      this.#collectObservableMeasurements(),
      this.#lastExportedState,
      this.#pendingObservableCounterBaselines
  • Files reviewed: 6/6 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.


// Discards any GC entries recorded but not yet delivered to the observer's callback, so a GC
// pause from just before the snapshot isn't attributed to the clone's first post-resume sample.
gcObserver?.takeRecords()
// Drains the addon's own CPU/event-loop/GC accumulators, which stats() otherwise reports as a
// delta since the last call - without this, the first post-resume capture would include
// pre-snapshot activity.
nativeMetrics?.stats()
@pr-commenter

pr-commenter Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-09-18 19:06:21

Comparing candidate commit d185b6b in PR branch tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets with baseline commit 48c72fc in branch tianning.li/microvm-buffer-reset-04-otel-runtime-baseline.

📊 Benchmarking dashboard

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

Unstable benchmarks

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

scenario:appsec-appsec-enabled-24

  • unstable max_rss_usage [-29.983MB; +6.587MB] or [-10.414%; +2.288%]

scenario:appsec-iast-no-vulnerability-iast-enabled-default-config-20

  • unstable max_rss_usage [-13254.191KB; +12992.591KB] or [-5.900%; +5.784%]

scenario:debugger-line-probe-with-snapshot-minimal-24

  • unstable max_rss_usage [-10.779MB; +13.424MB] or [-4.825%; +6.009%]

scenario:encoders-0.4-immediate-flush-20

  • unstable max_rss_usage [-3.205MB; +13.435MB] or [-4.198%; +17.594%]

scenario:llmobs-encode-unicode-mixed-20

  • unstable max_rss_usage [-11.957MB; +5.629MB] or [-15.022%; +7.072%]

scenario:plugin-graphql-long-with-depth-off-26

  • unstable max_rss_usage [-26.054MB; +34.155MB] or [-11.898%; +15.598%]

scenario:plugin-pg-service-26

  • unstable execution_time [-82.893ms; +91.304ms] or [-5.098%; +5.616%]

@litianningdatadog
litianningdatadog force-pushed the tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets branch from 3331733 to 82d6409 Compare September 17, 2026 20:58

@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: 82d6409ed0

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 254 to 255
resetPendingState () {
this.#measurements = []

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 Cancel in-flight metric exports during identity refresh

When an identity refresh occurs while exporter.export() still has an HTTP request in flight, this method clears only reader-owned state, so every resumed clone can complete the pre-snapshot metrics request. OtlpHttpExporterBase.resetPendingState() was added to cancel exactly these requests, and the log processor invokes it, but the metric reader never does; call the exporter reset here as well to prevent duplicated pre-refresh metrics.

Useful? React with 👍 / 👎.

Comment on lines +466 to +468
for (const instrument of this.observableInstruments) {
const remainingCapacity = maxMeasurements - measurements.length
const observableMeasurements = instrument.collect(remainingCapacity, onDrop)

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 Badge Reserve reset capacity for observable counter baselines

When gauges or observable up/down counters emit enough data points to fill the 65,536-measurement reset budget, this loop consumes all capacity on readings that resetObservableCounterBaselines() immediately ignores, so later ObservableCounters are never sampled at the refresh boundary. If those earlier instruments emit fewer points at the next periodic collection, a previously known counter loses that entire first post-resume interval via the pending-baseline path, while a newly appearing counter exports its process-lifetime absolute value under the clone identity; collect or prioritize only delta ObservableCounter readings here.

Useful? React with 👍 / 👎.

Comment on lines +522 to +523
if (type !== METRIC_TYPES.OBSERVABLECOUNTER || this.#getTemporality(type) !== TEMPORALITY.DELTA) {
continue

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 Rebase cumulative observable counters on identity refresh

When OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is CUMULATIVE or LOWMEMORY, this condition skips every ObservableCounter, so its next export still reports the callback's full pre-snapshot cumulative value under each clone's refreshed runtime ID. This directly affects the built-in nodejs.eventloop.time ObservableCounter as well as user counters; retain a refresh-time offset for cumulative counters and export values relative to it, analogous to the synchronous cumulative state reset.

Useful? React with 👍 / 👎.

@litianningdatadog
litianningdatadog force-pushed the tianning.li/microvm-buffer-reset-04-otel-runtime-baseline branch from 8d3615b to 8118609 Compare September 17, 2026 21:54
@litianningdatadog
litianningdatadog force-pushed the tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets branch 2 times, most recently from 52bc0b1 to f2fc0ab Compare September 17, 2026 22:39

@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: f2fc0ab560

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +730 to +731
const baseline = observableCounterBaselines.get(stateKey)
if (baseline !== undefined) dataPoint.value -= baseline

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 Badge Rebase cumulative series absent during refresh

When temporality is CUMULATIVE or LOWMEMORY and an ObservableCounter attribute series was exported before the snapshot but does not emit during resetPendingState(), the current revision's new baseline map has no entry for it; this condition therefore leaves its first returned process-lifetime value unchanged and reports pre-snapshot counts under the clone identity. Unlike the DELTA branch, cumulative counters have no deferred-baseline path, so previously seen cumulative series need to be tracked and their first post-refresh observation discarded or used as the new offset when no refresh sample was available.

Useful? React with 👍 / 👎.

@litianningdatadog
litianningdatadog force-pushed the tianning.li/microvm-buffer-reset-04-otel-runtime-baseline branch from 8118609 to 48c72fc Compare September 18, 2026 18:28
@litianningdatadog
litianningdatadog force-pushed the tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets branch from f2fc0ab to 60c0679 Compare September 18, 2026 18:29
@litianningdatadog
litianningdatadog force-pushed the tianning.li/microvm-buffer-reset-05-otel-runtime-metric-resets branch from 60c0679 to d185b6b Compare September 18, 2026 18:53

@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: d185b6bd65

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (baseline !== undefined) {
dataPoint.value -= baseline
// Keep the latest absolute reading so a later refresh can preserve absent-series state.
observableCounterBaselines.set(stateKey, currentValue)

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 Keep the cumulative refresh baseline fixed

When an ObservableCounter uses CUMULATIVE or LOWMEMORY temporality after an identity refresh, updating the stored baseline after every export converts the series into interval deltas while it is still marked cumulative. For example, a refresh baseline of 23 followed by callback values 25 and 27 exports 2 and 2, whereas cumulative clone-local values must be 2 and 4; retain the refresh-time baseline until the next refresh. The current tests stop after one post-refresh export and therefore miss this repeated-collection sibling case.

AGENTS.md reference: AGENTS.md:L79-L80

Useful? React with 👍 / 👎.

Comment on lines +210 to +212
const observe = maxMeasurements === Infinity
? (instrument, value, attributes) => {
if (instruments.has(instrument) && (!filter || filter(instrument))) {

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 Badge Skip batch callbacks without matching counters

During an identity refresh, the new filter suppresses observations from non-ObservableCounter instruments but still invokes every batch callback. A batch callback registered only for gauges or ObservableUpDownCounters can drain or reset its backing accumulator on each invocation; this hidden collection discards that result, so the next real export loses the accumulated measurement. Check whether the callback's instrument set contains a matching instrument before invoking it.

Useful? React with 👍 / 👎.

Comment on lines +742 to +746
if (metric.type === METRIC_TYPES.OBSERVABLECOUNTER && observableCounterStateKeys) {
scopeKey = this.#getScopeKey(metric.instrumentationScope)
for (const dataPoint of metric.dataPointMap.values()) {
const stateKey = this.#getStateKey(scopeKey, metric.name, metric.type, dataPoint.attrKey)
observableCounterStateKeys.add(stateKey)

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 Badge Stop retaining series after the one-shot refresh

In a MicroVM using CUMULATIVE or LOWMEMORY temporality, every periodic collection now permanently adds each ObservableCounter attribute series to #observableCounterStateKeys. The sole production identity-refresh publisher is the one-shot /run hook, so after that refresh this set is never consumed again; counters with rotating attributes therefore grow retained heap for the clone's entire lifetime. Disable or clear this tracking after the refresh state has been captured.

AGENTS.md reference: AGENTS.md:L107-L112

Useful? React with 👍 / 👎.

@khanayan123

Copy link
Copy Markdown
Collaborator

Going to move this PR to draft since there has been no activity for 3 weeks, please reopen once ready

@khanayan123
khanayan123 marked this pull request as draft October 6, 2026 12:09

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

aws-microvm AWS MicroVM related features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants