Skip to content

fix(tracing): discard native buffers on MicroVM identity refresh - #20150

Draft
litianningdatadog wants to merge 1 commit into
tianning.li/4-buffer-reset-upon-microvm-startfrom
tianning.li/5-libdadadog-based-buffer-reset-upon-microvm-start
Draft

fix(tracing): discard native buffers on MicroVM identity refresh#20150
litianningdatadog wants to merge 1 commit into
tianning.li/4-buffer-reset-upon-microvm-startfrom
tianning.li/5-libdadadog-based-buffer-reset-upon-microvm-start

Conversation

@litianningdatadog

@litianningdatadog litianningdatadog commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Description

Builds on the MicroVM identity-refresh reset path by using discard-only native lifecycle hooks for libdatadog-backed trace and telemetry buffers. Native trace exporter buffers now shut down without flushing during identity refresh, and the native telemetry worker is discarded instead of stopped/flushed before it is rebuilt with the refreshed runtime ID.

The span aggregator keeps writer replacement and active trace invalidation under the same lock so pre-refresh traces cannot be written through the replacement writer during the refresh boundary.

Testing

Tested it with the expected libdatadog change (PR 2478) and the logs show the reset is invoked upon MicroVM receives /run/ event.

image

Risks

The intended behavior drops pre-refresh native trace/telemetry buffers during Lambda MicroVM identity refresh. Rust/native dependency changes may need the native benchmark/build jobs before this leaves draft.

Additional Notes

Stacked draft PR on top of #20149. The MicroVM identity-refresh release note is already covered earlier in the stack; this PR should use the changelog/no-changelog label.

@litianningdatadog litianningdatadog added the changelog/no-changelog A changelog entry is not required for this PR. label Sep 8, 2026
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against tianning.li/4-buffer-reset-upon-microvm-start using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/_trace/processor/__init__.py                                    @DataDog/apm-sdk-capabilities-python
ddtrace/internal/telemetry/writer.py                                    @DataDog/apm-python
ddtrace/internal/writer/writer.py                                       @DataDog/apm-core-python
src/native/Cargo.lock                                                   @DataDog/apm-core-python
src/native/Cargo.toml                                                   @DataDog/apm-core-python
src/native/data_pipeline/mod.rs                                         @DataDog/apm-core-python
src/native/telemetry.rs                                                 @DataDog/apm-core-python
tests/telemetry/test_telemetry.py                                       @DataDog/apm-python
tests/telemetry/test_writer.py                                          @DataDog/apm-python
tests/tracer/test_processors.py                                         @DataDog/apm-sdk-capabilities-python
tests/tracer/test_writer.py                                             @DataDog/apm-sdk-capabilities-python

@litianningdatadog
litianningdatadog requested a lite review from Copilot September 8, 2026 20:27
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

There are 3 circular imports that already exist on the base branch and have not been changed by this PR.

ddtrace.llmobs -> ddtrace.llmobs._evaluators -> ddtrace.llmobs._evaluators.format -> ddtrace.llmobs._experiment -> ddtrace.llmobs
ddtrace.errortracking._handled_exceptions.bytecode_injector -> ddtrace.errortracking._handled_exceptions.callbacks -> ddtrace.errortracking._handled_exceptions.collector -> ddtrace.errortracking._handled_exceptions.bytecode_reporting -> ddtrace.errortracking._handled_exceptions.bytecode_injector
ddtrace.appsec._asm_request_context -> ddtrace.appsec._iast._iast_request_context_base -> ddtrace.appsec._iast._iast_env -> ddtrace.appsec._iast.reporter -> ddtrace.appsec._exploit_prevention.stack_traces -> ddtrace.appsec._asm_request_context

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Sep 8, 2026

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 231 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=134)
ddtrace.internal.opentelemetry.context -×-> ddtrace.trace  (product:opentelemetry -> product:tracing, score=132)
ddtrace.llmobs._integrations.llama_index -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)
ddtrace.internal.opentelemetry.span -×-> ddtrace.trace  (product:opentelemetry -> product:tracing, score=132)
ddtrace.llmobs._integrations.langchain -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)

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

datadog-datadog-prod-us1 Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Pipelines  Tests

Unblock PR with BitsAI

⚠️ Warnings

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

🚦 20 Pipeline jobs failed

