Skip to content

[EXPORTER] Allocate OTLP recordable messages on a per recordable Arena - #4580

Open
ygkat wants to merge 19 commits into
open-telemetry:mainfrom
ygkat:otlp-recordable-arena
Open

ygkat wants to merge 19 commits into
open-telemetry:mainfrom
ygkat:otlp-recordable-arena

Conversation

@ygkat

@ygkat ygkat commented Sep 16, 2026 •

Copy link
Copy Markdown

Fixes #4558 (partially, short term step agreed in the issue)

Motivation

Issue #4558 measured that recording into OtlpRecordable costs about 5 heap allocations per span attribute on the thread that produces the span, roughly 2.5 times what the generic SpanData recordable costs, because the recordable holds its proto::trace::v1::Span by value and the message is therefore not Arena allocated. Every set_key, set_string_value, add_attributes and mutable_value becomes a separate small allocation, and those blocks are freed later on the export thread.

A maintainer scoped the short term fix in the issue discussion:

I think your Option A (but limited to just adding an arena to OtlpRecordable and OtlpLogRecordable) will be a quick performance improvement to the recording path that we can implement now.

This pull request implements exactly that and nothing more. The longer term work discussed in the issue, a common spec compliant recordable shared by all built in exporters that also enforces unique attribute keys and satisfies the readable span interface, is explicitly out of scope here and stays with the maintainers.

The exporter owned Arena shared across recordables that a later revision of this pull request tried is dropped, as the maintainers asked. Arena reuse may come back separately.

Changes

exporters/otlp/include/opentelemetry/exporters/otlp/otlp_recordable.h

  • Adds a google::protobuf::Arena arena_ member, declared before the message pointer so it is constructed first and destroyed last.
  • Replaces proto::trace::v1::Span span_ with proto::trace::v1::Span *span_, created in the constructor with google::protobuf::Arena::Create<proto::trace::v1::Span>(&arena_). The pointer is owned by the Arena, is never null and is never deleted.
  • Adds a char arena_initial_block_[512] member, aligned to std::max_align_t and declared before the Arena, and hands it to the Arena through the Arena(char *, std::size_t) constructor. The Arena therefore starts from a block that lives inside the recordable and goes to the heap only if a span outgrows it. Nothing else about the Arena is configured, since protobuf's own block growth policy is what a span that outgrows the block should follow. How 512 was chosen is explained in the comment on kArenaInitialBlockSize.
  • span() keeps both signatures and now returns *span_.
  • Copy and move are deleted explicitly with a comment, and the destructor is declared as defaulted. An Arena member makes the class non copyable and non movable anyway, the explicit deletion documents it and gives a clearer diagnostic.
  • The constructor is now declared here and defined in otlp_recordable.cc. Defined in the header, Arena::Create is instantiated in every translation unit that constructs a recordable, and MSVC reports C4702 inside protobuf's arena.h for a unit that includes a protobuf header before protobuf_include_prefix.h, as otlp_file_client_test.cc does. That failed the MSVC maintainer mode builds of an earlier revision of this pull request.
  • Includes google/protobuf/arena.h inside the existing protobuf include prefix and suffix block.

exporters/otlp/include/opentelemetry/exporters/otlp/otlp_log_recordable.h

The same change for proto::logs::v1::LogRecord. This class had no user declared constructor, so a default constructor was added, defined in otlp_log_recordable.cc, to create the message on the Arena. log_record() keeps both signatures.

exporters/otlp/src/otlp_recordable.cc and otlp_log_recordable.cc

Mechanical, every span_. becomes span_-> and every proto_record_. becomes proto_record_->. No logic changes. The two constructors are defined here, with a NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) because the inline block is left uninitialized on purpose, the Arena hands it out as it fills it.

CHANGELOG.md

One entry under Unreleased.

What did not change

  • OtlpRecordableUtils::PopulateRequest still does scope_spans->add_spans()->CopyFrom(otlp_recordable->span()) and the equivalent for log records.
  • The per export Arena created in the three exporters stays as it is, and no exporter is changed.
  • No public API is added or removed. span(), log_record() and every Recordable override keep their signatures.
  • No test needed a change. All existing recordable tests read through span() and log_record() and none of them copied or moved a recordable.

Note on layout and on ABI

The Arena member and the inline block change the size and the layout of OtlpRecordable, from 216 to 752 bytes, and of OtlpLogRecordable, from 152 to 736 bytes, and both classes become non copyable and non movable. The inline block is why they grow, and it is paid whether or not a given span uses it. What it replaces is two heap blocks of 256 and 240 bytes that a default configured Arena takes as soon as the message is created, so the byte count is close to a wash and the allocation count is not.

Per docs/abi-policy.md, ABI stability is provided for the API and is not required for SDK provided interfaces such as exporters, so no ABI version guard was added. Applications that link the OTLP exporter need a rebuild, and any code that copied a recordable, which nothing in this repository does, now fails to compile.

The block size is a private constant in the public header, because it sizes a member, so it is baked into user translation units.

Benchmarks

Measured with the existing OTLP benchmarks. Release, GCC 11.5.0, glibc 2.34, protobuf 35.0.0 shared, abseil 20250512, gRPC 1.82.1, C++17, an 8 vCPU VM on a Xeon Gold 5120 at 2.2 GHz that runs other workloads, taskset -c 2-3. main is the merge base dc0c321, built the same way. Each of 24 rounds runs each benchmark binary once for main and once for this PR with --benchmark_repetitions=5, alternating which side goes first, and the ratio against main is formed from the repetition medians inside a round before anything is pooled, so machine drift cancels. The tables show the median over rounds of CPU time and of that ratio, with a bootstrap 95 percent confidence interval over the per round ratios. Where an interval contains 1.0 the difference is within noise. Real time gives ratios within 0.01 of these, and for attribute_count:1 its interval contains 1.0.

otlp_recordable_benchmark

The Record* cases start a span through the tracer, record into it and end it, with a BufferingSpanProcessor. The recordables are destroyed in ForceFlush outside the timed region, so these numbers do not include destruction.

benchmark main this PR ratio 95% CI
RecordMinimalSpan 832 ns 877 ns 1.06 [1.05, 1.08]
RecordNominalSpan 1,642 ns 1,581 ns 0.96 [0.95, 0.97]
RecordSpanWithAttributes/attribute_count:1 979 ns 1,004 ns 1.03 [1.01, 1.04]
RecordSpanWithAttributes/attribute_count:10 2,404 ns 2,362 ns 0.98 [0.97, 0.99]
RecordSpanWithAttributes/attribute_count:128 25,410 ns 20,054 ns 0.79 [0.76, 0.82]
RecordSpanWithEvents/event_count:1 1,252 ns 1,233 ns 0.98 [0.97, 1.01]
RecordSpanWithEvents/event_count:10 4,879 ns 5,147 ns 1.05 [1.04, 1.06]
RecordSpanWithEvents/event_count:128 52,756 ns 50,771 ns 0.96 [0.95, 0.99]
RecordSpanWithLinks/link_count:1 1,281 ns 1,290 ns 0.99 [0.98, 1.01]
RecordSpanWithLinks/link_count:10 5,378 ns 5,301 ns 0.99 [0.98, 0.99]
RecordSpanWithLinks/link_count:128 59,549 ns 53,833 ns 0.90 [0.90, 0.91]
BM_OtlpPopulateRequest/span_count:1 1.3 us 1.3 us 1.00 [1.00, 1.01]
BM_OtlpPopulateRequest/span_count:512 99.2 us 103.3 us 1.04 [1.04, 1.04]

A span with nothing or one attribute recorded is 3 to 6 percent slower to record, since the recordable is now a 752 byte allocation and its Arena is set up whether or not anything is recorded into it. With more content the recording side gets faster, down to 0.79 for 128 attributes, with the exception of 10 events at 1.05. BM_OtlpPopulateRequest, which copies already recorded spans into an Arena allocated request with unchanged code, is 4 percent slower for 512 spans.

otlp_grpc_exporter_benchmark

Each pass creates 200 recordables, exports them through OtlpGrpcExporter with a fake stub, which copies them into the request with PopulateRequest, and destroys them, so unlike the cases above this includes destruction. The benchmark counts a pass as 1000 iterations, the table shows time per span. It is only built by Bazel, so for CMake it was built with a local target that is identical on both sides, and BM_otlp_grpc_with_collector, which needs a running collector, was not run.

benchmark main this PR ratio 95% CI
BM_OtlpExporterEmptySpans 189 ns 215 ns 1.14 [1.13, 1.14]
BM_OtlpExporterSparseSpans 694 ns 612 ns 0.88 [0.87, 0.89]
BM_OtlpExporterDenseSpans 5,424 ns 3,368 ns 0.62 [0.61, 0.63]

Empty spans, with nothing recorded, pay for the larger recordable and the Arena set up as above. Sparse spans with the identity, the name and the timestamps are 0.88 and dense spans with 15 attributes are 0.62 of main.

Heap allocations

Counted out of tree with the allocation counting harness from the first revision: StartSpan 9 → 5, one attribute 4.83 → 1.17 for the nominal shape in test_common and 5.38 → 1.38 for eight 64 character values.

Tests

  • ctest in a Release and in a Debug build with -DOTELCPP_WITH_OTLP_GRPC=ON -DOTELCPP_WITH_OTLP_HTTP=ON -DOTELCPP_WITH_OTLP_FILE=ON -DOTELCPP_WITH_OTLP_GRPC_CREDENTIAL_PREVIEW=ON, run serially in a private network namespace because a local collector holds ports 4317 and 4318: 1431 of 1439 and 1420 of 1428 pass. The 8 failures in each are the SSL credential tests of OtlpGrpcExporterTestPeer and OtlpGrpcMetricExporterTestPeer, which crash in gRPC's OpenSSL credential setup on this host, independent of this change.
  • otlp_recordable_test, 45 tests, and otlp_log_recordable_test, 28 tests, pass unchanged.
  • With -fno-exceptions the OTLP recordables, the OTLP trace and log exporters and their tests build. sdk/src/configuration, which this pull request does not touch, does not build without exceptions, so the full tree was not built.
  • A maintainer mode build with GCC 11 builds the recordables and the OTLP trace and log exporters without warnings. clang-tidy 22 with the repository configuration reports no warning in the recordable sources, or in the tests that construct recordables, that it does not also report on main.
  • Memory checking with valgrind 3.24.0 memcheck, run as --track-origins=yes --leak-check=full --errors-for-leak-kinds=definite,indirect, on otlp_recordable_test and otlp_log_recordable_test: 0 errors from 0 contexts, 0 bytes definitely lost, 0 bytes indirectly lost. Both report 2094 bytes possibly lost in 19 blocks, which is protobuf's static descriptor initialization and is identical on main. --track-origins=yes is there for the inline Arena block, which is deliberately left uninitialized. No use of an uninitialized value is reported from it.
  • tools/format.sh with clang-format 18 and cmake-format 0.6.13 leaves the tree unchanged.
  • Codecov will report low patch coverage. Almost all uncovered changed lines are the proto_record_. to proto_record_-> rewrites in OtlpLogRecordable::SetSeverity, whose cases the existing tests exercise as much as they do on main.
  • No new test was added. The change is a memory placement change with no new behaviour, and the existing recordable tests read the messages through span() and log_record(), including spans whose attributes, events and links overflow the inline block.

Out of scope

The redesign discussed in the issue, one optimized spec compliant recordable type shared by all built in exporters that enforces unique attribute keys, respects the limits while recording and avoids duplicated allocations when several processors are configured, is not addressed here and is left to the maintainers as agreed in the issue.

OtlpRecordable and OtlpLogRecordable held their Span and LogRecord messages
by value, so every set_key, set_string_value and add_attributes call during
recording was a heap allocation on the thread that produced the span or the
log record, about 5 per attribute.

Each recordable now owns a google::protobuf::Arena and creates its message on
that Arena, so recording a field is an Arena bump and the whole message is
released with the Arena. Recording a span with attributes drops from about 5.0
to about 1.0 heap allocations per attribute, the one that remains being the
character buffer of a value longer than the std::string small buffer, which
protobuf allocates outside the Arena.

The Arena starts from a block that lives inside the recordable rather than
from the heap. Each recordable carries an aligned char array and passes it to
the Arena(char *, std::size_t) constructor, which is the constructor protobuf
documents for exactly this. A default configured Arena takes a 256 byte block
from the heap as soon as the message is created and a 240 byte one right after
it, so starting a span cost 7 heap allocations with an Arena and 9 without one.
With the inline block it costs 5, and a span whose recorded content fits in the
block makes no Arena block allocation at all. The block sizes, 512 bytes for a
span and 512 for a log record, were measured: a span with the identity, the
name, the kind and the timestamps recorded uses 288 bytes of Arena space.
Nothing else about the Arena is configured. protobuf's own block growth policy
is what a span that outgrows its inline block should follow, and its defaults,
a 256 byte first heap block growing to at most 32768, are already that.

The inline block is paid by every recordable whether or not a span uses it, so
sizeof(OtlpRecordable) goes from 216 to 752 bytes and sizeof(OtlpLogRecordable)
from 152 to 736. That replaces the two heap blocks a default configured Arena
would have taken, so the byte count is close to unchanged and the allocation
count is not.

span() and log_record() keep their signatures and
OtlpRecordableUtils::PopulateRequest still copies each recordable message into
the Arena allocated request, so the export path is unchanged. The Arena member
changes the memory layout of both recordables and makes them neither copyable
nor movable, which also has to hold, since the Arena points into the object.

open-telemetry#4558
otlp_recordable_benchmark.cc times a whole span in one region, so it cannot
say which part of the application thread path a change to OtlpRecordable
moves. The new otlp_recordable_phase_benchmark.cc times one phase at a time,
StartSpan, SetAttribute and End, plus the destruction of the recordable, which
with a BatchSpanProcessor is paid by the exporter thread and not by the
application thread. OtlpRecordable has no End method, so the destruction case
is named DestroyRecordable rather than folded into End.

Every case is measured over three span shapes, minimal with no attributes, the
nominal mix already shared through test_common, and a long string shape whose
values are past the std::string small buffer, which isolates the character
buffer allocation that an Arena backed string field still makes on the heap.

Every case is also measured with one span alive at a time and with 128 spans
alive at a time, because a recordable that owns an Arena holds a block of it
for the whole life of the span, so the two cases land in different parts of
the allocator. One live span is what a simple processor gives, many live spans
is what a batch processor queue gives.

Only the phase under test is timed, through UseManualTime, and the cost of the
two bracketing clock reads is measured once and taken off, so the reported
ns/span counter is comparable across live span counts.

A second target, otlp_recordable_phase_alloc_benchmark, builds the same source
with OTELCPP_BENCHMARK_COUNT_ALLOCATIONS, which replaces the global operator
new with a per thread counter and reports allocs/span and allocs/attr. It is a
separate binary because the counter perturbs the very allocations it measures,
so the timing binary stays uninstrumented.

Building the same source twice under different defines needs the benchmark
macro to accept them, and otel_cc_benchmark took only name, srcs, deps and
tags, so passing local_defines to it made the whole //exporters/otlp package
fail to load. The macro now takes local_defines and threads it through to both
the cc_binary and the _smoketest cc_test it generates. local_defines rather
than defines, because these belong to the benchmark sources and not to
anything that depends on the targets, and it is the spelling already used
elsewhere in the tree.

open-telemetry#4558
@ygkat
ygkat requested a review from a team as a code owner September 16, 2026 04:01
@linux-foundation-easycla

linux-foundation-easycla Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

The comments claimed 512 was simply the best of the sizes measured. It is
not ahead on every shape: for spans with many long attributes a 768 byte
block wins on allocation count, on record time and on peak memory, because
which size wins on memory depends on where a span's overflow lands in
protobuf's block doubling.

Also attribute the regression at 768 and 1024 to glibc malloc's smallbin
and largebin boundary at a 1008 byte chunk rather than to a general rule
about 1 kB objects, so the size is re-measured rather than assumed on a
different allocator.

Comments only, no behavior change.
@ygkat
ygkat force-pushed the otlp-recordable-arena branch from b064b52 to 3f9bbe2 Compare September 16, 2026 04:01
@owent

owent commented Sep 17, 2026

Copy link
Copy Markdown
Member

Good point. Building on that, here's another idea: could we move the arena from Recordable into the request when Export is called? That way, we could avoid at least one more copy.

@ygkat

ygkat commented Sep 17, 2026

Copy link
Copy Markdown
Author

@owent Thanks. I tried it the way I understood it, so please correct me if this is not what you meant. The per-recordable Arena from this PR stays, and PopulateRequest hands the message to the request with UnsafeArenaAddAllocated instead of CopyFrom, guarded on request->GetArena() != nullptr because a non-Arena request would delete the borrowed messages in its destructor. About 20 lines, accessors unchanged.

Same harness as above, 40 matched repetitions per shape, baseline is this PR's branch:

shape total CPU per span export side CPU per span peak RSS
minimal 0.88 [0.84, 0.97] 0.78 [0.74, 0.82] 0.96
nominal 0.82 [0.79, 0.85] 0.71 [0.68, 0.72] 0.88
long strings 0.83 [0.82, 0.87] 0.75 [0.71, 0.76] 0.87

The recording thread is unchanged (ratio 0.94 to 1.0), the exported bytes are identical except for ids and timestamps, valgrind is clean on the unit tests and on the end to end path, and existing tests pass unchanged.

The cost is a lifetime contract that does not exist today. The recordables must outlive every read of the request, and BatchSpanProcessor destroys them right after Export() returns. Every in tree exporter serializes before returning (HTTP sync and async, gRPC sync, file), so it holds. The one caveat is the gRPC async preview path, where a client interceptor can defer serialization past Export() and the completion callback receives *request after return (today it only reads a size). Since PopulateRequest is public, I would make the handover explicit rather than keyed on GetArena().

Is this what you meant, or the other direction where the recordable allocates its message on an Arena owned by the exporter or the request? I did not build that one, because with BatchSpanProcessor the request does not exist yet when the span starts and one recordable can be exported by several processors. If the pointer handover is what you have in mind, I will fold it into this PR.

@owent

owent commented Sep 24, 2026

Copy link
Copy Markdown
Member

@owent Thanks. I tried it the way I understood it, so please correct me if this is not what you meant. The per-recordable Arena from this PR stays, and PopulateRequest hands the message to the request with UnsafeArenaAddAllocated instead of CopyFrom, guarded on request->GetArena() != nullptr because a non-Arena request would delete the borrowed messages in its destructor. About 20 lines, accessors unchanged.

Same harness as above, 40 matched repetitions per shape, baseline is this PR's branch:

shape total CPU per span export side CPU per span peak RSS
minimal 0.88 [0.84, 0.97] 0.78 [0.74, 0.82] 0.96
nominal 0.82 [0.79, 0.85] 0.71 [0.68, 0.72] 0.88
long strings 0.83 [0.82, 0.87] 0.75 [0.71, 0.76] 0.87
The recording thread is unchanged (ratio 0.94 to 1.0), the exported bytes are identical except for ids and timestamps, valgrind is clean on the unit tests and on the end to end path, and existing tests pass unchanged.

The cost is a lifetime contract that does not exist today. The recordables must outlive every read of the request, and BatchSpanProcessor destroys them right after Export() returns. Every in tree exporter serializes before returning (HTTP sync and async, gRPC sync, file), so it holds. The one caveat is the gRPC async preview path, where a client interceptor can defer serialization past Export() and the completion callback receives *request after return (today it only reads a size). Since PopulateRequest is public, I would make the handover explicit rather than keyed on GetArena().

Is this what you meant, or the other direction where the recordable allocates its message on an Arena owned by the exporter or the request? I did not build that one, because with BatchSpanProcessor the request does not exist yet when the span starts and one recordable can be exported by several processors. If the pointer handover is what you have in mind, I will fold it into this PR.

@ygkat The other direction — the recordable allocates its message on an Arena owned by the exporter.

Concretely: the exporter keeps one Arena and uses it for all recordable objects between two
Otlp*Exporter::Export calls. Since MakeRecordable already funnels through the exporter, it can
hand its current Arena to every recordable it creates. At Export time we move this shared Arena
into the request, and let PopulateRequest move data instead of copying it when the Arena of the
input spans/logs is the same as the request's — falling back to copying otherwise.

This also answers the two concerns you raised: the request not existing yet when the span starts
is fine, because the Arena lives in the exporter between calls, not in the request; and fan-out is
fine, because MultiRecordable gives each processor its own recordable, so a message allocated on
an exporter's Arena is only ever read by that exporter.

Yes, this changes the behavior of PopulateRequest — the input spans/logs on the matching Arena
are moved-from after the call. That should be documented, and since PopulateRequest is public
but not exported, I think it's OK to change the ABI here.

The win over the UnsafeArenaAddAllocated variant is one Arena per batch instead of N, and no
borrowed lifetime at all.

…ove messages into the request

Each OTLP trace and log exporter owns one Arena that MakeRecordable hands to
every recordable it creates until the next export. Export swaps in a fresh
Arena and builds the request on the old one, and PopulateRequest adds the
messages that are already on the request's Arena with AddAllocated instead of
copying them. Messages on any other Arena are still copied.

The Arena is shared through a std::shared_ptr by the exporter, the recordables
and the request, because MakeRecordable runs on application threads without a
lock, a batch can hold recordables from older Arenas and a log recordable can
outlive its exporter. Shutdown drops the exporter's reference so that
recordables created afterwards do not keep growing the Arena.

open-telemetry#4558
…benchmark

The OTLP exporters now create their recordables on an Arena they share until
the next export, but the no-op exporter of the phase benchmark still created
each recordable with an Arena of its own, so StartSpan, SetAttribute and
DestroyRecordable measured a layout that no exporter uses any more.

NullSpanExporter now holds an OtlpRecordableArena, creates every recordable on
it and replaces it on Export, like the real exporters. BufferingSpanProcessor
never calls Export, so the fixture replaces the Arena itself once a group of
spans has ended, outside the timed region. That leaves the recordables holding
the only references, as after a real export, so the last recordable destroyed
also frees the Arena and DestroyRecordable includes that cost.
@ygkat ygkat changed the title [EXPORTER] Allocate OTLP recordable messages on a per recordable Arena [EXPORTER] Share one Arena per exporter across OTLP recordables and move messages into the request Sep 27, 2026
@ygkat

ygkat commented Sep 27, 2026

Copy link
Copy Markdown
Author

@owent Thanks, done. The exporter now owns the Arena and hands it out in MakeRecordable, Export swaps in a fresh one and builds the request on the old one, and PopulateRequest moves the messages on the request's Arena and copies the rest. The Arena is a std::shared_ptr shared by the exporter, the recordables and the request, since a span started before an export can end after it and a log record can outlive the exporter.

I rewrote the PR description for the new design, with updated benchmarks. CPU per span is 0.33 to 0.64 of main. There are two regressions, described there: minimal spans created from 8 threads are slower than main because of the mutex in MakeRecordable, and a span left open across exports keeps its whole Arena alive.

@owent

owent commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Have you considered replacing the mutex with a read-write lock? From my understanding of the usage pattern:

  • Export is only invoked by a single processor thread, so it could safely hold the write lock.
  • MakeRecordable can be called from user threads, and since it's expected to be called very frequently, a mutex would likely become a contention bottleneck. With a read-write lock, multiple user threads could hold the read lock simultaneously, allowing MakeRecordable to run concurrently and significantly reducing lock conflicts.

What do you think?

ygkat added 3 commits October 1, 2026 10:45
The SetStatus change from main dereferences span_ as a message, but span_ is a
pointer on this branch. Also wrap the benchmark CMake comment for cmake-format
and guard the counting allocator's throw for builds without exceptions.
MakeRecordable runs on every span start from application threads, while only
the processor thread rotates the Arena. A shared lock lets those threads take
the current Arena concurrently, which removes the slowdown the plain mutex
caused when many threads start spans at once.
@ygkat

ygkat commented Oct 1, 2026

Copy link
Copy Markdown
Author

@owent Thanks. I had considered a read-write lock, but expected the shared reader count to bounce between cores the same way the mutex does, so I only tried a spinlock, which did not help, and a thread local cache of the Arena, which removed the contention but let idle threads keep old Arenas alive. Your point made me measure it after all, and that expectation was wrong.

With std::shared_timed_mutex (C++14), Get() under a shared lock and Rotate()/Release() under an exclusive lock, creating minimal spans from 8 threads goes from 0.67x of main with the mutex to 1.0x, and nominal spans from 0.93x to 1.25x. Single thread is unchanged within noise. Profiling also showed that with the mutex most of the time went into threads colliding on the batch processor's queue, not into the lock itself. I pushed the change and updated the description.

@dbarker dbarker left a comment

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.

Thanks for working on this PR. Reducing dynamic allocations is important.

However, this change adds substantial complexity to the OTLP exporters, degrades multi-threaded performance, and introduces a memory-retention behavior that prevents accepting it as-is.

Span lifetimes are application-defined. Applications may create spans that last microseconds alongside spans that remain active for minutes or hours. With the shared-arena design, an arena is released only after the last recordable that references it is destroyed. A long-lived span can therefore retain the arena generation it started on across many export cycles.

That retained arena also contains the protobuf allocations for every span created in the same generation, including short-lived spans that have already been exported successfully. Their memory cannot be reclaimed when the request completes. It remains allocated until the long-lived span ends. Multiple long-lived spans created in different generations can retain multiple such arenas concurrently.

This changes memory retention from being tied to an individual recordable and request to being tied to the longest-lived span in an arena generation. The resulting memory usage is workload-dependent and can become significant for applications with high span volume and long-lived spans.

@ygkat

ygkat commented Oct 2, 2026

Copy link
Copy Markdown
Author

@dbarker @owent Thanks for the review. The shared Arena came from owent's suggestion earlier in this PR, and that is the design dbarker's concerns are about. The memory retention is real, it is the regression listed in the description. On multi-threaded performance, with the read-write lock, creating minimal spans from 8 threads is on par with main (1207k vs 1174k spans/s) and nominal spans are 1.25x main.

Since the two of you point in different directions, could you agree on one before I change the design again? I will follow whichever you choose. In case it helps, I measured both designs on our production HAProxy with the OTel filter, and the per-recordable Arena from the first revision and the current shared Arena came out the same in CPU per request, export thread cost per span and memory, so for our use the first revision would be enough.

@codecov

codecov Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 53.39806% with 48 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.70%. Comparing base (e06cf6b) to head (66089e2).

Files with missing lines Patch % Lines
exporters/otlp/src/otlp_log_recordable.cc 29.42% 48 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #4580      +/-   ##
==========================================
+ Coverage   86.70%   86.70%   +0.01%     
==========================================
  Files         530      530              
  Lines       21206    21215       +9     
==========================================
+ Hits        18384    18393       +9     
  Misses       2822     2822              
