Skip to content

Fix batch span processor benchmark accounting and latency measurement - #9070

Draft
friscoMad wants to merge 1 commit into
open-telemetry:mainfrom
friscoMad:codex/fix-bsp-benchmarks
Draft

friscoMad wants to merge 1 commit into
open-telemetry:mainfrom
friscoMad:codex/fix-bsp-benchmarks

Conversation

@friscoMad

@friscoMad friscoMad commented Nov 26, 2026 •

Copy link
Copy Markdown

The batch span processor benchmarks can lose counts through integer division, sum drop ratios across iterations and forks, and read metrics before the queue drains. Some fixtures resubmit unended spans or schedule asynchronous work for a zero-delay exporter. This PR fixes the measurement harness before changing the processor in #9068.

There are no production-code changes. Merge this PR first; #9068 contains the worker implementation and concurrency tests.

Previous benchmarks and their replacements

Previous benchmark Previous workload and limitations New workload / replacement
BatchSpanProcessorBenchmark Five producer threads repeatedly passed a pre-created list of unended spans to processor.onEnd(), then waited for forceFlush(). Parameters covered 1000/2000/5000 spans and 0/1/5 ms exporter delays. The tracer provider had no processor, so the fixture could return non-recording spans that fail the ReadableSpan cast. No exported/dropped accounting accompanied its primary score. Retained as the burst-and-flush benchmark. Each operation creates and ends spanCount real sampled spans through the SDK, then waits for a checked flush. Five producers and the three span counts remain. It now includes span creation/end and complete span accounting. The primary result is bursts/s, not spans/s.
BatchSpanProcessorFlushBenchmark The same burst loop, explicit flush, thread count, parameters, and JMH defaults as BatchSpanProcessorBenchmark; it was not a separate flush-only latency measurement. Removed as a duplicate. Its workload is covered by BatchSpanProcessorBenchmark, including the flush. This consolidates an existing duplicate; removing the old benchmark name is not required by the accounting fix.
BatchSpanProcessorMultiThreadBenchmark Unpaced producers at 1/2/5/10/20 threads created spans and called processor.onEnd() directly. The default exporter delay was 0 ms, but exports still used a scheduled executor. Metrics were read before shutdown drained the queue; auxiliary counts were divided among threads and the drop ratio was normalized before JMH summed it. Retained with the same thread-count entry points. Each invocation creates and ends one real sampled span. It uses the shared fixture, a synchronous no-op exporter by default, and raw attempted/exported/dropped counters collected after draining. Primary throughput still counts attempts, including dropped spans; use the export count and drop fraction alongside it.
BatchSpanProcessorDroppedSpansBenchmark The same five-producer, unpaced, zero-delay workload covered by MultiThreadBenchmark.export_05Thread(), with longer iterations and separate lifecycle/counter code. Its provider also lacked the processor, and shutdown was not awaited. Removed. Use BatchSpanProcessorMultiThreadBenchmark.export_05Thread() and its corrected counters. The old benchmark's 20-second measurement duration is not retained as the default; longer iterations can still be selected with -r 20s.
BatchSpanProcessorCpuBenchmark The same five thread-count variants, with a 100 µs parkNanos after each submission inside the timed operation. Its default exporter delay was 1 ms. The comment treated the sleep as a fixed 10k spans/s per thread, although work and scheduling also consume time. Auxiliary counters were exposed as operation rates. Retained as a paced CPU-profiling workload. It creates/ends a span and keeps the relative 100 µs park inside the timed operation. Throughput therefore includes pacing and is not span-end latency or a guaranteed arrival rate. It now shares raw event counters and reports worker CPU; its default exporter changes to the common 0 ms synchronous no-op. Use -p delayMs=1 for the asynchronous delaying exporter.
No previous equivalent None of the old primary scores isolated the public Span.end() call from span creation, pacing, or an explicit flush. New BatchSpanProcessorSpanEndBenchmark: SampleTime results in ns for one or ten producers. Span creation and deadline pacing run in an invocation setup fixture; only span.end() is in the benchmark method. The target defaults to 10,000 spans/s per producer and is configurable. Missed arrival slots are counted and skipped, rather than replayed as catch-up bursts. Runs reject any dropped spans and iteration batch sizes other than one, which would otherwise end the same prepared span repeatedly.

The old and new scores are not directly comparable across harness versions: the new throughput workloads measure real span creation/end, the zero-delay exporter behaves differently, and the counters cover a complete iteration. Before/after processor comparisons must use the same corrected harness on both variants. Those implementation measurements are in #9068.

Defaults and parameter coverage

Benchmark family Previous default run New default run
Burst / flush 1 fork; 5 × 1s warm-up; 10 × 1s measurement 3 forks; 3 × 2s warm-up; 5 × 2s measurement
Multi-thread / CPU 1 fork; 1 × 1s warm-up; 5 × 5s measurement 3 forks; 3 × 2s warm-up; 5 × 2s measurement
Dropped spans 1 fork; 5 × 1s warm-up; 5 × 20s measurement Consolidated into the five-producer multi-thread case
New span-end latency — 3 forks; 3 × 2s warm-up; 5 × 2s measurement

The shared defaults are delayMs=0, maxQueueSize=2048, and maxExportBatchSize=512. The default burst matrix now covers the three span counts at delay 0; -p delayMs=0,1,5 restores the previous delay matrix. Positive delays use the existing asynchronous DelayingSpanExporter; delay 0 uses SpanExporter.noop() to avoid an executor handoff in queue-focused measurements. Set maxExportBatchSize=1 to exercise frequent worker notifications. Fork counts, warm-up, and measurement durations remain overridable through JMH.

Shared-state refactor

