Skip to content

Add static char helpers like IsAsciiHexDigit#8417

Merged
andrewlock merged 3 commits into
masterfrom
andrew/client-side-stats/char-helpers
Apr 8, 2026
Merged

Add static char helpers like IsAsciiHexDigit#8417
andrewlock merged 3 commits into
masterfrom
andrew/client-side-stats/char-helpers

Conversation

@andrewlock

Copy link
Copy Markdown
Member

Summary of changes

Vendors standard .NET 7+ char/ASCII helpers, and uses them where appropriate

Reason for change

Was duplicating these standard methods in various places, I was going to be adding more, seemed a good time to explicitly vendor these properly.

Implementation details

  • Based on static char helpers methods that are available in .NET 7+
  • Created as static extension methods, so they act as true pollyfills
  • Replace the handrolled versions
  • Replace similar methods - this isn't exhaustive, and there are some potential alternative places, but they're used in places where we pattern match explicitly, and didn't want to get too much into refactoring. We can address them later as we see fit.
  • Didn't mark these for agressive inlining, because they're not marked as such in the runtime, and I trust the .NET team more than my own gut 😄

Test coverage

Added a few simple "exhaustive" unit tests for the behaviour.

Other details

Pre-requisite for client-side-stats improvements. Part of a stack

@andrewlock
andrewlock requested review from a team as code owners April 7, 2026 12:14
@andrewlock
andrewlock requested a review from a team as a code owner April 7, 2026 12:14

@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: 8c15dbe077

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

@pr-commenter

pr-commenter Bot commented Apr 7, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-04-08 11:46:30

Comparing candidate commit 46be799 in PR branch andrew/client-side-stats/char-helpers with baseline commit f9e8d09 in branch master.

Found 30 performance improvements and 37 performance regressions! Performance is the same for 214 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 ----------------------------------'

scenario:Benchmarks.Trace.ActivityBenchmark.StartStopWithChild net6.0

  • 🟩 throughput [+9583.946op/s; +11800.600op/s] or [+8.056%; +9.919%]

scenario:Benchmarks.Trace.AgentWriterBenchmark.WriteAndFlushEnrichedTraces net472

  • 🟥 execution_time [+311.927ms; +313.788ms] or [+154.789%; +155.713%]

scenario:Benchmarks.Trace.AgentWriterBenchmark.WriteAndFlushEnrichedTraces net6.0

  • 🟥 execution_time [+380.593ms; +383.645ms] or [+300.692%; +303.103%]

scenario:Benchmarks.Trace.AgentWriterBenchmark.WriteAndFlushEnrichedTraces netcoreapp3.1

  • 🟥 execution_time [+400.029ms; +401.603ms] or [+354.011%; +355.403%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleMoreComplexBody net6.0

  • 🟩 execution_time [-16.426ms; -12.243ms] or [-7.672%; -5.718%]
  • 🟩 throughput [+7461.922op/s; +10280.325op/s] or [+5.447%; +7.504%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleMoreComplexBody netcoreapp3.1

  • 🟩 throughput [+7408.806op/s; +9695.415op/s] or [+6.698%; +8.766%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleSimpleBody net6.0

  • 🟩 execution_time [-26.517ms; -21.665ms] or [-11.826%; -9.661%]
  • 🟩 throughput [+110994.332op/s; +133627.501op/s] or [+11.858%; +14.276%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleSimpleBody netcoreapp3.1

  • 🟩 throughput [+103076.590op/s; +119815.742op/s] or [+14.810%; +17.215%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorMoreComplexBody net6.0

  • 🟩 throughput [+9511.489op/s; +12535.911op/s] or [+6.052%; +7.976%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorMoreComplexBody netcoreapp3.1

  • 🟩 throughput [+7589.680op/s; +10298.201op/s] or [+6.046%; +8.204%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorSimpleBody net6.0

  • 🟩 throughput [+221656.444op/s; +262198.595op/s] or [+7.391%; +8.743%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorSimpleBody netcoreapp3.1

  • 🟩 execution_time [-19.419ms; -15.021ms] or [-8.952%; -6.924%]
  • 🟩 throughput [+203649.635op/s; +258167.547op/s] or [+8.083%; +10.247%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeArgs net472

  • 🟥 execution_time [+299.914ms; +300.482ms] or [+149.857%; +150.141%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeArgs net6.0

  • 🟥 execution_time [+299.919ms; +303.189ms] or [+151.250%; +152.899%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeArgs netcoreapp3.1

  • 🟥 execution_time [+300.139ms; +302.993ms] or [+151.187%; +152.624%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeLegacyArgs net472

  • 🟥 execution_time [+298.493ms; +299.390ms] or [+146.608%; +147.048%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeLegacyArgs net6.0

  • 🟥 execution_time [+294.479ms; +296.448ms] or [+143.960%; +144.922%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeLegacyArgs netcoreapp3.1

  • 🟥 execution_time [+299.692ms; +300.942ms] or [+149.786%; +150.410%]

scenario:Benchmarks.Trace.Asm.AppSecWafBenchmark.RunWafRealisticBenchmarkWithAttack net6.0

  • 🟥 execution_time [+26.303µs; +51.328µs] or [+8.397%; +16.386%]
  • 🟥 throughput [-461.610op/s; -256.556op/s] or [-14.390%; -7.998%]

scenario:Benchmarks.Trace.AspNetCoreBenchmark.SendRequest net472

  • 🟥 execution_time [+299.687ms; +300.303ms] or [+149.575%; +149.882%]

scenario:Benchmarks.Trace.AspNetCoreBenchmark.SendRequest net6.0

  • 🟩 throughput [+1148.462op/s; +1308.939op/s] or [+9.437%; +10.756%]

scenario:Benchmarks.Trace.AspNetCoreBenchmark.SendRequest netcoreapp3.1

  • 🟥 execution_time [+369.911ms; +373.248ms] or [+280.870%; +283.403%]
  • 🟩 throughput [+653.470op/s; +853.645op/s] or [+6.326%; +8.264%]

scenario:Benchmarks.Trace.CIVisibilityProtocolWriterBenchmark.WriteAndFlushEnrichedTraces net472

  • 🟥 throughput [-505.430op/s; -444.546op/s] or [-45.797%; -40.280%]

scenario:Benchmarks.Trace.CIVisibilityProtocolWriterBenchmark.WriteAndFlushEnrichedTraces net6.0

  • 🟥 throughput [-742.100op/s; -658.669op/s] or [-49.498%; -43.933%]

scenario:Benchmarks.Trace.CIVisibilityProtocolWriterBenchmark.WriteAndFlushEnrichedTraces netcoreapp3.1

  • 🟥 execution_time [+362.468ms; +371.313ms] or [+216.798%; +222.088%]
  • 🟥 throughput [-464.108op/s; -429.072op/s] or [-32.315%; -29.876%]

scenario:Benchmarks.Trace.CharSliceBenchmark.OriginalCharSlice net6.0

  • 🟩 execution_time [-169.530µs; -127.037µs] or [-8.588%; -6.435%]
  • 🟩 throughput [+37.166op/s; +48.492op/s] or [+7.337%; +9.573%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearch net472

  • 🟥 execution_time [+301.023ms; +302.870ms] or [+151.589%; +152.520%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearch net6.0

  • 🟥 execution_time [+300.163ms; +302.031ms] or [+150.412%; +151.348%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearch netcoreapp3.1

  • 🟥 execution_time [+300.700ms; +303.893ms] or [+151.059%; +152.663%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearchAsync net472

  • 🟥 execution_time [+301.383ms; +303.095ms] or [+151.344%; +152.204%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearchAsync net6.0

  • 🟥 execution_time [+296.278ms; +298.428ms] or [+146.496%; +147.559%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearchAsync netcoreapp3.1

  • 🟥 execution_time [+302.478ms; +306.047ms] or [+153.309%; +155.118%]

scenario:Benchmarks.Trace.GraphQLBenchmark.ExecuteAsync net472

  • 🟥 execution_time [+302.850ms; +304.364ms] or [+152.003%; +152.763%]

scenario:Benchmarks.Trace.GraphQLBenchmark.ExecuteAsync net6.0

  • 🟥 execution_time [+300.060ms; +302.432ms] or [+149.552%; +150.734%]
  • 🟩 throughput [+56895.680op/s; +61874.445op/s] or [+11.298%; +12.286%]

scenario:Benchmarks.Trace.GraphQLBenchmark.ExecuteAsync netcoreapp3.1

  • 🟥 execution_time [+299.553ms; +302.189ms] or [+149.025%; +150.336%]

scenario:Benchmarks.Trace.HttpClientBenchmark.SendAsync net472

  • 🟥 throughput [-5958.275op/s; -5653.288op/s] or [-6.802%; -6.454%]

scenario:Benchmarks.Trace.ILoggerBenchmark.EnrichedLog net6.0

  • 🟩 execution_time [-15.736ms; -12.084ms] or [-7.317%; -5.619%]
  • 🟩 throughput [+20472.918op/s; +27011.303op/s] or [+5.616%; +7.410%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatAspectBenchmark net6.0

  • 🟩 allocated_mem [-20.597KB; -20.577KB] or [-7.513%; -7.506%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatBenchmark net6.0

  • 🟥 execution_time [+5.602µs; +9.467µs] or [+13.241%; +22.377%]
  • 🟥 throughput [-4411.779op/s; -2665.044op/s] or [-18.572%; -11.219%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatBenchmark netcoreapp3.1

  • 🟩 throughput [+1585.034op/s; +3101.528op/s] or [+9.725%; +19.029%]

scenario:Benchmarks.Trace.Log4netBenchmark.EnrichedLog net472

  • 🟥 execution_time [+302.308ms; +303.650ms] or [+152.803%; +153.481%]

scenario:Benchmarks.Trace.Log4netBenchmark.EnrichedLog net6.0

  • 🟥 execution_time [+303.405ms; +305.975ms] or [+154.432%; +155.741%]

scenario:Benchmarks.Trace.Log4netBenchmark.EnrichedLog netcoreapp3.1

  • 🟥 execution_time [+299.798ms; +302.365ms] or [+150.086%; +151.371%]

scenario:Benchmarks.Trace.RedisBenchmark.SendReceive net6.0

  • 🟩 throughput [+35152.614op/s; +40340.168op/s] or [+6.654%; +7.636%]

scenario:Benchmarks.Trace.SerilogBenchmark.EnrichedLog net472

  • 🟥 execution_time [+300.362ms; +301.954ms] or [+149.704%; +150.497%]

scenario:Benchmarks.Trace.SerilogBenchmark.EnrichedLog net6.0

  • 🟥 execution_time [+302.994ms; +308.307ms] or [+152.149%; +154.817%]

scenario:Benchmarks.Trace.SerilogBenchmark.EnrichedLog netcoreapp3.1

  • 🟥 execution_time [+303.866ms; +306.417ms] or [+154.101%; +155.395%]

scenario:Benchmarks.Trace.SingleSpanAspNetCoreBenchmark.SingleSpanAspNetCore net472

  • 🟥 execution_time [+300.012ms; +300.716ms] or [+149.647%; +149.998%]
  • 🟩 throughput [+65128474.351op/s; +65431063.900op/s] or [+47.431%; +47.651%]

scenario:Benchmarks.Trace.SingleSpanAspNetCoreBenchmark.SingleSpanAspNetCore net6.0

  • 🟩 throughput [+1031.171op/s; +1201.737op/s] or [+7.971%; +9.290%]

scenario:Benchmarks.Trace.SingleSpanAspNetCoreBenchmark.SingleSpanAspNetCore netcoreapp3.1

  • 🟥 execution_time [+298.952ms; +299.882ms] or [+149.110%; +149.574%]
  • 🟩 throughput [+16263049.601op/s; +18275159.890op/s] or [+7.203%; +8.095%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishScope net6.0

  • 🟩 throughput [+94678.751op/s; +103277.960op/s] or [+8.840%; +9.643%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishSpan net6.0

  • 🟩 throughput [+90445.487op/s; +120149.975op/s] or [+7.001%; +9.300%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishSpan netcoreapp3.1

  • 🟩 throughput [+74444.276op/s; +82507.225op/s] or [+7.394%; +8.194%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishTwoScopes net6.0

  • 🟩 throughput [+55722.676op/s; +59882.845op/s] or [+10.118%; +10.874%]

scenario:Benchmarks.Trace.TraceAnnotationsBenchmark.RunOnMethodBegin net6.0

  • 🟩 throughput [+81747.132op/s; +99571.816op/s] or [+9.133%; +11.125%]

@dd-trace-dotnet-ci-bot

dd-trace-dotnet-ci-bot Bot commented Apr 7, 2026

Copy link
Copy Markdown

Execution-Time Benchmarks Report ⏱️

Execution-time results for samples comparing This PR (8417) and master.

⚠️ Potential regressions detected

HttpMessageHandler

Metric Master (Mean ± 95% CI) Current (Mean ± 95% CI) Change Status
.NET Framework 4.8 - CallTarget+Inlining+NGEN
duration1128.41 ± (1135.32 - 1144.68) ms1236.53 ± (1235.75 - 1243.74) ms+9.6%❌⬆️
Full Metrics Comparison

FakeDbCommand

Metric Master (Mean ± 95% CI) Current (Mean ± 95% CI) Change Status
.NET Framework 4.8 - Baseline
duration71.05 ± (71.20 - 71.64) ms71.33 ± (71.41 - 71.84) ms+0.4%✅⬆️
.NET Framework 4.8 - Bailout
duration75.40 ± (75.32 - 75.67) ms75.46 ± (75.54 - 75.92) ms+0.1%✅⬆️
.NET Framework 4.8 - CallTarget+Inlining+NGEN
duration1057.05 ± (1057.61 - 1063.16) ms1056.57 ± (1055.83 - 1060.96) ms-0.0%
.NET Core 3.1 - Baseline
process.internal_duration_ms22.14 ± (22.11 - 22.17) ms22.09 ± (22.06 - 22.12) ms-0.2%
process.time_to_main_ms83.61 ± (83.42 - 83.79) ms83.01 ± (82.83 - 83.19) ms-0.7%
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.89 ± (10.89 - 10.90) MB10.93 ± (10.92 - 10.93) MB+0.3%✅⬆️
runtime.dotnet.threads.count12 ± (12 - 12)12 ± (12 - 12)+0.0%
.NET Core 3.1 - Bailout
process.internal_duration_ms22.09 ± (22.06 - 22.13) ms22.04 ± (22.00 - 22.08) ms-0.2%
process.time_to_main_ms84.44 ± (84.29 - 84.59) ms84.61 ± (84.42 - 84.81) ms+0.2%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.93 ± (10.93 - 10.94) MB10.95 ± (10.95 - 10.96) MB+0.2%✅⬆️
runtime.dotnet.threads.count13 ± (13 - 13)13 ± (13 - 13)+0.0%
.NET Core 3.1 - CallTarget+Inlining+NGEN
process.internal_duration_ms224.13 ± (222.77 - 225.48) ms224.07 ± (222.74 - 225.39) ms-0.0%
process.time_to_main_ms513.88 ± (512.63 - 515.12) ms515.82 ± (514.50 - 517.14) ms+0.4%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed47.87 ± (47.84 - 47.90) MB48.33 ± (48.29 - 48.36) MB+0.9%✅⬆️
runtime.dotnet.threads.count28 ± (28 - 28)28 ± (28 - 28)+0.2%✅⬆️
.NET 6 - Baseline
process.internal_duration_ms20.91 ± (20.89 - 20.94) ms20.95 ± (20.92 - 20.98) ms+0.2%✅⬆️
process.time_to_main_ms72.11 ± (71.96 - 72.26) ms72.25 ± (72.07 - 72.44) ms+0.2%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.62 ± (10.62 - 10.63) MB10.63 ± (10.63 - 10.63) MB+0.1%✅⬆️
runtime.dotnet.threads.count10 ± (10 - 10)10 ± (10 - 10)+0.0%
.NET 6 - Bailout
process.internal_duration_ms20.85 ± (20.81 - 20.88) ms20.90 ± (20.87 - 20.92) ms+0.2%✅⬆️
process.time_to_main_ms72.82 ± (72.66 - 72.98) ms72.92 ± (72.77 - 73.08) ms+0.1%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.72 ± (10.71 - 10.72) MB10.75 ± (10.75 - 10.76) MB+0.3%✅⬆️
runtime.dotnet.threads.count11 ± (11 - 11)11 ± (11 - 11)+0.0%
.NET 6 - CallTarget+Inlining+NGEN
process.internal_duration_ms386.91 ± (384.51 - 389.31) ms385.96 ± (383.94 - 387.98) ms-0.2%
process.time_to_main_ms514.40 ± (513.59 - 515.21) ms517.47 ± (516.51 - 518.42) ms+0.6%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed50.01 ± (49.99 - 50.03) MB50.03 ± (50.01 - 50.06) MB+0.0%✅⬆️
runtime.dotnet.threads.count28 ± (28 - 28)28 ± (28 - 28)+0.0%✅⬆️
.NET 8 - Baseline
process.internal_duration_ms18.98 ± (18.95 - 19.01) ms19.15 ± (19.11 - 19.18) ms+0.9%✅⬆️
process.time_to_main_ms70.76 ± (70.60 - 70.92) ms71.30 ± (71.15 - 71.44) ms+0.8%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed7.66 ± (7.66 - 7.67) MB7.69 ± (7.68 - 7.69) MB+0.3%✅⬆️
runtime.dotnet.threads.count10 ± (10 - 10)10 ± (10 - 10)+0.0%
.NET 8 - Bailout
process.internal_duration_ms19.15 ± (19.12 - 19.19) ms19.11 ± (19.07 - 19.14) ms-0.2%
process.time_to_main_ms72.21 ± (72.08 - 72.34) ms72.30 ± (72.11 - 72.48) ms+0.1%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed7.72 ± (7.71 - 7.72) MB7.74 ± (7.74 - 7.75) MB+0.3%✅⬆️
runtime.dotnet.threads.count11 ± (11 - 11)11 ± (11 - 11)+0.0%
.NET 8 - CallTarget+Inlining+NGEN
process.internal_duration_ms305.27 ± (302.82 - 307.71) ms308.10 ± (305.95 - 310.25) ms+0.9%✅⬆️
process.time_to_main_ms474.90 ± (474.18 - 475.63) ms478.10 ± (477.36 - 478.84) ms+0.7%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed36.95 ± (36.92 - 36.98) MB37.02 ± (37.00 - 37.04) MB+0.2%✅⬆️
runtime.dotnet.threads.count27 ± (27 - 27)27 ± (27 - 27)-0.0%

HttpMessageHandler

Metric Master (Mean ± 95% CI) Current (Mean ± 95% CI) Change Status
.NET Framework 4.8 - Baseline
duration187.77 ± (187.80 - 188.45) ms191.52 ± (192.32 - 193.39) ms+2.0%✅⬆️
.NET Framework 4.8 - Bailout
duration191.59 ± (191.34 - 191.69) ms194.84 ± (194.87 - 195.47) ms+1.7%✅⬆️
.NET Framework 4.8 - CallTarget+Inlining+NGEN
duration1128.41 ± (1135.32 - 1144.68) ms1236.53 ± (1235.75 - 1243.74) ms+9.6%❌⬆️
.NET Core 3.1 - Baseline
process.internal_duration_ms183.67 ± (183.37 - 183.97) ms208.63 ± (208.02 - 209.24) ms+13.6%✅⬆️
process.time_to_main_ms79.10 ± (78.91 - 79.29) ms90.81 ± (90.52 - 91.11) ms+14.8%✅⬆️
runtime.dotnet.exceptions.count3 ± (3 - 3)3 ± (3 - 3)+0.0%
runtime.dotnet.mem.committed16.10 ± (16.01 - 16.20) MB15.89 ± (15.87 - 15.90) MB-1.4%
runtime.dotnet.threads.count19 ± (19 - 19)20 ± (20 - 20)+3.8%✅⬆️
.NET Core 3.1 - Bailout
process.internal_duration_ms183.32 ± (183.10 - 183.53) ms206.11 ± (205.54 - 206.67) ms+12.4%✅⬆️
process.time_to_main_ms80.26 ± (80.19 - 80.34) ms90.68 ± (90.42 - 90.95) ms+13.0%✅⬆️
runtime.dotnet.exceptions.count3 ± (3 - 3)3 ± (3 - 3)+0.0%
runtime.dotnet.mem.committed16.03 ± (15.92 - 16.14) MB15.98 ± (15.96 - 16.00) MB-0.3%
runtime.dotnet.threads.count20 ± (20 - 20)21 ± (21 - 21)+3.3%✅⬆️
.NET Core 3.1 - CallTarget+Inlining+NGEN
process.internal_duration_ms388.40 ± (387.05 - 389.75) ms414.79 ± (413.41 - 416.17) ms+6.8%✅⬆️
process.time_to_main_ms500.26 ± (499.29 - 501.23) ms545.20 ± (543.83 - 546.58) ms+9.0%✅⬆️
runtime.dotnet.exceptions.count3 ± (3 - 3)3 ± (3 - 3)+0.0%
runtime.dotnet.mem.committed58.17 ± (57.97 - 58.38) MB59.19 ± (59.15 - 59.23) MB+1.8%✅⬆️
runtime.dotnet.threads.count30 ± (30 - 30)30 ± (30 - 30)+1.2%✅⬆️
.NET 6 - Baseline
process.internal_duration_ms187.68 ± (187.45 - 187.92) ms207.51 ± (207.03 - 207.99) ms+10.6%✅⬆️
process.time_to_main_ms68.93 ± (68.80 - 69.05) ms76.20 ± (75.93 - 76.48) ms+10.6%✅⬆️
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed16.07 ± (15.91 - 16.23) MB16.30 ± (16.28 - 16.33) MB+1.4%✅⬆️
runtime.dotnet.threads.count18 ± (18 - 18)20 ± (19 - 20)+8.4%✅⬆️
.NET 6 - Bailout
process.internal_duration_ms186.90 ± (186.73 - 187.07) ms208.47 ± (208.00 - 208.94) ms+11.5%✅⬆️
process.time_to_main_ms69.56 ± (69.50 - 69.62) ms78.44 ± (78.22 - 78.66) ms+12.8%✅⬆️
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed15.40 ± (15.24 - 15.57) MB16.30 ± (16.27 - 16.33) MB+5.8%✅⬆️
runtime.dotnet.threads.count18 ± (18 - 18)20 ± (20 - 20)+11.4%✅⬆️
.NET 6 - CallTarget+Inlining+NGEN
process.internal_duration_ms597.05 ± (594.20 - 599.91) ms598.03 ± (595.28 - 600.78) ms+0.2%✅⬆️
process.time_to_main_ms501.78 ± (500.91 - 502.65) ms542.83 ± (541.55 - 544.10) ms+8.2%✅⬆️
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed61.64 ± (61.54 - 61.73) MB61.70 ± (61.59 - 61.80) MB+0.1%✅⬆️
runtime.dotnet.threads.count30 ± (30 - 30)31 ± (31 - 31)+1.1%✅⬆️
.NET 8 - Baseline
process.internal_duration_ms185.50 ± (185.26 - 185.74) ms206.36 ± (205.92 - 206.80) ms+11.2%✅⬆️
process.time_to_main_ms68.29 ± (68.13 - 68.45) ms76.16 ± (75.85 - 76.47) ms+11.5%✅⬆️
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed11.70 ± (11.59 - 11.80) MB11.64 ± (11.63 - 11.66) MB-0.5%
runtime.dotnet.threads.count18 ± (17 - 18)19 ± (19 - 19)+7.6%✅⬆️
.NET 8 - Bailout
process.internal_duration_ms184.40 ± (184.25 - 184.56) ms206.64 ± (206.15 - 207.13) ms+12.1%✅⬆️
process.time_to_main_ms69.12 ± (69.08 - 69.16) ms77.82 ± (77.51 - 78.13) ms+12.6%✅⬆️
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed11.27 ± (11.14 - 11.40) MB11.72 ± (11.70 - 11.74) MB+4.0%✅⬆️
runtime.dotnet.threads.count18 ± (18 - 18)20 ± (20 - 20)+9.8%✅⬆️
.NET 8 - CallTarget+Inlining+NGEN
process.internal_duration_ms522.62 ± (519.98 - 525.26) ms544.05 ± (536.78 - 551.32) ms+4.1%✅⬆️
process.time_to_main_ms460.71 ± (460.07 - 461.34) ms503.24 ± (502.29 - 504.20) ms+9.2%✅⬆️
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed50.82 ± (50.79 - 50.84) MB50.88 ± (50.80 - 50.96) MB+0.1%✅⬆️
runtime.dotnet.threads.count30 ± (30 - 30)30 ± (30 - 30)+0.9%✅⬆️
Comparison explanation

Execution-time benchmarks measure the whole time it takes to execute a program, and are intended to measure the one-off costs. Cases where the execution time results for the PR are worse than latest master results are highlighted in **red**. The following thresholds were used for comparing the execution times:

  • Welch test with statistical test for significance of 5%
  • Only results indicating a difference greater than 5% and 5 ms are considered.

Note that these results are based on a single point-in-time result for each branch. For full results, see the dashboard.

Graphs show the p99 interval based on the mean and StdDev of the test run, as well as the mean value of the run (shown as a diamond below the graph).

Duration charts
FakeDbCommand (.NET Framework 4.8)
gantt
    title Execution time (ms) FakeDbCommand (.NET Framework 4.8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (72ms)  : 68, 75
    master - mean (71ms)  : 68, 75

    section Bailout
    This PR (8417) - mean (76ms)  : 73, 78
    master - mean (75ms)  : 73, 78

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (1,058ms)  : 1022, 1095
    master - mean (1,060ms)  : 1020, 1101

Loading
FakeDbCommand (.NET Core 3.1)
gantt
    title Execution time (ms) FakeDbCommand (.NET Core 3.1)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (112ms)  : 108, 115
    master - mean (112ms)  : 108, 116

    section Bailout
    This PR (8417) - mean (113ms)  : 110, 116
    master - mean (113ms)  : 111, 116

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (780ms)  : 758, 802
    master - mean (775ms)  : 756, 794

Loading
FakeDbCommand (.NET 6)
gantt
    title Execution time (ms) FakeDbCommand (.NET 6)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (99ms)  : 96, 103
    master - mean (99ms)  : 96, 102

    section Bailout
    This PR (8417) - mean (100ms)  : 97, 102
    master - mean (99ms)  : 97, 102

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (933ms)  : 898, 968
    master - mean (929ms)  : 896, 962

Loading
FakeDbCommand (.NET 8)
gantt
    title Execution time (ms) FakeDbCommand (.NET 8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (98ms)  : 95, 101
    master - mean (97ms)  : 94, 101

    section Bailout
    This PR (8417) - mean (99ms)  : 96, 101
    master - mean (99ms)  : 97, 101

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (816ms)  : 776, 856
    master - mean (811ms)  : 770, 851

Loading
HttpMessageHandler (.NET Framework 4.8)
gantt
    title Execution time (ms) HttpMessageHandler (.NET Framework 4.8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (193ms)  : 185, 201
    master - mean (188ms)  : 185, 191

    section Bailout
    This PR (8417) - mean (195ms)  : 192, 198
    master - mean (192ms)  : 190, 193

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (1,240ms)  : crit, 1183, 1297
    master - mean (1,140ms)  : 1067, 1213

Loading
HttpMessageHandler (.NET Core 3.1)
gantt
    title Execution time (ms) HttpMessageHandler (.NET Core 3.1)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (310ms)  : 303, 317
    master - mean (271ms)  : 266, 275

    section Bailout
    This PR (8417) - mean (306ms)  : crit, 300, 313
    master - mean (271ms)  : 268, 274

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (998ms)  : crit, 972, 1025
    master - mean (918ms)  : 897, 940

Loading
HttpMessageHandler (.NET 6)
gantt
    title Execution time (ms) HttpMessageHandler (.NET 6)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (293ms)  : 286, 299
    master - mean (265ms)  : 261, 268

    section Bailout
    This PR (8417) - mean (296ms)  : crit, 288, 303
    master - mean (264ms)  : 262, 266

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (1,171ms)  : 1141, 1200
    master - mean (1,128ms)  : 1083, 1173

Loading
HttpMessageHandler (.NET 8)
gantt
    title Execution time (ms) HttpMessageHandler (.NET 8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8417) - mean (293ms)  : 286, 299
    master - mean (263ms)  : 260, 267

    section Bailout
    This PR (8417) - mean (295ms)  : crit, 288, 303
    master - mean (263ms)  : 261, 264

    section CallTarget+Inlining+NGEN
    This PR (8417) - mean (1,084ms)  : crit, 971, 1197
    master - mean (1,015ms)  : 974, 1055

Loading


internal static class CharHelpers
{
extension(char)

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.

what is this extension(char) madness?!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Pull request overview

This PR vendors the .NET 7+ ASCII/char helper APIs (as polyfills for earlier TFMs) and replaces several hand-rolled ASCII digit/hex/letter checks across the tracer with the standardized helpers.

Changes:

  • Add polyfilled ASCII char helpers (e.g., IsAsciiDigit, IsAsciiHexDigit, IsAsciiLetterOrDigit) for non-.NET 7 targets.
  • Replace local digit/hex/alpha checks in several components with char.IsAscii* helpers.
  • Add unit tests intended to exhaustively validate helper behavior.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
tracer/src/Datadog.Trace/Util/CharHelpers.cs Adds vendored ASCII char helper polyfills for pre-.NET 7.
tracer/test/Datadog.Trace.Tests/Util/CharHelpersTests.cs Adds exhaustive tests for the new helpers.
tracer/src/Datadog.Trace/Telemetry/Collectors/DependencyTelemetryCollector.cs Uses char.IsAsciiHexDigit / char.IsAsciiDigit instead of local helpers.
tracer/src/Datadog.Trace/RemoteConfigurationManagement/RemoteConfigurationPath.cs Uses char.IsAsciiDigit for digit validation in path parsing.
tracer/src/Datadog.Trace/Processors/TraceUtil.cs Uses char.IsAsciiLetter / char.IsAsciiLetterOrDigit for metric normalization.
tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/IbmMq/IbmMqHeadersAdapter.cs Uses char.IsAsciiLetterOrDigit for MQ header name normalization.
tracer/src/Datadog.Trace/Ci/CiEnvironment/CIEnvironmentValues.cs Uses char.IsAsciiHexDigit for hex validation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tracer/test/Datadog.Trace.Tests/Util/CharHelpersTests.cs
Comment thread tracer/test/Datadog.Trace.Tests/Util/CharHelpersTests.cs
Comment thread tracer/src/Datadog.Trace/Util/CharHelpers.cs Outdated
Comment thread tracer/test/Datadog.Trace.Tests/Util/CharHelpersTests.cs Outdated
Comment thread tracer/test/Datadog.Trace.Tests/Util/CharHelpersTests.cs Outdated
@andrewlock
andrewlock force-pushed the andrew/client-side-stats/char-helpers branch from 8c15dbe to 46be799 Compare April 8, 2026 10:41
@andrewlock
andrewlock merged commit d7c107b into master Apr 8, 2026
139 checks passed
@andrewlock
andrewlock deleted the andrew/client-side-stats/char-helpers branch April 8, 2026 14:23
@github-actions github-actions Bot added this to the vNext-v3 milestone Apr 8, 2026
andrewlock added a commit that referenced this pull request Apr 16, 2026
## Summary of changes

Adds the `IpAddressObfuscationUtil` helper for use by client-side stats 

## Reason for change

It's not part of the RFC, but the agent does quantization of
IPaddresses, which could appear in peer tags (which are used for stats
calculations). Without this quantization, we would end up with an
explosion of buckets

## Implementation details

Used 🤖 to port the implementation from the Go agent, including the
tests. Then iterated on it repeatedly to try to bring the allocations
down as low as possible.

⚠️ There's still one code path which is kinda nasty where we try to
parse if the tag is a valid IP v6, as it causes an allocation on .NET
Framework, but I couldn't find a way to avoid that. Given all the
allocations we're going to get _anyway_, I think we will just have to
accept it for practical reasons, unless other people feel strongly

## Test coverage

Grabbed the quantization unit tests from the agent

## Other details

Pre-requisite for client-side-stats improvements. Part of a stack:

- #8417
andrewlock added a commit that referenced this pull request Apr 20, 2026
## Summary of changes

Updates the existing client-side-stats implementation to match version
1.2.0 [as defined in the
RFC](https://datadoghq.atlassian.net/wiki/spaces/APM/pages/6378947571/Client-Side+Stats+v1.2.0)
and as [implemented in the
agent](https://github.com/DataDog/datadog-agent/blob/c1d67a906f4c594654600760da1eea4c8037471a/pkg/proto/datadog/trace/stats.proto#L83).

## Reason for change

Our implementation is severely lagging the latest implementation in the
agent. This hasn't been a big deal, as it's not documented and not
enabled by default, but we'd like to fix the implementation to make it
usable.

## Implementation details

This was driven almost entirely by 🤖, by comparing our existing
implementation to the RFC, and also taking the agent/go implementation
as the canonical implementation.

> Implementing this in .NET highlighted a number of missing aspects in
the RFC, which I've raised elsewhere, and aim to get incorporated into
the RFC.

At a high level, the PR contains the following changes:

- Stats Wire Format & Serialization
- **Added new aggregation dimensions**: `SpanKind`, `IsTraceRoot` (as
Trilean), `HTTPMethod`, `HTTPEndpoint`, `GRPCStatusCode`,
`ServiceSource`, `PeerTags` to both the aggregation key and the msgpack
wire format
- **Fixed `GRPCStatusCode` type**: Changed from `int` to `string` to
match Go agent's wire format (agent was returning 400 Bad Request in
system tests)
- **gRPC status code extraction**: Checks 4 tag names in priority order
(`rpc.grpc.status_code`, `grpc.code`, `rpc.grpc.status.code`,
`grpc.status.code`)
- **Stochastic rounding**: `Hits`, `Errors`, `Duration`, `TopLevelHits`
accumulated as `double` (weighted by sampling rate) then rounded
probabilistically to `int64` for serialization
- **Duration weighting**: Durations are now multiplied by sampling
weight (`1/rate`), matching Go agent behavior
- **Default env**: Serializes `"unknown-env"` when environment is not
configured
  - **`git_commit_sha`**: Added as optional field in stats payload
  - **`Service`**: Added as top-level field in stats payload
- **Empty bucket suppression**: `HasHits()` check prevents sending
payloads with zero-hit buckets (stale keys retained for sketch reuse)
- Bucket Timing
- **10-second alignment**: Bucket `Start` timestamps aligned to
10-second boundaries (`ts - ts % 10_000_000_000`) matching Go tracer's
`alignTs`
- **Removed unused `StartTime`** property (only `Start` as aligned
nanoseconds)
- Agent Discovery (`/info` Endpoint)
- **`peer_tags`**: Parsed, sorted, deduplicated; used for peer tag
extraction on client/producer/consumer spans
- **`span_kinds_stats_computed`**: Parsed to override eligible span
kinds
  - **`obfuscation_version`**: Parsed for obfuscation negotiation
- **Trace filters**: Parsed `filter_tags`, `filter_tags_regex`,
`ignore_resources` from `/info`
- Trace Filtering
- **`TraceFilter` implementation**: Evaluates agent-configured filters
(exact tags, regex tags, resource patterns) against root spans before
stats computation
- **Tag-only filters**: Handles filter entries that match on tag key
presence without a specific value
- SQL Obfuscation
- **Operator splitters**: Added `* / = < > ! & ^ % ~ ? @ : #` as token
splitters (matching Go agent's `go-sqllexer` `isOperator()`) so queries
like `WHERE id='1'` are properly obfuscated
- **Whitespace normalization**: Post-processing pass adds spaces around
comparison operators (`=`, `<`, `>`, `!`) adjacent to `?` placeholders,
matching Go agent's normalizer output (e.g., `id='1'` → `id = ?`)
- **Obfuscation gating**: Only runs when `obfuscation_version` is
negotiated with agent; sends `Datadog-Obfuscation-Version` header
- Peer Tags
- **IP quantization**: Peer tag values run through
`IpAddressObfuscationUtil.QuantizePeerIpAddresses()` replacing
non-allowed IPs with `"blocked-ip-address"`
- **Base service handling**: Internal/missing-kind spans with
non-default service name use `_dd.base_service:{serviceName}` as sole
peer tag
- **FNV-1a hashing**: Peer tags hashed with null-byte separators for
aggregation key
- Other
- **No retries for stats**: Stats sends are fire-and-forget (retry limit
= 0)
- **Synthetics detection**: Uses `StartsWith("synthetics")` prefix
matching (not exact match)
- **Mock agent updates**: Test mock agent returns `obfuscation_version`
in `/info` response

## Test coverage

There's a _lot_ going on in this PR, because we were so far behind. I
_could_ split this into implementing individual features, but there
would be a lot of duplication between PRs, and it didn't seem like it
would be that easy to track. At least with this big bang we can compare
directly against the system tests etc.

The existing system tests for stats computation were checked, and made
to pass (which identified a number of hidden expectations which will be
added to the RFC). I'll create a PR to enable these in the system-tests
repo

## Other details

Part of a stack

- #8417
- #8418

There are still some _theoretical_ gaps between the go implementation
and the .NET implementation, but I _think_ these are non-issues in
_most_ cases:


  | Area | Gap | Impact |
  |------|-----|--------|
| gRPC status code normalization | Go agent normalizes string statuses
(e.g., `"CANCELLED"` → `"1"`); .NET passes raw tag value | Stats
mismatch if gRPC library uses string-form status codes |
| HTTP status code tags | Go agent checks both `http.status_code` and
`http.response.status_code` (OTel convention); .NET only checks
`http.status_code` | OTel spans using newer convention would get `0` in
.NET |
| Duration precision truncation | Go agent uses float bit masking; .NET
uses integer shifting — both target ~10 bits but may produce slightly
different values | Minor histogram differences |
| SQL obfuscation | Go agent uses full tokenizer + normalizer; .NET uses
character-level splitter with targeted normalization around comparison
operators only | Complex SQL with unusual formatting may produce
different resource strings |
| `HTTP_method` / `HTTP_endpoint` | .NET always populates from span
tags; Go agent only populates from newer OTel pipeline paths | Creates
different aggregation keys — Go groups all methods/routes together in
default path |
| `_top_level` metric | Go checks both `_top_level` and `_dd.top_level`;
.NET only checks `_dd.top_level` | Spans using older metric name would
be missed by .NET |
| `span_derived_primary_tags` | Still in Go agent code but implemented
in v1.3.0 RFC, which was reverted; removed from .NET | No current
impact; may need to re-add if spec reverts back |

There is another big elephant in the room, which is perf. The peer tags,
in particular, currently requires a _bunch_ of allocation. I'd rather
defer trying to fight against that to another PR if possible, unless
anyone has some clear ideas 😄

Another aspect I'm not sure about is how this interacts with
@zacharycmontoya's recent work to publish OTLP stats. I took a random
guess and fought the refactoring, but need to verify it.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Lucas Pimentel <[email protected]>
andrewlock added a commit that referenced this pull request Apr 20, 2026
## Summary of changes

Extracts `ContainsSpanId` from `TraceChunkModel` to `SpanCollection`

## Reason for change

I need to find a given span in a `SpanCollection` for client-side-stats.
The algorithm used by `TraceChunkModel` does it "properly" (by stating
from the last span when looking for a root span), so it seems to make
sense to move this method to `SpanCollection`. Additionally, this
essentially hides some of the internals about the `SpanCollection` type,
so seems like a better place for it anyway.

## Implementation details

- Move the `IndexOf()` method from `TraceChunkModel` to `SpanCollection`
- Switch it to `Contains()` instead, seeing as the index is never
actually used AFAICT. It's easy to switch it back later if we _do_ need
it.

## Test coverage

Added some unit tests for the method

## Other details


Part of a stack

- #8417
- #8418
- #8420
andrewlock added a commit that referenced this pull request Apr 21, 2026
## Summary of changes

Updates the processing pipeline for client side stats

## Reason for change

The bulk of the CSS 1.2.0 work was done in #8420, but the
span-processing pipeline wasn't the same as the Go agent:

| Step | Go Agent  | .NET Tracer                            |
| ---- | --------- | -------------------------------------- |
| 1    | Normalize | Normalize + Obfuscate (`ProcessTrace`) |
| 2    | Filter    | Filter + Sample (`ShouldKeepTrace`)    |
| 3    | Obfuscate |                                        |
| 4    | Sample    |                                        |
| 5    | Stats     | Stats (`AddRange`)                     |


## Implementation details

The difference was mostly due to the way we had separate
`ProcessTrace()` and `ShouldKeepTrace()` methods. By merging them, we
can encapsulate the pipeline, and ensure that we mirror the way the Go
agent processes traces.

Additionally, there are two different mechanisms for dropping spans now
- p0drops and "trace filtering", so added a new metric tag
`reason:trace_filter` for it.

Additionally, made some small optimizations:
- No need for an array of `ITraceProcessor` when it only contains one
- Updated `TraceFilter` algorithm to correctly look for local trace
root, starting from last span
- Made `_statsAggregator` non-null in `AgentWriter` to eliminate a bunch
of null checks

## Test coverage

Covered by existing tests.

## Other details

Part of a stack:
- #8417
- #8418
- #8420
- #8435
andrewlock added a commit that referenced this pull request Apr 21, 2026
## Summary of changes

Improves the performance of peer-tag hash calculation for "fast path"
cases (where there's an existing bucket)

## Reason for change

We have to calculate the hash of all peer tags as part of
client-side-stats bucketing calculations, which involves encoding them
as utf-8. Additionally, when we _send_ the buckets, we have to send the
tags as utf-8.

In the initial CSS 1.2.0 implementation, we encoded the tags every-time
we ran a calculation, which would allocate for every span that had peer
tags, generally quite expensive. In this PR, we switch to doing the
encoding twice: once with a zero-allocation implementation (amortized 0
on .NET Framework) to calculate the hash, and then, _if_ we need the
"real" encoded tags, then we do that encoding again.

## Implementation details

- Split the peer tags work in two, once to calculate the peer tags hash,
once to get the actual tags as `key:value`
- In the hash-calculation stage, we can use `stackalloc` for .NET Core,
and array pool implementation for .NET Framework etc
- As additional optimizations, we also 
- Pre-encode the peer tag _keys_ to utf-8, so that we only need to do
those once for the hash calculation.
- Pass key details from `BuildKey` to `GetEncodedPeerTags` (i.e. is this
a "base service" only tag, if so, what's the tag value, otherwise how
big does the peer tag list need to be)
- If client-side stats is disabled, don't bother doing all the
pre-calculation (or for trace filters)

There are some possible future optimizations, _not_ implemented in this
PR:
- Track which tags require IP quantization to avoid re-doing it. (Maybe
we should allow-list the quantization anyway, so that it only applies to
specific tags? Or alternatively, block list?)
- Instead of doing the encoding of `tag:value`, allow writing the
pre-computed `byte[]` to `MessagePackBinary` and appending the `value`.
This is doable, but requires updating the `MessagePackBinary`
implementation to support it, so I considered it out of scope for now

## Test coverage

Mostly covered by existing tests, but added some additional unit tests
that directly compare the hashing to values used in Go agent tests.

Additionally did some benchmarking. The key thing is that the
`ClientSpanWithPeerTags` path is zero-allocation (and it's nice that the
slow-path is still lower allocation than before, even if it's slower
over all)

| Method | Runtime | Mean | Error | Allocated |
| -------------------------------------------------- |
------------------ | ----------: | ---------: | --------: |
| BuildKey_SimpleSpan_Before | .NET 10.0 | 44.34 ns | 0.906 ns | - |
| BuildKey_SimpleSpan_After | .NET 10.0 | 39.17 ns | 0.445 ns | - |
| BuildKey_SimpleSpan_Before | .NET 6.0 | 93.13 ns | 1.837 ns | - |
| BuildKey_SimpleSpan_After | .NET 6.0 | 87.56 ns | 0.839 ns | - |
| BuildKey_SimpleSpan_Before | .NET Core 3.1 | 192.53 ns | 2.572 ns | -
|
| BuildKey_SimpleSpan_After | .NET Core 3.1 | 217.32 ns | 4.362 ns | - |
| BuildKey_SimpleSpan_Before | .NET Framework 4.8 | 131.98 ns | 2.621 ns
| - |
| BuildKey_SimpleSpan_After | .NET Framework 4.8 | 175.20 ns | 7.647 ns
| - |
| | | | | |
| BuildKey_ClientSpanNoPeerTags_Before | .NET 10.0 | 160.62 ns | 2.622
ns | - |
| BuildKey_ClientSpanNoPeerTags_After | .NET 10.0 | 151.27 ns | 1.995 ns
| - |
| BuildKey_ClientSpanNoPeerTags_Before | .NET 6.0 | 243.62 ns | 3.199 ns
| - |
| BuildKey_ClientSpanNoPeerTags_After | .NET 6.0 | 232.55 ns | 2.975 ns
| - |
| BuildKey_ClientSpanNoPeerTags_Before | .NET Core 3.1 | 550.47 ns |
9.998 ns | - |
| BuildKey_ClientSpanNoPeerTags_After | .NET Core 3.1 | 680.42 ns |
10.022 ns | - |
| BuildKey_ClientSpanNoPeerTags_Before | .NET Framework 4.8 | 442.88 ns
| 8.854 ns | - |
| BuildKey_ClientSpanNoPeerTags_After | .NET Framework 4.8 | 682.12 ns |
13.468 ns | - |
| | | | | |
| BuildKey_ClientSpanWithPeerTags_Before | .NET 10.0 | 800.82 ns |
15.062 ns | 840 B |
| BuildKey_ClientSpanWithPeerTags_After | .NET 10.0 | 575.04 ns | 5.604
ns | - |
| BuildKey_ClientSpanWithPeerTags_Before | .NET 6.0 | 1,076.07 ns |
13.124 ns | 840 B |
| BuildKey_ClientSpanWithPeerTags_After | .NET 6.0 | 1,440.26 ns |
28.755 ns | - |
| BuildKey_ClientSpanWithPeerTags_Before | .NET Core 3.1 | 1,531.27 ns |
13.509 ns | 840 B |
| BuildKey_ClientSpanWithPeerTags_After | .NET Core 3.1 | 1,774.35 ns |
89.601 ns | - |
| BuildKey_ClientSpanWithPeerTags_Before | .NET Framework 4.8 | 1,682.15
ns | 17.082 ns | 859 B |
| BuildKey_ClientSpanWithPeerTags_After | .NET Framework 4.8 | 2,040.90
ns | 162.895 ns | - |
| | | | | |
| BuildKey_ClientSpanWithPeerTags_GetEncodedPeerTags | .NET 10.0 |
1,141.85 ns | 9.980 ns | 760 B |
| BuildKey_ClientSpanWithPeerTags_GetEncodedPeerTags | .NET 6.0 |
2,720.55 ns | 53.097 ns | 760 B |
| BuildKey_ClientSpanWithPeerTags_GetEncodedPeerTags | .NET Core 3.1 |
3,534.28 ns | 141.234 ns | 760 B |
| BuildKey_ClientSpanWithPeerTags_GetEncodedPeerTags | .NET Framework
4.8 | 3,438.80 ns | 84.352 ns | 778 B |


<details><summary>Details</summary>
<p>

```csharp
// <copyright file="StatsAggregatorBenchmark.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Datadog.Trace;
using Datadog.Trace.Agent;
using Datadog.Trace.Agent.DiscoveryService;
using Datadog.Trace.Configuration;
using Datadog.Trace.Tagging;

namespace Benchmarks.Trace;

/// <summary>
/// StatsAggregator.BuildKey benchmarks
/// </summary>
[MemoryDiagnoser]
[BenchmarkCategory(Constants.TracerCategory)]
public class StatsAggregatorBenchmark
{
    private static readonly List<StatsAggregator.PeerTagKey> PeerTagKeys =
    [
        new("_dd.base_service"),
        new("aws.queue.name"),
        new("aws.queue.url"),
        new("aws.s3.bucket"),
        new("aws.stream.name"),
        new("bucketname"),
        new("db.couchbase.seed.nodes"),
        new("db.hostname"),
        new("db.instance"),
        new("db.system"),
        new("messaging.destination"),
        new("messaging.kafka.bootstrap.servers"),
        new("messaging.rabbitmq.exchange"),
        new("messaging.system"),
        new("network.destination.name"),
        new("peer.hostname"),
        new("peer.service"),
        new("server.address"),
        new("topic"),
    ];

    private StatsAggregator _aggregator;
    private Span _simpleSpan;
    private Span _clientSpanNoPeerTags;
    private Span _clientSpanWithPeerTags;
    private StatsAggregationKey _key;
    private List<byte[]> _encoded;

    [GlobalSetup]
    public void GlobalSetup()
    {
        _aggregator = new StatsAggregator(
            new NoOpApi(),
            new TracerSettings(),
            NullDiscoveryService.Instance,
            isOtlp: false);

        var now = DateTimeOffset.UtcNow;

        // Simple span: no span kind, no peer tags — exercises the "internal" fast path
        _simpleSpan = CreateSpan(now, "web-service", "web.request", "GET /api/users", "web");

        // Client span with SpanKind but no matching peer tags — iterates peer tag keys but finds nothing
        var clientTags = new HttpTags { HttpMethod = "GET", HttpStatusCode = "200" };
        _clientSpanNoPeerTags = CreateSpan(now, "web-service", "http.request", "GET /api/orders", "http", clientTags);

        // Client span with several peer tags set — the most expensive path
        var peerTags = new HttpTags { HttpMethod = "POST", HttpStatusCode = "200" };
        _clientSpanWithPeerTags = CreateSpan(now, "web-service", "http.request", "POST /api/data", "http", peerTags);
        _clientSpanWithPeerTags.Tags.SetTag("peer.service", "remote-service");
        _clientSpanWithPeerTags.Tags.SetTag("db.instance", "i-1234");
        _clientSpanWithPeerTags.Tags.SetTag("db.system", "postgres");
        _clientSpanWithPeerTags.Tags.SetTag("server.address", "db.example.com");
        _clientSpanWithPeerTags.Tags.SetTag("network.destination.name", "db.example.com");

    }

    [GlobalCleanup]
    public void GlobalCleanup()
    {
        _aggregator.DisposeAsync().GetAwaiter().GetResult();
        var value = _key;
        var encoded = _encoded;
    }

    /// <summary>
    /// BuildKey for a simple span with no span kind (internal fast-path, no peer tag iteration).
    /// </summary>
    [Benchmark]
    public void BuildKey_SimpleSpan()
    {
        _key = _aggregator.BuildKey(_simpleSpan, PeerTagKeys, out _);
    }

    /// <summary>
    /// BuildKey for a client span that has no matching peer tags (iterates all peer tag keys, finds none).
    /// </summary>
    [Benchmark]
    public void BuildKey_ClientSpanNoPeerTags()
    {
        _key = _aggregator.BuildKey(_clientSpanNoPeerTags, PeerTagKeys, out _);
    }

    /// <summary>
    /// BuildKey for a client span with several peer tags set (UTF-8 encoding + FNV hashing).
    /// </summary>
    [Benchmark]
    public void BuildKey_ClientSpanWithPeerTags()
    {
        _key = _aggregator.BuildKey(_clientSpanWithPeerTags, PeerTagKeys, out var results);
    }

    /// <summary>
    /// BuildKey for a client span with several peer tags set (UTF-8 encoding + FNV hashing).
    /// </summary>
    [Benchmark]
    public void BuildKey_ClientSpanWithPeerTags_GetEncodedPeerTags()
    {
        _key = _aggregator.BuildKey(_clientSpanWithPeerTags, PeerTagKeys, out var results);
        _encoded = StatsAggregator.GetEncodedPeerTags(_clientSpanWithPeerTags, PeerTagKeys, in results);
    }

    private static Span CreateSpan(DateTimeOffset start, string serviceName, string operationName, string resourceName, string type, ITags tags = null)
    {
        var tracer = Benchmarks.Trace.Asm.EmptyDatadogTracer.Instance;
        var traceContext = new TraceContext(tracer);
        var context = new SpanContext(null, traceContext, serviceName);
        var span = new Span(context, start, tags);
        span.OperationName = operationName;
        span.ResourceName = resourceName;
        span.Type = type;
        return span;
    }

    private sealed class NoOpApi : IApi
    {
        public TracesEncoding TracesEncoding => TracesEncoding.DatadogV0_4;

        public Task<bool> Ping() => Task.FromResult(true);

        public Task<bool> SendTracesAsync(ArraySegment<byte> traces, int numberOfTraces, bool statsComputationEnabled, long numberOfDroppedP0Traces, long numberOfDroppedP0Spans, bool apmTracingEnabled = true)
            => Task.FromResult(true);

        public Task<bool> SendStatsAsync(StatsBuffer stats, long bucketDuration, int tracerObfuscationVersion)
            => Task.FromResult(true);
    }
}
```

</p>
</details> 


## Other details


Part of a stack:
- #8417
- #8418
- #8420
- #8435
- #8436
- #8444
andrewlock added a commit that referenced this pull request Apr 23, 2026
## Summary of changes

Removes the minimum-agent version check from the client-side-stats check

## Reason for change

We didn't have it before, which means people who previously had stats,
suddenly won't have them. Also other agents (like bottlecap etc) don't
have the version. And we haven't figured out how to handle that yet.
While CSS is off by default, this seems like the best option to take.

## Implementation details

Remove the code that is checking for CSS support.

## Test coverage

Covered by existing (and removed a test for the behaviour)

## Other details

Follows on from 
- #8417
- #8418
- #8420
- #8435
- #8436
- #8444
- #8445
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.

4 participants