System Tests | tracer-release / End-to-end #11 / uds-flask 11 — ❌ 1 test failed · 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

1 failed test. Assertion Error: Missing stats for GET /resource_renaming/api/users/{param:int} at tests/test_resource_renaming.py:99.

Showing tests most relevant to this failure.

❌ tests.test_resource_renaming.Test_Resource_Renaming_Stats_Aggregation_Keys.test_stats_aggregation_with_method_and_endpoint[uds-flask] from system_tests_suite
AssertionError: Missing stats for GET /resource_renaming/api/users/{param:int}
assert ('GET', '/resource_renaming/api/users/{param:int}') in {}

self = <tests.test_resource_renaming.Test_Resource_Renaming_Stats_Aggregation_Keys object at 0x7fde503d2ff0>

    def test_stats_aggregation_with_method_and_endpoint(self):
        """Test that stats are aggregated by method and endpoint"""
        stats_points = []
        for stats_data in interfaces.library.get_data("/v0.6/stats"):
            stats = stats_data.get("request", {}).get("content", {}).get("Stats", [])
...
System Tests | tracer-release / End-to-end #8 / flask-poc 8 — ❌ 1 test failed · 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

1 failed test. AssertionError: Missing stats for GET /resource_renaming/api/users/{param:int}

❌ tests.test_resource_renaming.Test_Resource_Renaming_Stats_Aggregation_Keys.test_stats_aggregation_with_method_and_endpoint[flask-poc] from system_tests_suite
AssertionError: Missing stats for GET /resource_renaming/api/users/{param:int}
assert ('GET', '/resource_renaming/api/users/{param:int}') in {}

self = <tests.test_resource_renaming.Test_Resource_Renaming_Stats_Aggregation_Keys object at 0x7f1c3464c680>

    def test_stats_aggregation_with_method_and_endpoint(self):
        """Test that stats are aggregated by method and endpoint"""
        stats_points = []
        for stats_data in interfaces.library.get_data("/v0.6/stats"):
            stats = stats_data.get("request", {}).get("content", {}).get("Stats", [])
...
System Tests | tracer-release / End-to-end #9 / uwsgi-poc 9 — ❌ 1 test failed · 🔧 Needs a code fix, caused by this PR

View more details · View in GitHub Actions

1 failed test. Assertion Error: Missing stats for GET /resource_renaming/api/users/{param:int} in tests/test_resource_renaming.py:99.

Showing tests most relevant to this failure.

❌ tests.test_resource_renaming.Test_Resource_Renaming_Stats_Aggregation_Keys.test_stats_aggregation_with_method_and_endpoint[uwsgi-poc] from system_tests_suite
AssertionError: Missing stats for GET /resource_renaming/api/users/{param:int}
assert ('GET', '/resource_renaming/api/users/{param:int}') in {}

self = <tests.test_resource_renaming.Test_Resource_Renaming_Stats_Aggregation_Keys object at 0x7f5b84be82c0>

    def test_stats_aggregation_with_method_and_endpoint(self):
        """Test that stats are aggregated by method and endpoint"""
        stats_points = []
        for stats_data in interfaces.library.get_data("/v0.6/stats"):
            stats = stats_data.get("request", {}).get("content", {}).get("Stats", [])
...

View all 20 failed jobs.

📋 Copy fix prompt
CI on my pull request is failing. Help me find and fix the root cause of each failing job below — they were flagged as caused by changes in this PR, so focus on the diff. For each job, explain the failure and propose a fix.

Before you start, set up the Datadog software-delivery tooling so you can
query the CI data yourself:

1. Check whether you already have the Datadog software-delivery MCP tools
   (e.g. a `search_datadog_ci_pipeline_events` tool) and the `unblock-pr` skill.
2. If either is missing, STOP and ask me for permission before installing
   anything. Do not install or run anything until I have said yes.
3. Only with my explicit approval, set up the Datadog software-delivery MCP
   server and skills by following:
     https://docs.datadoghq.com/getting_started/software_delivery_mcp_tools/
   then restart so the skill is picked up.
4. If I decline, skip all of the above and work from the context below alone.

Then run /unblock-pr — it will pull the CI data itself. The job context below is what we already know.

If /unblock-pr is not available — because I declined the setup above, or it did not install — work from the context below instead.

Datadog has already classified this failure as caused by changes in this PR.
Take that as given and work the fix:

1. Locate the change. Diff this branch against its base and find the change
   that produces this error. Explain the mechanism, don't just name a file:
     git fetch origin && git diff $(git merge-base origin/tianning.li/4-buffer-reset-upon-microvm-start HEAD)...HEAD
2. Reproduce it locally. Run the failing job's command or test before
   proposing anything.
3. Propose the smallest fix that addresses the root cause — not a workaround,
   not a broadened assertion, not a disabled or skipped test.
4. Re-run the same command to confirm, and say exactly what you ran.
5. If the failure turns out to be intermittent rather than deterministic, say
   so plainly instead of "fixing" it — that is a flaky test, and patching it
   hides the problem.

If the right move is to re-run the job rather than change code, use the job
link in the context below. For GitHub Actions: `gh run rerun <run-id> --failed`,
where the run ID is the number after `/runs/` in that URL (not the trailing
number, which is the job ID).

Branch: tianning.li/5-libdadadog-based-buffer-reset-upon-microvm-start

System Tests | tracer-release / End-to-end #11 / uds-flask 11
Commit: 95d8c969e46b10089a1591fe4be2c8128076baa2
Error (code / test):
1 failed test. Assertion Error: Missing stats for GET /resource_renaming/api/users/{param:int} at tests/test_resource_renaming.py:99.
CI job: https://github.com/DataDog/dd-trace-py/actions/runs/34379811404/job/102564794628

System Tests | tracer-release / End-to-end #8 / flask-poc 8
Commit: 95d8c969e46b10089a1591fe4be2c8128076baa2
Error (code / test):
1 failed test. AssertionError: Missing stats for GET /resource_renaming/api/users/{param:int}
CI job: https://github.com/DataDog/dd-trace-py/actions/runs/34379811404/job/102564790220

System Tests | tracer-release / End-to-end #9 / uwsgi-poc 9
Commit: 95d8c969e46b10089a1591fe4be2c8128076baa2
Error (code / test):
1 failed test. Assertion Error: Missing stats for GET /resource_renaming/api/users/{param:int} in tests/test_resource_renaming.py:99.
CI job: https://github.com/DataDog/dd-trace-py/actions/runs/34379811404/job/102564794856

Plus 4 more failing jobs not shown here.

ℹ️ Info

No other issues found (see more)

❄️ No new flaky tests detected

Useful? React with 👍 / 👎

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

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.

🔵 Needs a closer look

It changes native lifecycle semantics and updates Rust/libdatadog dependencies, which warrants final human review despite the added targeted tests.

Pull request overview

This PR extends the Lambda MicroVM runtime-identity refresh reset path by introducing discard-without-flush lifecycle hooks for libdatadog-backed native trace exporter buffers and the native telemetry worker, and by tightening SpanAggregator reset ordering to prevent pre-refresh traces from being written across the refresh boundary.

Changes:

  • Add native discard/shutdown-without-flush hooks (Rust/PyO3) for telemetry workers and trace exporters, and invoke them during identity refresh / buffer drop paths.
  • Make SpanAggregator reset keep writer replacement and trace-buffer invalidation atomic under the same lock when dropping buffered traces.
  • Update tests to assert discard semantics and ordering guarantees; bump libdatadog git rev to a pinned commit (Cargo.toml/Cargo.lock).
File summaries
File Description
tests/tracer/test_writer.py Verifies native writer buffer drops do not flush and that exporter discard is invoked.
tests/tracer/test_processors.py Adds a concurrency test ensuring reset buffer invalidation and writer recreation remain atomic during identity refresh.
tests/telemetry/test_writer.py Updates MicroVM identity refresh telemetry test to assert worker discard (not stop/flush).
tests/telemetry/test_telemetry.py Adds subprocess test validating native telemetry worker discard unregisters the worker idempotently.
ddtrace/internal/writer/writer.py Calls native exporter shutdown_without_flush() from NativeWriter.drop_buffered_traces().
ddtrace/_trace/processor/init.py Moves trace-buffer invalidation into the writer-replacement critical section for the identity-refresh discard path.
ddtrace/internal/telemetry/writer.py Switches runtime identity refresh teardown from stop(send_app_closing=False) to discard().
src/native/data_pipeline/mod.rs Exposes shutdown_without_flush on the PyO3 TraceExporter wrapper.
src/native/telemetry.rs Adds PyO3 TelemetryWorkerPy.discard() to discard pending telemetry without flushing and stop the worker.
src/native/Cargo.toml Pins libdatadog dependencies to a specific commit rev and updates live-debugger package mapping.
src/native/Cargo.lock Updates the resolved dependency graph for the new libdatadog rev (including new transitive crates).
Review details
  • Files reviewed: 10/11 changed files
  • Comments generated: 0
  • Review effort level: Lite

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