Previously each benchmark owned its provider/exporter setup, shutdown, metrics snapshots, and thread-local counter adapter. Those copies disagreed about lifecycle level, shutdown completion, counter type, and when metrics were collected. The refactor separates shared resources from per-producer bookkeeping:

  • BatchSpanProcessorBenchmarkState, Scope.Benchmark: one fixture shared by the producers. It owns the exporter, processor through its SdkTracerProvider, tracer, meter provider, metric reader, configuration parameters, and final snapshots. Provider resources are created afresh for each iteration, including for the burst benchmark that previously used a trial-scoped processor. The processed-span telemetry version is explicitly selected so all cases read the same legacy metric names.
  • ProducerState, Scope.Thread: each producer registers once and owns its attempt count and skipped-slot count, reset each iteration. Attempts use a thread-local increment, with aggregation after producers stop. Burst operations count each span, not just each JMH invocation.
  • Counters, Scope.Thread, AuxCounters.Type.EVENTS: throughput cases publish each producer's attempts and raw shared export/drop/elapsed/CPU totals. Only producer index zero publishes the shared totals; other producers return zero for those fields. This avoids duplicated totals and integer division that loses remainders. Getters are declared on the counter class so JMH discovers them. Ratios are computed from aggregated totals rather than emitted as summable auxiliary counters.
  • Latency SpanState: reuses producer registration/accounting and adds a prepared span and deadline schedule. It does not use auxiliary counters because JMH SampleTime does not support them; the same final accounting is available in stdout ledger records.

Iteration teardown runs after JMH's producer barrier. It waits for a successful flush, records elapsed time through that final drain, reads the exported/dropped metrics, sums producer attempts, and checks attempted = exported + dropped. Latency cases additionally require zero drops. It then samples worker CPU, prints one BSP_LEDGER record outside the timed workload, and closes resources in cleanup paths. The fixture closes the tracer provider, interrupts and joins its captured worker after shutdown so an old worker cannot overlap the next iteration, and closes the meter provider. Queue-full logging is disabled for the trial and its previous level is restored afterward.

BatchSpanProcessorMetrics now sums all matching metric points and returns their full values. It no longer divides counts by the producer count, selects only the first matching point, or calculates dropRatio. The SDK's export metric counts submissions to the exporter, not downstream delivery acknowledgments; with the successful no-op exporter those submissions also complete successfully.

Counter interpretation is explicit:

  • Drop fraction: sum(droppedSpans) / sum(attemptedSpans).
  • Complete-iteration export rate: 1e9 * sum(exportedSpans) / sum(elapsedNanos).
  • Worker CPU fraction of one core: sum(exporterCpuNanos) / sum(elapsedNanos).

Ledger elapsed time includes JMH synchronization work around the measured loop and the final drain, so it must not be mixed with the primary score's measured interval. Worker CPU is thread lifetime CPU sampled before shutdown; it excludes producer threads and asynchronous exporter executor threads. Unavailable CPU accounting is NaN. Sampled latency has invocation/timer overhead and covers executed calls; skipped slots and achieved load must accompany tail comparisons. It is not an open-loop event-loop-lag measurement or a worst-case latency bound.

Tests and validation

Three new fixture tests check the final drain and exact totals across uneven producer counts, detection of missing spans, and summation across metric points. sdk/trace/build.gradle.kts makes JMH output and jmh-core available to the test source set so those tests exercise the actual benchmark fixture. This also means ordinary trace tests compile the JMH sources; no dependency is added to the published SDK runtime.

  • ./gradlew :spotlessCheck :sdk:trace:check --continue --console=plain --max-workers=4 passes using JDK 25, including root Markdown formatting and the trace module's tests, formatting, static analysis, and API checks.
  • The standalone benchmark branch passes 352 tests: 322 regular tests and 30 incubating tests. Its Java 11 test run also passes.
  • All 13 retained JMH entry points pass short forked Java 11 smoke runs with the original worker implementation, and the throughput auxiliary counters preserve attempted = exported + dropped. Smoke timings validate the harness and are not performance claims.
  • The benchmark README is formatted by the root :spotlessFlexmarkApply task. Markdown formatting is configured only on the root project; :sdk:trace:spotlessApply alone does not cover it. This fixes the :spotlessFlexmarkCheck failure reported by the Ubuntu, macOS, and Windows builds.

AI-assisted implementation, tests, and analysis with Codex (GPT-6), with additional Codex review. AI credit is retained in Assisted-by and this description.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

CLA Not Signed

@opentelemetry-pr-dashboard

Copy link
Copy Markdown

Pull request dashboard status

Waiting on the author · refreshed 2026-11-26 12:45 UTC

Move out of draft to request review.

Status above doesn't look right?
  • Just replied or pushed? Anything around or after the refresh time above may not be picked up yet — give it a few minutes.
  • Anything look wrong? Report it with what you expected; it helps us improve the dashboard.

Drain before collecting raw counters, use a synchronous no-op exporter for
queue-focused workloads, and report worker CPU and skipped arrival slots.
Add sampled span-end latency cases and regression tests for the ledger.
Consolidate duplicate workloads and document how to interpret the results.

Assisted-by: Codex (GPT-6)
Affirm-Session: 01a2082c-1867-76b2-b0c5-02646130a887
@friscoMad
friscoMad force-pushed the codex/fix-bsp-benchmarks branch from 5141f06 to 5613ac0 Compare November 26, 2026 13:00
@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.59%. Comparing base (a92b644) to head (5613ac0).

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9070      +/-   ##
============================================
+ Coverage     90.56%   90.59%   +0.03%     
- Complexity    11220    11225       +5     
============================================
  Files          1032     1032              
  Lines         30599    30599              
  Branches       4010     4010              
============================================
+ Hits          27711    27722      +11     
+ Misses         1913     1904       -9     
+ Partials        975      973       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
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