Skip to content

refactor(native): split the msgpack packer and store meta_struct as bytes - #22136

Open
gnufede wants to merge 3 commits into
mainfrom
gnufede/package-split-native-msgpack
Open

gnufede wants to merge 3 commits into
mainfrom
gnufede/package-split-native-msgpack

Conversation

@gnufede

@gnufede gnufede commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Part of replacing #22018 with smaller PRs on main. Addresses
#22018 (comment) and
#22018 (comment).

What

The native span stops calling back into Python to encode meta_struct. It stores bytes only, which is what the
agent spec says meta_struct is (map<string, bytes>). The generic msgpack packer moves next to the native
extension, so it can ship in ddtrace-native later.

  • Packer split. The generic msgpack Packer / packb moves out of ddtrace/internal/_encoding.pyx into a
    new Cython module, ddtrace/internal/native/_msgpack.pyx, together with the pack.h / pack_template.h /
    sysdep.h headers. The packer is unchanged. _encoding still compiles against the headers (extra include
    dir) and re-imports packb. The v0.4 encoder, data streams, the CI Visibility encoder and the testing tracer
    API import it from the new module.
  • Bytes-only native meta_struct. SpanData stores meta_struct as a Rust-owned list of (str, bytes).
    Its methods are _set_encoded_struct_tag / _get_encoded_struct_tag / _has_encoded_struct_tags /
    _get_encoded_struct_tags, and the setter raises TypeError for anything that isn't str -> bytes.
    wire.rs copies the stored bytes into the wire map, so the Rust crate no longer imports any Python packer
    (the ddtrace.internal._encoding import and its drop logging are gone). The GC traversal visits the
    meta_struct keys like the other string fields; the values are Rust-owned bytes. _encoding.pyx writes the
    stored bytes as msgpack bin, and the wire layout is unchanged.
  • Live dicts stay on the Python Span. The nested, mutable dicts that products read and edit (LLMObs,
    AppSec, IAST, AI Guard, stack traces, CI Visibility coverage) live in a lazy _meta_struct slot on Span,
    which keeps _set_struct_tag / _get_struct_tag / _remove_struct_tag / _has_meta_structs /
    _get_meta_structs. No product caller changes.
  • Encode when the writer takes the span. Products edit the dicts in place until the last trace processor
    has run (the LLMObs processor also removes its key), so nothing is encoded before the writer. The Cython
    encoders pack Span._packed_struct_tags() straight into the payload, so no span keeps a second, encoded copy.
    NativeTraceBuffer.write() stores the encoding in the native span with Span._encode_struct_tags() just
    before handing it to Rust, because the native span is all the Rust encoder reads. Encoding in write()
    rather than in SpanAggregator covers every caller, including the ones that write spans themselves (Ray's
    span manager, benchmarks). An entry that fails to encode is dropped, the first drop in the process logs one
    warning, and the application thread never sees the error.
    SpanData declares _encode_struct_tags() as a no-op that Span overrides, so the writer calls it without a
    cast, and spans with no struct tags return before any work.
  • ast-grep. With the Rust import gone, this PR deletes the native-no-python-imports suppression in
    wire.rs (from chore(native): fail on python imported from src/native #22161). src/native has no ast-grep-ignore left.

Tests

  • tests/tracer/test_encoders.py: the encoder reads the live dicts when the writer takes the span, and an
    entry that fails to encode is dropped with one warning while the rest of the span is still encoded.
  • tests/tracer/test_processors.py: the aggregator hands the writer the struct-tag state after the last
    trace processor (in-place edits, additions and removals).
  • tests/tracer/test_native_trace_buffer.py: write() encodes the struct tags, the wire output matches the
    Cython encoder, and a native span with no encoded struct tags sends none.
  • tests/tracer/test_span_data.py: the native encoded round-trip and the TypeError for non-bytes keys and
    values. The live struct-tag tests moved to tests/tracer/test_span.py, with a check that a reference cycle
    through Span._meta_struct is collected.
  • tests/vendor/msgpack/* import from the new module.
  • Run locally on py3.14: tracer suite 4506 passed, 22 failed (span, buffer, encoder and processor files after
    the review round: 660 passed, 1 failed, same cause). All 22 are subprocess tests that assert empty
    stderr and hit localhost:8126 with no agent running; none touch meta_struct. Earlier runs: CI Visibility
    651 passed, AppSec 182 passed, LLMObs 494 passed / 8 failed (pytest-asyncio environment). scripts/lint
    clean. CI is the first run on other Python versions.
  • Performance evidence for the encoder and buffer paths is in test(benchmarks): cover meta_struct encoding and the native trace buffer #22158. Encoding at the writer has not been
    benchmarked separately.

Plan: products encode their own values

Agreed with @brettlangdon: the end state is that every product encodes its own meta_struct values with
packb when its span finishes, and the core never encodes product data. This PR does not force that move.
It keeps two paths, so each product switches on its own timeline:

Today's path (unchanged) Target path
Write span._set_struct_tag(key, dict) span._set_encoded_struct_tag(key, packb(value))
Read span._get_struct_tag(key) (live dict) span._get_encoded_struct_tag(key) (bytes)
Encoded by the writer, when it takes the span the product, when its span finishes
  1. This PR: the native contract is bytes-only and the packer lives next to the native extension. No
    product changes.
  2. Follow-up (core, small): the Python encoders also ship tags set through _set_encoded_struct_tag
    (today only the native trace buffer does), one rule for a key set through both paths, and
    _has_meta_structs() sees both. Until it lands, products stay on today's path.
  3. Per product, one PR per key: LLMObs, AppSec/IAST, AI Guard, security and CI Visibility move their keys
    (11 call sites in 9 modules). A key moves when nothing edits it after the span finishes, because an encoded
    value can no longer change; the LLMObs processor, which removes its key in a trace processor, moves last.
  4. Clean-up: delete Span._meta_struct, _packed_struct_tags / _encode_struct_tags, the encode step in
    the writers and the five transitional stubs in _native.pyi.

Risks

  • _native.pyi still declares the five live struct-tag methods on SpanData, because AppSec, IAST and
    security type their spans as SpanData (refactor(appsec): use native span data interfaces #20898). Only Span implements them; the stub comment says so.
    They go away in step 4.
  • The legacy path encodes when the writer takes the span, not at finish, so it still reflects edits made by
    trace processors. A product that moves to the target path gives that up for its key.

Notes

  • No customer-visible change: changelog/no-changelog.

🤖 Generated with Claude Code

gnufede and others added 3 commits November 26, 2026 16:43
The generic msgpack Packer and packb import nothing from ddtrace, but
they lived in _encoding next to the trace encoders, which import the
constants, the logger, span limits and agent settings and stay with the
tracer. Moving the packer into its own Cython module, next to the Rust
extension in ddtrace.internal.native, lets it ship verbatim with the
ddtrace-native package, and lets the extension import it as a sibling
instead of reaching into ddtrace.internal._encoding.

The packer is unchanged. The msgpack headers move with it, and
_encoding, whose trace encoders also compile against them, adds that
directory to its include path. The v0.4 encoder, data streams, the CI
visibility encoder and the testing tracer API import packb from the new
module.

The type parameters in test_subtype.py only satisfy mypy, which checks
the files a commit touches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The native TraceBuffer imported ddtrace.internal._encoding on first use
to pack meta_struct values. The extension is moving to a standalone
package that must not import any ddtrace module. Now that the packer
lives next to the extension, the extension imports it as a sibling: at
init it records the package it was imported into (from its own module
name) and imports <package>._msgpack. That resolves to
ddtrace.internal.native in dd-trace-py and to _ddtrace_native in the
ddtrace-native package, with no ddtrace path in the crate and no
registration call from Python to keep in sync.

TraceBuffer.__init__ does the import, so write() imports nothing and
keeps working in sandboxes that block imports after startup. If the
import fails, write() drops each meta_struct entry with a single
warning, because it must never raise into user code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The native extension is moving to a standalone package that must not
import any ddtrace module. The last reach-in, the packb import in
span/wire.rs, now goes to the sibling _msgpack; this check keeps new
ones from coming back. It scans src/native for py.import /
PyModule::import calls on a ddtrace module, ignoring comments and plain
string literals such as the pyclass module attribute and event names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gnufede gnufede added the changelog/no-changelog A changelog entry is not required for this PR. label Nov 26, 2026
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 26, 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.

.gitignore                                                              @DataDog/apm-python-guild
benchmarks/suitespec.yml                                                @DataDog/apm-core-python
ddtrace/internal/_encoding.pyi                                          @DataDog/apm-core-python
ddtrace/internal/_encoding.pyx                                          @DataDog/apm-core-python
ddtrace/internal/ci_visibility/encoder.py                               @DataDog/ci-app-libraries
ddtrace/internal/datastreams/processor.py                               @DataDog/data-streams-monitoring
ddtrace/internal/native/_msgpack.pyi                                    @DataDog/apm-core-python
ddtrace/internal/native/_msgpack.pyx                                    @DataDog/apm-core-python
ddtrace/internal/native/pack.h                                          @DataDog/apm-core-python
ddtrace/internal/native/pack_template.h                                 @DataDog/apm-core-python
ddtrace/internal/native/sysdep.h                                        @DataDog/apm-core-python
ddtrace/testing/internal/tracer_api/__init__.py                         @DataDog/ci-app-libraries
scripts/check_native_python_imports.py                                  @DataDog/apm-python-guild
scripts/gen_gitlab_config.py                                            @DataDog/apm-python-guild
scripts/lint                                                            @DataDog/apm-python-guild
setup.py                                                                @DataDog/apm-python-guild
src/native/data_pipeline/trace_buffer.rs                                @DataDog/apm-core-python
src/native/lib.rs                                                       @DataDog/apm-core-python
src/native/span/wire.rs                                                 @DataDog/apm-core-python
tests/suitespec.yml                                                     @DataDog/apm-python-guild
tests/tracer/test_native_trace_buffer.py                                @DataDog/apm-sdk-capabilities
tests/vendor/msgpack/test_buffer.py                                     @DataDog/apm-python-guild
tests/vendor/msgpack/test_case.py                                       @DataDog/apm-python-guild
tests/vendor/msgpack/test_except.py                                     @DataDog/apm-python-guild
tests/vendor/msgpack/test_limits.py                                     @DataDog/apm-python-guild
tests/vendor/msgpack/test_newspec.py                                    @DataDog/apm-python-guild
tests/vendor/msgpack/test_pack.py                                       @DataDog/apm-python-guild
tests/vendor/msgpack/test_read_size.py                                  @DataDog/apm-python-guild
tests/vendor/msgpack/test_seq.py                                        @DataDog/apm-python-guild
tests/vendor/msgpack/test_subtype.py                                    @DataDog/apm-python-guild
tests/vendor/msgpack/test_unpack.py                                     @DataDog/apm-python-guild

@datadog-prod-us1-3

datadog-prod-us1-3 Bot commented Nov 26, 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.

🚦 4 Pipeline jobs failed

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

View more details · View in GitLab

Changelog | Validate changelog

View more details · View in GitHub Actions

DataDog/apm-reliability/dd-trace-py | appsec/appsec_iast_packages 1/5

View more details · View in GitLab

View all 4 failed jobs.

ℹ️ 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: 597e3f6 | Docs | View more details | Give us feedback!

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Nov 26, 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.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.base -×-> 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

@pr-commenter

pr-commenter Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-12-04 18:57:04

Comparing candidate commit 597e3f6 in PR branch gnufede/package-split-native-msgpack with baseline commit 56a4a53 in branch main.

📊 Benchmarking dashboard

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

scenario:iastaspects-title_aspect

  • 🟥 execution_time [+19.569µs; +23.299µs] or [+7.234%; +8.612%]

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 [-716.149ns; +748.545ns] or [-6.762%; +7.068%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-32.539ns; +44.818ns] or [-5.108%; +7.036%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1796.579ns; +2022.267ns] or [-9.073%; +10.213%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-2329.713ns; +1358.690ns] or [-11.935%; +6.961%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-361.972ns; +395.382ns] or [-8.579%; +9.371%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-200.673ns; +254.724ns] or [-7.610%; +9.660%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-109.546ns; +74.180ns] or [-8.073%; +5.466%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-5139.446ns; +4277.107ns] or [-10.434%; +8.683%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-1054.323ns; +875.183ns] or [-10.230%; +8.492%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-42.166µs; +70.281µs] or [-7.303%; +12.173%]

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

@gnufede
gnufede marked this pull request as ready for review November 26, 2026 17:23
@gnufede
gnufede requested review from a team as code owners November 26, 2026 17:23
@gnufede
gnufede requested review from brettlangdon and mabdinur and removed request for a team November 26, 2026 17:23
@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-12-04T18:25:37.488729Z 597e3f6 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: 02829510ae

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

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

No reportable defect was identified in the msgpack extraction or sibling-import changes. Suite-selection changes and runtime/wheel-build behavior remain unvalidated.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 0282951

@gnufede
gnufede force-pushed the gnufede/package-split-native-msgpack branch from ed258ee to c0eaba5 Compare November 27, 2026 13:56
@gnufede
gnufede changed the base branch from main to gnufede/benchmark-trace-buffer-meta-struct November 27, 2026 13:57
@gnufede
gnufede added this pull request to stack #22159 November 27, 2026 14:01

@datadog-prod-us1-3 datadog-prod-us1-3 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 native buffer derives the sibling packer’s location from its own package and resolves it during construction. The completed static review found no actionable defect; native builds, runtime tests, and wheel contents remain unverified.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit c0eaba5

@gnufede
gnufede force-pushed the gnufede/package-split-native-msgpack branch from c0eaba5 to 63c5b93 Compare November 27, 2026 14:15
@gnufede
gnufede removed this pull request from stack #22159 November 27, 2026 14:19
@gnufede
gnufede changed the base branch from gnufede/benchmark-trace-buffer-meta-struct to gnufede/native-import-check November 27, 2026 14:19

@datadog-prod-us1-3 datadog-prod-us1-3 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 specialist found no actionable defects in the packer extraction, sibling imports, build configuration, or consumers. Serialization logic is preserved, but runtime behavior was not tested.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 8ab8610

@datadog-prod-us1-3 datadog-prod-us1-3 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 packer extraction preserves serialization logic, and Rust resolves the packer relative to the extension’s package. Confidence is limited to static inspection; tests and benchmarks were not executed.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit d470175

@gnufede gnufede changed the title chore(native): split the msgpack packer into native._msgpack and import it as a sibling refactor(native): split the msgpack packer and store meta_struct as bytes Dec 2, 2026

@datadog-prod-us1-3 datadog-prod-us1-3 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 PR extracts native._msgpack and moves struct-tag encoding into Python, removing Rust’s packer imports. One issue remains: Ray’s direct writes bypass encoding and silently lose struct tags, while the same bypass leaves meta-struct benchmarks measuring empty storage; no earlier findings needed resolution, and validation remains static.

Open Bits AI session

🤖 Bits Code Review · Commit 2312e81

Comment thread ddtrace/_trace/processor/__init__.py Resolved

@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: 2312e814af

ℹ️ 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 thread src/native/span/wire.rs Resolved
Comment thread ddtrace/_trace/processor/__init__.py Resolved

@datadog-prod-us1-3 datadog-prod-us1-3 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 extracts native._msgpack and removes Rust’s Python packer imports, with struct tags encoded at writer boundaries. This fixes the earlier Ray data loss and empty meta-struct benchmark workload; no findings remain open, with validation limited to static inspection.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 6c3688e

gnufede added a commit that referenced this pull request Dec 2, 2026
Flagging ddtrace-named string literals was an indirect proxy: the real
dependency is the Python import call itself. Banning pyo3's import APIs
outright (suggested in review) is stricter -- it catches module names
computed at runtime -- and smaller: no pyo3 `module = "..."` exemption
and no literal-matching utilities are needed, replacing ~465 lines of
rule, snapshot and tests with ~120.

The one remaining import in src/native (wire.rs packb) is grandfathered
with a suppression; the packer split (#22136) removes it. The literal
suppressions in context_provider.rs and wire.rs are no longer needed and
are reverted to main's version.
@gnufede
gnufede force-pushed the gnufede/package-split-native-msgpack branch from 6c3688e to e208e6e Compare December 2, 2026 14:55

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

Writer-time struct-tag encoding covers direct native-buffer writes and preserves edits made by trace processors. Runtime behavior and performance were not exercised.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit e208e6e

@gnufede
gnufede force-pushed the gnufede/package-split-native-msgpack branch from e208e6e to 0fef1ae Compare December 2, 2026 15:27

@datadog-prod-us1-3 datadog-prod-us1-3 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 native writer encodes live struct tags before serialization, covering direct writer callers despite the omission described in the PR text. The completed static review identified no reportable defect.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 0fef1ae

@gnufede
gnufede force-pushed the gnufede/package-split-native-msgpack branch 2 times, most recently from 3a28078 to a92e6bc Compare December 2, 2026 16:08

@datadog-prod-us1-3 datadog-prod-us1-3 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 reviewed head encodes struct tags at writer and encoder boundaries, addressing the aggregator-bypass risk described in the PR text. Runtime behavior and wheel packaging remain unverified.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit a92e6bc

@gnufede
gnufede removed this pull request from stack #22162 December 2, 2026 17:33
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Dec 3, 2026
## Description

Split out of #22136: fail CI if Rust code under `src/native` imports a Python module.

- A new ast-grep rule `native-no-python-imports` (`.sg/rules/`) flags any `.import` or `::import`
  call in `src/native/**/*.rs` (four call patterns: `$RECV.import($$$ARGS)`,
  `$TYPE::import($$$ARGS)` and their turbofish forms). That covers the method
  form (`py.import(...)`, `PyOnceLock::import`, the deprecated `GILOnceCell` alias) and every
  associated-function spelling (`Python::import`, `pyo3::Python::import`, `<Python>::import`,
  `PyModule::import`, `pyo3::types::PyModule::import`, aliased types), with or without turbofish
  generics. pyo3 0.30 has no other import entry point (`import_bound` was removed in 0.23).
  Only calls match: a Rust module or field named `import` that is not called
  (`self.import.dispatch(...)`, `use crate::encoding::import`) is not flagged.
- Why: the native extension is heading to a standalone package that must not depend on
  `ddtrace`. Python registers the callables native needs instead (e.g.
  `Context._register_tracestate_helpers`).
- The ban is on the import call, not on the module name, so names built at runtime are caught
  too. String literals that only mention `ddtrace` (event names, log messages, pyo3
  `module = "..."` class metadata) are not imports and are not flagged, so no exemptions are
  needed for them.
- The only existing import, `py.import("ddtrace.internal._encoding")` in
  `src/native/span/wire.rs`, carries an inline `// ast-grep-ignore: native-no-python-imports`
  suppression. #22136 (stacked on this PR) removes that code path and the suppression with it,
  leaving `src/native` with no Python imports.
- The check rides the existing ast-grep rules CI job: no new script, lint subcommand or CI
  wiring. `scripts/lint sg` now passes `--error=unused-suppression`, so a suppression whose rule
  stops firing fails CI and the suppression list can only shrink.

## Customer impact

None: developer and CI tooling only. `changelog/no-changelog`.

## Testing

- `scripts/lint sg` clean on the real tree (exit 0), with `--error=unused-suppression`.
- `scripts/lint sg-test`: all 29 ast-grep test suites pass, including the new rule's test and
  snapshot (method and associated-function forms, fully qualified, `<Python>::import`, aliased
  and turbofish calls, a runtime-computed name, a multiline method chain; ddtrace-named literals,
  pyo3 `module =` metadata and Rust modules or fields named `import` stay valid).
- Inline suppressions are not applied by `ast-grep test`, so the suppression path is covered by
  `scripts/lint sg` against the `wire.rs` site.
- #22136 restacked on this branch: `scripts/lint sg` and `sg-test` pass at its head, which has
  no suppressions left under `src/native`.

## Risks

Low. The rule is scoped to `src/native/**/*.rs`. A future legitimate import needs an explicit
inline suppression with a justification, which reviewers see in the diff.

## Additional Notes

This replaces the earlier version of this PR, which flagged string literals naming `ddtrace`
modules (with shared `ddtrace-named-literal` / `pyo3-module-arg` utils and a pyo3 exemption).
Banning the import call is stricter (it also catches computed names) and smaller: the PR went
from +475/−3 to +172/−1, most of it the generated rule-test snapshot.





Co-authored-by: federico.mon <federico.mon@datadoghq.com>
Base automatically changed from gnufede/native-import-check to main December 3, 2026 09:00

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

Writer-side struct-tag encoding covers direct-write callers, addressing the Ray omission described in the PR’s risk section. Runtime behavior and packaging of the extracted Cython module remain unverified.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit a92e6bc

@gnufede
gnufede force-pushed the gnufede/package-split-native-msgpack branch from a92e6bc to 206bc17 Compare December 3, 2026 10:15

@datadog-prod-us1-3 datadog-prod-us1-3 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 native wire-encoder comparison remains incomplete because the exact base-version wire.rs blob was unavailable. Runtime behavior and performance were not exercised.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 206bc17

Comment thread ddtrace/_trace/span.py Resolved
if let Some(o) = &self._trace_id_py {
visit.call(o)?;
}
if let Some(d) = &self.meta_struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we don't have to traverse and visit the PyBackedStrings ?

@datadog-prod-us1-3 datadog-prod-us1-3 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 pinned revision retains Rust-side meta_struct encoding; the bytes-only migration described in the PR text is outside this diff. Static review identified no actionable defect, while runtime and release-wheel behavior remain unverified.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 597e3f6

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

Labels

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.

4 participants