@litianningdatadog litianningdatadog added the aws-microvm Work related to AWS MicroVM onboarding label Sep 8, 2026
@pr-commenter

pr-commenter Bot commented Sep 8, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-09-09 17:26:13

Comparing candidate commit 181f65c in PR branch tianning.li/5-libdadadog-based-buffer-reset-upon-microvm-start with baseline commit 2c062e6 in branch tianning.li/4-buffer-reset-upon-microvm-start.

📊 Benchmarking dashboard

Found 0 performance improvements and 7 performance regressions! Performance is the same for 574 metrics, 10 unstable metrics, 1 known flaky benchmarks, 17 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 ----------------------------------'

scenario:httppropagationextract-tracecontext_headers

  • 🟥 execution_time [+3.071µs; +3.289µs] or [+8.035%; +8.605%]

scenario:httppropagationinject-ids_only

  • 🟥 execution_time [+2.533µs; +2.690µs] or [+14.717%; +15.633%]

scenario:iastaspects-rstrip_aspect

  • 🟥 execution_time [+44.186µs; +49.561µs] or [+11.431%; +12.822%]

scenario:iastaspects-stringio_noaspect

  • 🟥 execution_time [+24.674µs; +28.661µs] or [+7.447%; +8.650%]

scenario:iastaspectsospath-ospathbasename_aspect

  • 🟥 execution_time [+109.902µs; +116.797µs] or [+28.266%; +30.040%]

scenario:telemetryaddmetric-1-count-metric-1-times

  • 🟥 execution_time [+419.754ns; +446.784ns] or [+15.245%; +16.226%]

scenario:tracer-small

  • 🟥 execution_time [+27.990µs; +30.013µs] or [+8.475%; +9.088%]

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 [-815.754ns; +667.644ns] or [-7.355%; +6.019%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-38.513ns; +27.678ns] or [-6.263%; +4.501%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1663.529ns; +1633.308ns] or [-9.711%; +9.535%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-481.824ns; +1984.132ns] or [-3.712%; +15.288%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-323.960ns; +326.309ns] or [-8.805%; +8.869%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-271.019ns; +235.721ns] or [-9.213%; +8.013%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-37.153ns; +114.276ns] or [-3.237%; +9.958%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4367.988ns; +3572.101ns] or [-10.636%; +8.698%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-782.835ns; +742.358ns] or [-9.682%; +9.181%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-57.884µs; +52.454µs] or [-9.981%; +9.045%]

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.

scenario:span-start

  • 🟥 execution_time [+1.396ms; +1.644ms] or [+10.105%; +11.896%]

Known flaky benchmarks without significant changes:

  • scenario:errortrackingflasksqli-baseline
  • scenario:flasksimple-iast-get
  • scenario:iastaspects-casefold_aspect
  • scenario:iastaspects-casefold_noaspect
  • scenario:iastaspects-index_aspect
  • scenario:iastaspects-ljust_noaspect
  • scenario:iastaspects-lower_aspect
  • scenario:iastaspects-replace_aspect
  • scenario:iastaspects-swapcase_aspect
  • scenario:iastaspects-title_noaspect
  • scenario:iastaspects-translate_aspect
  • scenario:iastaspects-translate_noaspect
  • scenario:iastaspects-upper_noaspect
  • scenario:packagespackageforrootmodulemapping-cache_off
  • scenario:packagespackageforrootmodulemapping-cache_on
  • scenario:sethttpmeta-all-enabled
  • scenario:telemetryaddmetric-record-100-metrics

@litianningdatadog
litianningdatadog force-pushed the tianning.li/5-libdadadog-based-buffer-reset-upon-microvm-start branch from d41721f to 181f65c Compare September 9, 2026 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

aws-microvm Work related to AWS MicroVM onboarding changelog/no-changelog A changelog entry is not required for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants