Skip to content

perf(kafka): trim the DSM produce/consume hook hot path - #22121

Draft
labbati wants to merge 4 commits into
labbati/dsm2-794-python-dsm-performance-overheadfrom
labbati/dsm2-904-python-dsm-round-2-hot-path
Draft

labbati wants to merge 4 commits into
labbati/dsm2-794-python-dsm-performance-overheadfrom
labbati/dsm2-904-python-dsm-round-2-hot-path

Conversation

@labbati

@labbati labbati commented Nov 26, 2026

Copy link
Copy Markdown
Member

Stacked on #21963. Python-only, behavior-preserving changes to the Kafka DSM hooks (DSM2-794):

  • Look up produce arguments without raising exceptions.
  • Measure consume headers and find the pathway header in one pass; fast byte-size path for plain str/bytes.
  • Import the DSM processor accessor once at module level.
  • Slimmer set_checkpoint: cached str(hash), arithmetic header length, one thread-local read, one bucket lookup.

Stats are unchanged (hashes, parents, payload sizes, counts), pinned by new tests. One difference: malformed consumed headers now record size 0 instead of raising ValueError.

Speedlab numbers to follow (DSM share = (apm+dsm − apm-only)/(apm-only − baseline)).

Read value, key and the delivery callback from kwargs/args with membership
and length checks instead of get_argument_value/set_argument_value, which
raised and caught up to ~8 exceptions per produced message. Behavior is
unchanged, including leaving positional callbacks unwrapped. A unit test
pins argument lookup and callback wrapping.

DSM2-903
Add exact str/bytes fast paths to _calculate_byte_size (ASCII strings are
measured without encoding). On consume, compute the header size and collect
the pathway headers in a single loop instead of also building dict(headers).
Repeated keys keep last-wins semantics. Tests pin byte sizes and the consume
hook's payload size and parent pathway.

DSM2-901
Import data_streams_processor at module level instead of on every hook call;
it is now defined before the integration imports in
ddtrace.internal.datastreams so the kafka module can import it without a
cycle. Drop the hasattr(message, "len") check: confluent_kafka.Message has
no len() method, so the value was always measured.

DSM2-902
- Cache str(hash) next to the pathway hash so tagging a span does not
  format it on every checkpoint.
- Compute the produce pathway header length arithmetically instead of
  encoding the context to measure it.
- Read the thread-local context once.
- Look up the stats bucket once in on_checkpoint_creation and join the
  edge tags outside the lock.

The hash cache stays keyed on tuple(tags) and base_hash_bytes: keying it
on the comma-joined tags could collide for tags containing commas.
on_checkpoint_creation remains the single aggregation path rather than
being inlined into DataStreamsCtx.set_checkpoint. Tests pin the header
size, span tag, and serialized stats.

DSM2-904
@linear-code

linear-code Bot commented Nov 26, 2026

Copy link
Copy Markdown

DSM2-904

@cit-pr-commenter-54b7da

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

@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against labbati/dsm2-794-python-dsm-performance-overhead using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/internal/datastreams/__init__.py                                @DataDog/data-streams-monitoring
ddtrace/internal/datastreams/kafka.py                                   @DataDog/data-streams-monitoring
ddtrace/internal/datastreams/processor.py                               @DataDog/data-streams-monitoring
ddtrace/internal/datastreams/utils.py                                   @DataDog/data-streams-monitoring
tests/contrib/kafka/test_kafka_dsm.py                                   @DataDog/data-streams-monitoring
tests/datastreams/test_byte_size.py                                     @DataDog/data-streams-monitoring
tests/datastreams/test_encoding.py                                      @DataDog/data-streams-monitoring
tests/datastreams/test_processor.py                                     @DataDog/data-streams-monitoring

@pr-commenter

pr-commenter Bot commented Nov 26, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-26 13:47:40

Comparing candidate commit 7d5fc46 in PR branch labbati/dsm2-904-python-dsm-round-2-hot-path with baseline commit 2fe7ace in branch labbati/dsm2-794-python-dsm-performance-overhead.

📊 Benchmarking dashboard

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

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 [-714.024ns; +715.899ns] or [-6.660%; +6.678%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-35.571ns; +40.140ns] or [-5.541%; +6.253%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1901.432ns; +1776.944ns] or [-9.510%; +8.887%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1983.721ns; +1638.203ns] or [-10.045%; +8.295%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-372.406ns; +368.385ns] or [-8.699%; +8.605%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-216.977ns; +230.564ns] or [-8.065%; +8.570%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-82.639ns; +89.036ns] or [-6.285%; +6.772%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4794.497ns; +4324.291ns] or [-9.782%; +8.822%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-822.068ns; +1036.728ns] or [-7.980%; +10.063%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-44.011µs; +34.671µs] or [-7.502%; +5.910%]

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant