Skip to content

feat(trace-utils): add v1-native agentless JSON encoder brick - #2370

Draft
anais-raison wants to merge 3 commits into
mainfrom
anais/v1-agentless-encoder-brick
Draft

feat(trace-utils): add v1-native agentless JSON encoder brick#2370
anais-raison wants to merge 3 commits into
mainfrom
anais/v1-agentless-encoder-brick

Conversation

@anais-raison

@anais-raison anais-raison commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds a v1-native equivalent of the existing v0.4 agentless JSON encoder, as groundwork for making v1::Span/v1::TraceChunk the exporter's canonical internal type:

  • agentless_encoder::encode_payload_from_v1 and its helpers (collect_attrs_v1, flatten_attr_into_v1, encode_span_link_v1, encode_span_event_v1) (libdd-trace-utils)

Nothing is wired into the live pipeline yet.

Motivation

Part of APMSP-2812: migration of the exporter from v0.4 to v1 with isolated bricks first before one final breaking PR that will handle the actual swap.

Additional Notes

Pure addition, no behavior change — these functions aren't called anywhere yet, so there's no regression risk.

Isolated brick for APMSP-2812: adds encode_payload_from_v1 and its
v1::Span-native helpers (collect_attrs_v1, flatten_attr_into_v1,
encode_span_link_v1, encode_span_event_v1) alongside the existing v0.4
agentless encoder. Not wired into any live send path yet.
@github-actions

github-actions Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

📚 Documentation Check Results

⚠️ 764 documentation warning(s) found

📦 libdd-trace-utils - 764 warning(s)


Updated: 2026-08-20 11:27:46 UTC | Commit: c522e74 | missing-docs job results

@anais-raison anais-raison self-assigned this Aug 19, 2026
@github-actions

github-actions Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

🔒 Cargo Deny Results

⚠️ 3 issue(s) found, showing only errors (advisories, bans, sources)

📦 libdd-trace-utils - 3 error(s)

Show output
error[vulnerability]: Invalid pointer dereference in `fmt::Pointer` impl for `Atomic` and `Shared` when the underlying pointer is invalid
   ┌─ /home/runner/work/libdatadog/libdatadog/Cargo.lock:63:1
   │
63 │ crossbeam-epoch 0.9.18 registry+https://github.com/rust-lang/crates.io-index
   │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ security vulnerability detected
   │
   ├ ID: RUSTSEC-2026-0204
   ├ Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0204
   ├ Affected versions of `fmt::Display` dereference the underlying pointer. This causes a invalid pointer dereference e.g., when a pointer created with `Atomic::null` or `Shared::null`. `fmt::Debug` impls and pre-0.9 `fmt::Display` impls, which do not dereference pointers, are not affected by this issue.
   ├ Announcement: https://github.com/crossbeam-rs/crossbeam/pull/1276
   ├ Solution: Upgrade to >=0.9.20 (try `cargo update -p crossbeam-epoch`)
   ├ crossbeam-epoch v0.9.18
     └── crossbeam-deque v0.8.5
         └── rayon-core v1.12.1
             └── rayon v1.10.0
                 └── criterion v0.5.1
                     ├── libdd-common v5.2.0
                     │   ├── libdd-capabilities-impl v4.0.0
                     │   │   └── libdd-trace-utils v10.1.0
                     │   │       └── (dev) libdd-trace-utils v10.1.0 (*)
                     │   └── libdd-trace-utils v10.1.0 (*)
                     ├── (dev) libdd-trace-normalization v3.0.1
                     │   └── libdd-trace-utils v10.1.0 (*)
                     └── (dev) libdd-trace-utils v10.1.0 (*)

error[vulnerability]: h2 unbounded empty DATA frames
   ┌─ /home/runner/work/libdatadog/libdatadog/Cargo.lock:97:1
   │