Files with missing lines Coverage Δ
...opentelemetry/exporters/otlp/otlp_log_recordable.h 100.00% <100.00%> (ø)
...ude/opentelemetry/exporters/otlp/otlp_recordable.h 100.00% <100.00%> (ø)
exporters/otlp/src/otlp_recordable.cc 91.86% <100.00%> (+0.45%) ⬆️
exporters/otlp/src/otlp_log_recordable.cc 41.25% <29.42%> (+1.51%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@owent

owent commented Oct 5, 2026

Copy link
Copy Markdown
Member

In my opinion, we can complete arena allocation for recordable in this PR. Arena reuse can be done in a follow-up PR as a separate optimization, since the reuse logic is a bit more complex.

@dbarker

dbarker commented Oct 8, 2026

Copy link
Copy Markdown
Member

@dbarker @owent Thanks for the review. The shared Arena came from owent's suggestion earlier in this PR, and that is the design dbarker's concerns are about. The memory retention is real, it is the regression listed in the description. On multi-threaded performance, with the read-write lock, creating minimal spans from 8 threads is on par with main (1207k vs 1174k spans/s) and nominal spans are 1.25x main.

Since the two of you point in different directions, could you agree on one before I change the design again? I will follow whichever you choose. In case it helps, I measured both designs on our production HAProxy with the OTel filter, and the per-recordable Arena from the first revision and the current shared Arena came out the same in CPU per request, export thread cost per span and memory, so for our use the first revision would be enough.

Thanks. For this PR please limit the scope to adding an arena per recordable and reporting its performance using the existing otlp benchmarks. Let's pause a shared arena approach for now.

ygkat added 6 commits October 12, 2026 21:35
The performance of this change is reported with the existing OTLP
benchmarks, so the phase isolated benchmark and its CMake and Bazel
targets are no longer needed. The local_defines parameter of
otel_cc_benchmark was only used by its allocation counting variant and is
removed with it.
Limit this change to an Arena per recordable, as agreed in the review, and
leave sharing an Arena across recordables for later. Each OtlpRecordable
and OtlpLogRecordable again owns its Arena, which starts from a 512 byte
block inside the recordable, and PopulateRequest copies each message into
the request as before.

This removes OtlpRecordableArena, the Arena constructors of the
recordables, the shared Arena and its lock in the OTLP trace and log
exporters, the move into the request in PopulateRequest, and the tests for
them. The exporters and OtlpRecordableUtils are back to main.

open-telemetry#4558
Replace the entry for the shared Arena with the one for an Arena per
recordable, and move it back to the Unreleased section, where the merge of
main had left it under 1.29.0.
The constructors create the message with Arena::Create. Defined in the
header, that template is instantiated in every translation unit that
constructs a recordable, and MSVC reports C4702, unreachable code, inside
protobuf's arena.h when such a unit includes a protobuf header before
protobuf_include_prefix.h, as otlp_file_client_test.cc does. With warnings
as errors that fails the MSVC maintainer mode builds. Defined in
otlp_recordable.cc and otlp_log_recordable.cc, the template is only
instantiated where the protobuf headers come in through the prefix.

Also declare the destructors and mark the inline block, which is left
uninitialized on purpose, so that clang-tidy does not report
cppcoreguidelines-special-member-functions and
cppcoreguidelines-pro-type-member-init for both classes.
@ygkat ygkat changed the title [EXPORTER] Share one Arena per exporter across OTLP recordables and move messages into the request [EXPORTER] Allocate OTLP recordable messages on a per recordable Arena Oct 12, 2026
@ygkat

ygkat commented Oct 12, 2026

Copy link
Copy Markdown
Author

@dbarker @owent Thank you both for agreeing on the scope. I limited the PR to the per recordable Arena from the first revision, updated to current main, and removed the shared Arena, the exporter changes and the phase benchmark. The description now reports the existing otlp_recordable_benchmark and otlp_grpc_exporter_benchmark. Spans with content get faster, down to 0.62 of main for dense spans, and spans with nothing recorded pay 6 to 14 percent for the larger recordable.

@dbarker dbarker added the discuss To discuss in SIG meeting label Oct 12, 2026

@owent owent left a comment

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.

LGTM after cppcheck warnings are fixed.

BTW: Would it make sense to increase arena_initial_block_, at least for the OTLP file exporter and the OTLP HTTP exporter with JSON format? My measurements show the auto-generated attributes of the OTLP file exporter take about 2 KB, which means the current 512-byte initial block always requires two additional dynamically allocated blocks. If raising the global default feels too aggressive, another option would be making the initial block size configurable per exporter.

@ygkat

ygkat commented Oct 13, 2026

Copy link
Copy Markdown
Author

@owent Thanks. I pushed 5aa9922 for the cppcheck and include-what-you-use warnings, it needs a workflow approval to run CI.

On the block size, I measured 512, 768 and 1024 bytes for the first revision. The larger blocks cut allocations for spans with many long attributes, but with many spans alive at once they made starting a span slower on glibc malloc, because the larger recordable falls into a slower size range of the allocator. So a larger global default is not free for spans that stay small, and a per exporter setting would avoid that trade-off. Since dbarker asked to keep this PR to the per recordable Arena, I would leave the size at 512 here, but I can add the option to this PR if you both prefer.

@chanderraja

Copy link
Copy Markdown

I performed independent measurements of this PR on the application thread.

Builds: main at 0a5bb0b, and the same commit with this PR's head (5aa9922) merged in. I built both in the repo's dev container (.devcontainer/Dockerfile.dev: clang 22.1.8; protobuf 35.1.0 and abseil 20250512.1 from third_party_release), Release with -O2 -g -fno-omit-frame-pointer.

My harness is a small app that emits spans in a tight loop on one thread. It uses the OTLP HTTP exporter and a BatchSpanProcessor with max_queue_size 16384 (no drops), exporting to a local sink that discards everything. I counted allocations per thread with an LD_PRELOAD malloc counter and took them from the emitting thread only: 10,000 spans after a 1,000-span warmup. Latency is the time per span in the loop, 10 interleaved rounds of 10 samples each.

main main + #4580
Allocations per span, no attributes 9 5
Allocations per span, 5 string attributes (12-byte keys, 24-byte values) 36 11
SetIdentity allocations, root / child span 4 / 5 1 / 1
Span emit p50, ratio to main (median of per-round ratios, range) 1 0.74 (0.68–0.88)
Span emit p95, ratio to main 1 0.66 (0.64–0.80)

This reproduces the 9 allocations down to 5 for a minimal span. The allocation counts were identical across runs. The PR was faster in every one of the 10 rounds, though main's per-sample p50s were much more spread out than the PR's. Nothing that I measured on the emitting thread got worse, including p95. This harness keeps up to 16,384 recordables alive in the queue at once (glibc malloc), which is the case the PR's block-size comment is concerned about, and the 512-byte block held up there.

Measured on one desktop machine (Ryzen 5 5600G, single-channel DDR4, boost off). The latency ratios may differ on other hardware; the allocation counts shouldn’t.

I also tried two changes to SetIdentity on top of the PR:

  • skip set_trace_state when trace_state()->Empty();
  • fill trace_id with mutable_trace_id()->assign(...).

One practical note: the PR currently conflicts with main in CHANGELOG.md and otlp_recordable.h. #4734 added attribute_value_depth_limit to SpanLimits, and main’s constructor now passes it as the third value. The constructor this PR moves into otlp_recordable.cc still lists six values. Since span_limits_ is filled by position, it would likely still compile after a rebase but shift max_events and the later limits into the wrong fields, so it needs the extra (std::numeric_limitsstd::size_t::max)() added there too.

Harness, method and data: section 4 of a parity study in the microtel repo.

I'm happy to rerun these on later revisions of the PR.

@owent owent left a comment

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.

LGTM after conflicts are resolved.

Pass attribute_value_depth_limit in the OtlpRecordable constructor, which
SpanLimits gained in open-telemetry#4734, so the later limits keep their fields, and move
the CHANGELOG entry to Unreleased after the 1.30.0 release.
@ygkat

ygkat commented Nov 17, 2026

Copy link
Copy Markdown
Author

@chanderraja Thanks for measuring this independently, and for catching the SpanLimits order. I merged main and added attribute_value_depth_limit to the constructor in otlp_recordable.cc. Without it, the existing SpanLimitsNoLimitDefault, SpanLimitsFieldsMerged and TestLinkLimits tests fail. The CHANGELOG entry moved to Unreleased, since 1.30.0 is out.

@ygkat

ygkat commented Nov 17, 2026

Copy link
Copy Markdown
Author

@dbarker When you have time, could you take another look? As you asked, the PR is now limited to the per recordable Arena, the shared Arena and the exporter changes are gone, and the description reports the existing otlp benchmarks. owent has approved, and it is up to date with main.

@dbarker dbarker removed the discuss To discuss in SIG meeting label Nov 23, 2026

@dbarker dbarker left a comment

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.

Thanks for the optimization and updates.

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.

OtlpRecordable: about 5 heap allocations per attribute, then a deep copy at export. Arena backed recordable or adopt into the request?

4 participants