Repository navigation
Conversation
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
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.
b064b52 to
3f9bbe2
Compare
|
Good point. Building on that, here's another idea: could we move the arena from |
|
@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 Same harness as above, 40 matched repetitions per shape, baseline is this PR's branch:
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 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 |
@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 This also answers the two concerns you raised: the request not existing yet when the span starts Yes, this changes the behavior of The win over the |
…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.
|
@owent Thanks, done. The exporter now owns the Arena and hands it out in 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 |
|
Have you considered replacing the mutex with a read-write lock? From my understanding of the usage pattern:
What do you think? |
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.
|
@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 |
dbarker
left a comment
There was a problem hiding this comment.
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.
|
@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 Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
|
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. |
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. |
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.
|
@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 |
owent
left a comment
There was a problem hiding this comment.
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.
… the recordable constructors
|
@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. |
|
I performed independent measurements of this PR on the application thread. Builds: My harness is a small app that emits spans in a tight loop on one thread. It uses the OTLP HTTP exporter and a
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
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
left a comment
There was a problem hiding this comment.
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.
|
@chanderraja Thanks for measuring this independently, and for catching the |
|
@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
left a comment
There was a problem hiding this comment.
Thanks for the optimization and updates.
Fixes #4558 (partially, short term step agreed in the issue)
Motivation
Issue #4558 measured that recording into
OtlpRecordablecosts about 5 heap allocations per span attribute on the thread that produces the span, roughly 2.5 times what the genericSpanDatarecordable costs, because the recordable holds itsproto::trace::v1::Spanby value and the message is therefore not Arena allocated. Everyset_key,set_string_value,add_attributesandmutable_valuebecomes 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:
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.hgoogle::protobuf::Arena arena_member, declared before the message pointer so it is constructed first and destroyed last.proto::trace::v1::Span span_withproto::trace::v1::Span *span_, created in the constructor withgoogle::protobuf::Arena::Create<proto::trace::v1::Span>(&arena_). The pointer is owned by the Arena, is never null and is never deleted.char arena_initial_block_[512]member, aligned tostd::max_align_tand declared before the Arena, and hands it to the Arena through theArena(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 onkArenaInitialBlockSize.span()keeps both signatures and now returns*span_.otlp_recordable.cc. Defined in the header,Arena::Createis instantiated in every translation unit that constructs a recordable, and MSVC reports C4702 inside protobuf'sarena.hfor a unit that includes a protobuf header beforeprotobuf_include_prefix.h, asotlp_file_client_test.ccdoes. That failed the MSVC maintainer mode builds of an earlier revision of this pull request.google/protobuf/arena.hinside the existing protobuf include prefix and suffix block.exporters/otlp/include/opentelemetry/exporters/otlp/otlp_log_recordable.hThe same change for
proto::logs::v1::LogRecord. This class had no user declared constructor, so a default constructor was added, defined inotlp_log_recordable.cc, to create the message on the Arena.log_record()keeps both signatures.exporters/otlp/src/otlp_recordable.ccandotlp_log_recordable.ccMechanical, every
span_.becomesspan_->and everyproto_record_.becomesproto_record_->. No logic changes. The two constructors are defined here, with aNOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)because the inline block is left uninitialized on purpose, the Arena hands it out as it fills it.CHANGELOG.mdOne entry under Unreleased.
What did not change
OtlpRecordableUtils::PopulateRequeststill doesscope_spans->add_spans()->CopyFrom(otlp_recordable->span())and the equivalent for log records.span(),log_record()and everyRecordableoverride keep their signatures.span()andlog_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 ofOtlpLogRecordable, 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.mainis the merge base dc0c321, built the same way. Each of 24 rounds runs each benchmark binary once formainand once for this PR with--benchmark_repetitions=5, alternating which side goes first, and the ratio againstmainis 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 forattribute_count:1its interval contains 1.0.otlp_recordable_benchmarkThe
Record*cases start a span through the tracer, record into it and end it, with aBufferingSpanProcessor. The recordables are destroyed inForceFlushoutside the timed region, so these numbers do not include destruction.RecordMinimalSpanRecordNominalSpanRecordSpanWithAttributes/attribute_count:1RecordSpanWithAttributes/attribute_count:10RecordSpanWithAttributes/attribute_count:128RecordSpanWithEvents/event_count:1RecordSpanWithEvents/event_count:10RecordSpanWithEvents/event_count:128RecordSpanWithLinks/link_count:1RecordSpanWithLinks/link_count:10RecordSpanWithLinks/link_count:128BM_OtlpPopulateRequest/span_count:1BM_OtlpPopulateRequest/span_count:512A 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_benchmarkEach pass creates 200 recordables, exports them through
OtlpGrpcExporterwith a fake stub, which copies them into the request withPopulateRequest, 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, andBM_otlp_grpc_with_collector, which needs a running collector, was not run.BM_OtlpExporterEmptySpansBM_OtlpExporterSparseSpansBM_OtlpExporterDenseSpansEmpty 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:
StartSpan9 → 5, one attribute 4.83 → 1.17 for the nominal shape intest_commonand 5.38 → 1.38 for eight 64 character values.Tests
ctestin 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 ofOtlpGrpcExporterTestPeerandOtlpGrpcMetricExporterTestPeer, which crash in gRPC's OpenSSL credential setup on this host, independent of this change.otlp_recordable_test, 45 tests, andotlp_log_recordable_test, 28 tests, pass unchanged.-fno-exceptionsthe 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.main.--track-origins=yes --leak-check=full --errors-for-leak-kinds=definite,indirect, onotlp_recordable_testandotlp_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 onmain.--track-origins=yesis there for the inline Arena block, which is deliberately left uninitialized. No use of an uninitialized value is reported from it.tools/format.shwith clang-format 18 and cmake-format 0.6.13 leaves the tree unchanged.proto_record_.toproto_record_->rewrites inOtlpLogRecordable::SetSeverity, whose cases the existing tests exercise as much as they do onmain.span()andlog_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.