97 │ h2 0.4.6 registry+https://github.com/rust-lang/crates.io-index
   │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ security vulnerability detected
   │
   ├ ID: RUSTSEC-2026-0258
   ├ Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0258
   ├ The h2 crate, used internally by hyper, had a flaw that would accept and queue empty DATA frames without limit.
     If streams were not actively drained, this could lead to unbounded memory usage, or a panic if the length overflows.
     
     Low severity.
     
     Patched in v0.4.16.
   ├ Announcement: https://github.com/hyperium/hyper/security/advisories/GHSA-q83h-524g-xf6h
   ├ Solution: Upgrade to >=0.4.16 (try `cargo update -p h2`)
   ├ h2 v0.4.6
     └── hyper v1.6.0
         ├── httpmock v0.8.0-alpha.1
         │   └── libdd-trace-utils v10.1.0
         │       └── (dev) libdd-trace-utils v10.1.0 (*)
         ├── hyper-rustls v0.27.7
         │   └── libdd-common v5.2.0
         │       ├── libdd-capabilities-impl v4.0.0
         │       │   └── libdd-trace-utils v10.1.0 (*)
         │       └── libdd-trace-utils v10.1.0 (*)
         ├── hyper-util v0.1.17
         │   ├── httpmock v0.8.0-alpha.1 (*)
         │   ├── hyper-rustls v0.27.7 (*)
         │   └── libdd-common v5.2.0 (*)
         ├── libdd-common v5.2.0 (*)
         └── libdd-trace-utils v10.1.0 (*)

error[unsound]: Rand is unsound with a custom logger using `rand::rng()`
    ┌─ /home/runner/work/libdatadog/libdatadog/Cargo.lock:184:1
    │
184 │ rand 0.8.5 registry+https://github.com/rust-lang/crates.io-index
    │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ unsound advisory detected
    │
    ├ ID: RUSTSEC-2026-0097
    ├ Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0097
    ├ It has been reported (by [@lopopolo](https://github.com/lopopolo)) that the `rand` library is [unsound](https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library) (i.e. that safe code using the public API can cause Undefined Behaviour) when all the following conditions are met:
      
      - The `log` and `thread_rng` features are enabled
      - A [custom logger](https://docs.rs/log/latest/log/#implementing-a-logger) is defined
      - The custom logger accesses `rand::rng()` (previously `rand::thread_rng()`) and calls any `TryRng` (previously `RngCore`) methods on `ThreadRng`
      - The `ThreadRng` (attempts to) reseed while called from the custom logger (this happens every 64 kB of generated data)
      - Trace-level logging is enabled or warn-level logging is enabled and the random source (the `getrandom` crate) is unable to provide a new seed
      
      `TryRng` (previously `RngCore`) methods for `ThreadRng` use `unsafe` code to cast `*mut BlockRng<ReseedingCore>` to `&mut BlockRng<ReseedingCore>`. When all the above conditions are met this results in an aliased mutable reference, violating the Stacked Borrows rules. Miri is able to detect this violation in sample code. Since construction of [aliased mutable references is Undefined Behaviour](https://doc.rust-lang.org/stable/nomicon/references.html), the behaviour of optimized builds is hard to predict.
    ├ Announcement: https://github.com/rust-random/rand/pull/1763
    ├ Solution: Upgrade to >=0.10.1 OR <0.10.0, >=0.9.3 OR <0.9.0, >=0.8.6 (try `cargo update -p rand`)
    ├ rand v0.8.5
      ├── (dev) libdd-common v5.2.0
      │   ├── libdd-capabilities-impl v4.0.0
      │   │   └── libdd-trace-utils v10.1.0
      │   │       └── (dev) libdd-trace-utils v10.1.0 (*)
      │   └── libdd-trace-utils v10.1.0 (*)
      ├── (dev) libdd-trace-normalization v3.0.1
      │   └── libdd-trace-utils v10.1.0 (*)
      ├── libdd-trace-utils v10.1.0 (*)
      └── proptest v1.5.0
          ├── (dev) libdd-common v5.2.0 (*)
          └── (dev) libdd-tinybytes v1.1.2
              ├── (dev) libdd-tinybytes v1.1.2 (*)
              └── libdd-trace-utils v10.1.0 (*)

advisories FAILED, bans ok, sources ok

Updated: 2026-08-20 11:29:54 UTC | Commit: c522e74 | dependency-check job results

@datadog-datadog-us1-prod

datadog-datadog-us1-prod Bot commented Aug 19, 2026

Copy link
Copy Markdown

Pipelines  Tests

⚠️ Warnings

🚦 2 Pipeline jobs failed

semver-check | semver-check — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitHub Actions

Git checkout failed due to local changes in Cargo.lock that would be overwritten.

Required checks pass | allchecks

View in Datadog · View in GitHub Actions

Some checks have failed or timed out during workflow execution.

📋 Copy prompt for your agent
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.

Branch: anais/v1-agentless-encoder-brick

semver-check | semver-check
Commit: c522e7439141d62f5848a414eddfbe4ce228f765
Error (code / build):
Git checkout failed due to local changes in Cargo.lock that would be overwritten.
CI job: https://github.com/DataDog/libdatadog/actions/runs/32363811700/job/96408993728

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
Patch Coverage: 95.51%
Overall Coverage: 76.64% (+0.16%)

Useful? React with 👍 / 👎

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

@pr-commenter

pr-commenter Bot commented Aug 19, 2026

Copy link
Copy Markdown

Benchmarks

Comparison

Benchmark execution time: 2026-08-20 12:03:08

Comparing candidate commit 1a854a5 in PR branch anais/v1-agentless-encoder-brick with baseline commit 1765c7c in branch main.

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

Benchmark execution time: 2026-08-20 12:10:18

Comparing candidate commit 1a854a5 in PR branch anais/v1-agentless-encoder-brick with baseline commit 1765c7c in branch main.

Found 4 performance improvements and 2 performance regressions! Performance is the same for 162 metrics, 10 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 ----------------------------------'

scenario:alloc_free/system/4096

  • 🟩 execution_time [-21.637ns; -21.491ns] or [-20.381%; -20.244%]

scenario:datadog_sample_span/name_pattern_rule_not_matching/wall_time

  • 🟩 execution_time [-6.869ns; -6.643ns] or [-4.142%; -4.006%]

scenario:glob_matcher/unicode_pattern_ascii_subject/wall_time

  • 🟩 execution_time [-4.292ns; -4.229ns] or [-4.555%; -4.487%]

scenario:ip_address/quantize_peer_ip_address_benchmark

  • 🟥 execution_time [+419.592ns; +435.432ns] or [+8.403%; +8.720%]

scenario:profiler_attached/fast_path_system/4096

  • 🟩 execution_time [-12.230ns; -12.073ns] or [-11.639%; -11.490%]

scenario:profiler_attached/slow_path_system/4096

  • 🟥 execution_time [+24.288ns; +24.383ns] or [+18.907%; +18.980%]

Candidate

Omitted due to size.

Baseline

Omitted due to size.

@dd-octo-sts

dd-octo-sts Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Artifact Size Benchmark Report

aarch64-alpine-linux-musl
Artifact Baseline Commit Change
/aarch64-alpine-linux-musl/lib/libdatadog_profiling.a 89.47 MB 89.47 MB +0% (+16 B) 👌
/aarch64-alpine-linux-musl/lib/libdatadog_profiling.so 8.20 MB 8.20 MB 0% (0 B) 👌
aarch64-unknown-linux-gnu
Artifact Baseline Commit Change
/aarch64-unknown-linux-gnu/lib/libdatadog_profiling.a 100.65 MB 100.65 MB +0% (+8 B) 👌
/aarch64-unknown-linux-gnu/lib/libdatadog_profiling.so 11.06 MB 11.06 MB 0% (0 B) 👌
libdatadog-x64-windows
Artifact Baseline Commit Change
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.dll 26.62 MB 26.62 MB 0% (0 B) 👌
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.lib 94.56 KB 94.56 KB 0% (0 B) 👌
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.pdb 180.69 MB 180.69 MB 0% (0 B) 👌
/libdatadog-x64-windows/debug/static/datadog_profiling_ffi.lib 772.58 MB 772.59 MB +0% (+8.42 KB) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.dll 8.72 MB 8.72 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.lib 94.56 KB 94.56 KB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.pdb 25.64 MB 25.64 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/static/datadog_profiling_ffi.lib 51.06 MB 51.06 MB 0% (0 B) 👌
libdatadog-x86-windows
Artifact Baseline Commit Change
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.dll 23.20 MB 23.20 MB -0% (-512 B) 👌
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.lib 96.04 KB 96.04 KB 0% (0 B) 👌
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.pdb 185.60 MB 185.61 MB +0% (+8.00 KB) 👌
/libdatadog-x86-windows/debug/static/datadog_profiling_ffi.lib 759.08 MB 758.95 MB --.01% (-135.34 KB) 💪
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.dll 6.74 MB 6.74 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.lib 96.04 KB 96.04 KB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.pdb 27.58 MB 27.58 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/static/datadog_profiling_ffi.lib 48.60 MB 48.60 MB 0% (0 B) 👌
x86_64-alpine-linux-musl
Artifact Baseline Commit Change
/x86_64-alpine-linux-musl/lib/libdatadog_profiling.a 79.74 MB 79.74 MB 0% (0 B) 👌
/x86_64-alpine-linux-musl/lib/libdatadog_profiling.so 9.15 MB 9.15 MB 0% (0 B) 👌
x86_64-unknown-linux-gnu
Artifact Baseline Commit Change
/x86_64-unknown-linux-gnu/lib/libdatadog_profiling.a 95.38 MB 95.38 MB 0% (0 B) 👌
/x86_64-unknown-linux-gnu/lib/libdatadog_profiling.so 11.16 MB 11.16 MB 0% (0 B) 👌

Comment on lines +525 to +529
type CollectedAttrsV1<'a, T> = (
Vec<(String, String)>,
Vec<(String, f64)>,
Vec<(&'a <T as TraceData>::Text, &'a <T as TraceData>::Bytes)>,
);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

it's inferable from the typing, but I would prefer and actual struct with named field rather than an aliased tuple here

Comment on lines +542 to +546
.filter(|(k, _)| !PROMOTED_ATTR_KEYS_V1.contains(&(*k).borrow()))
.chain(chunk_attrs_dd.iter().filter(|(k, _)| {
!PROMOTED_ATTR_KEYS_V1.contains(&(*k).borrow())
&& !span_attrs_dd.iter().any(|(k2, _)| k2 == *k)
}));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is this really necessary?

We perfom len(PROMOTED_ATTR_KEYS_V1) * len(span_attr) + (len(PROMOTED_ATTR_KEYS_V1) + len(span_attr) ) * len(chunk_attr) string comparison 🤔

Span level attributes should not collide with chunk level attribute, and if they do they should be promoted before we reach the encoder IMO.

Comment on lines +499 to +501
AttributeValueV1::Bytes(_) => {
// Callers filter `Bytes` out before recursing; unreachable in practice.
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is not true
If one of the nested AttributeValueV1::List item is a Bytes attribute it is not filteredt

Comment on lines +548 to +561
let mut meta_leaves: Vec<(String, String)> = Vec::new();
let mut metrics_leaves: Vec<(String, f64)> = Vec::new();
let mut bytes_attrs: Vec<(&T::Text, &T::Bytes)> = Vec::new();
let mut key_buf = String::new();
for (k, v) in merged_attrs {
match v {
AttributeValueV1::Bytes(b) => bytes_attrs.push((k, b)),
_ => {
key_buf.clear();
key_buf.push_str(k.borrow());
flatten_attr_into_v1(&mut key_buf, v, &mut meta_leaves, &mut metrics_leaves);
}
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think we can assume that most of of attributes are scalars.
This means that the attribute key will be a single segment, that does not need flattening and we can borrow it as is from the merged_attrs.

So in order to not copy keys in the non-nested case we can use a Vec<(Cow<'a, str>, Cow<'a, str>)> and borrow the key (and values if the scalar is a string, or a value we can turn in a &'static like booleans)

Something like this I guess

Suggested change
let mut meta_leaves: Vec<(String, String)> = Vec::new();
let mut metrics_leaves: Vec<(String, f64)> = Vec::new();
let mut bytes_attrs: Vec<(&T::Text, &T::Bytes)> = Vec::new();
let mut key_buf = String::new();
for (k, v) in merged_attrs {
match v {
AttributeValueV1::Bytes(b) => bytes_attrs.push((k, b)),
_ => {
key_buf.clear();
key_buf.push_str(k.borrow());
flatten_attr_into_v1(&mut key_buf, v, &mut meta_leaves, &mut metrics_leaves);
}
}
}
let mut meta_leaves: Vec<(Cow<'a, str>, Cow<'a, str>)> = Vec::new();
let mut metrics_leaves: Vec<(Cow<'a, str>, f64)> = Vec::new();
let mut bytes_attrs: Vec<(&T::Text, &T::Bytes)> = Vec::new();
let mut key_buf = String::new();
for (k, v) in merged_attrs {
match v {
AttributeValueV1::Bytes(b) => bytes_attrs.push((k, b)),
AttributeValueV1::String(s) => meta_leaves.push(Cow::Borrowed(k.as_str(), Cow::Borrowed(s)),
// same for metrics/ bools/ints/floats
_ => {
key_buf.clear();
key_buf.push_str(k.borrow());
flatten_attr_into_v1(&mut key_buf, v, &mut meta_leaves, &mut metrics_leaves);
}
}
}

Comment on lines +563 to +564
dedup_first_wins_v1(meta_leaves),
dedup_first_wins_v1(metrics_leaves),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

why is the dedup here necessary if we already filtered out trace chunks and span attrs with the same paths?

}
_ => {}
}
metrics.serialize_entry(key, val)?;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We should skip NaN and Inf metric values as is done for the v04 encoder

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants