Skip to content

Metric optimizations for stellar-core apply path - #38

Merged
graydon merged 6 commits into
stellar:masterfrom
dmkozh:apply_opt
Jun 30, 2026
Merged

graydon merged 6 commits into
stellar:masterfrom
dmkozh:apply_opt

Conversation

@dmkozh

@dmkozh dmkozh commented Jun 24, 2026

Copy link
Copy Markdown

This includes all the changes that were necessary to reduce the negative impact of metrics in Core apply path from over +~100% to +~2-8%. Likely this could be pushed further, but for now the improvement seems good enough to just merge it and start benefitting from the improvements. I also expect this to have some positive impact on Core overall, though it might be too small to be visible.

The gist of the changes:

  • A bunch of build & test fixes, mostly reducing flakiness to make sure that the tests are green both before and after the changes
  • Make Meter lock-free, use atomics instead
  • Improve CKMS implementation by using linear algorithms instead of quadratic ones
  • Expose methods for flushing batches of metrics (very useful for the apply stage which really needs just a single update per ledger)

Copilot AI review requested due to automatic review settings June 24, 2026 01:09

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR reduces metrics overhead in the “core apply” hot path by introducing batch update APIs, removing contention from Meter/EWMA, and rewriting CKMS batch/compaction to avoid quadratic behavior. It also includes build/test adjustments aimed at improving portability (notably Windows) and reducing test flakiness.

Changes:

  • Add bulk update APIs (UpdateMany) to Sample, Histogram, Timer, and CKMSSample to amortize locking/window-advance overhead.
  • Make Meter/EWMA lock-free via atomics and adjust tests to exercise concurrent access patterns.
  • Optimize CKMS batch insertion and compression to linear-style passes; add a lightweight Tracy integration wrapper; refine CMake options for collectd and Windows.

Reviewed changes

Copilot reviewed 23 out of 23 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
test/test_timer.cc Reworks snapshot timing to reduce flakiness by waiting for a non-empty CKMS window.
test/test_meter.cc Updates expectations/types and adds concurrency-focused meter tests.
test/test_histogram.cc Makes CKMS window test less timing-sensitive; adds concurrent reader/writer test for UpdateMany.
test/stats/test_exp_decay_sample.cc Relaxes assertions to account for sampling randomness.
test/stats/test_ewma.cc Adds a concurrency test to ensure rates stay finite under concurrent operations.
test/stats/test_ckms_sample.cc Switches tests to use SystemClock for CKMS windowing consistency.
test/CMakeLists.txt Improves Windows/gtest configuration and gates collectd reporter tests behind an option.
src/medida/tracy.h Adds an optional Tracy wrapper header to avoid hard dependency on Tracy headers/macros.
src/medida/timer.h Introduces Timer::UpdateMany API for batch duration recording.
src/medida/timer.cc Implements Timer::UpdateMany and uses Tracy wrapper include.
src/medida/timer_context.cc Uses Tracy wrapper include instead of directly including Tracy.
src/medida/stats/sample.h Adds default virtual UpdateMany to the Sample interface.
src/medida/stats/ewma.cc Replaces volatile state with atomics; updates operations to use relaxed atomics.
src/medida/stats/ckms.h Adds size-aware allowableError overload used by optimized algorithms.
src/medida/stats/ckms.cc Rewrites insertBatch/compress to avoid quadratic vector insert/erase costs.
src/medida/stats/ckms_sample.h Adds UpdateMany overloads to CKMS sample.
src/medida/stats/ckms_sample.cc Implements UpdateMany with single lock/window advance for a whole batch.
src/medida/meter.cc Makes meter ticking/counting lock-free; uses atomics and a ticking gate instead of a mutex.
src/medida/histogram.h Adds Histogram::UpdateMany API.
src/medida/histogram.cc Implements UpdateMany; replaces recursive mutex with non-recursive mutex and unlocked helpers.
src/medida/counter.cc Uses Tracy wrapper include instead of directly including Tracy.
src/medida/buckets.cc Uses Tracy wrapper include instead of directly including Tracy.
CMakeLists.txt Adds collectd build option, adjusts MSVC handling, sets C++ standard, gates collectd reporter source, and changes Windows library type/linking/install behavior.
Comments suppressed due to low confidence (2)

test/test_timer.cc:113

  • This assertion can become flaky if takeSnapshot retries and calls updateValues() again (the snapshot may legitimately contain >50 samples). Consider only asserting a lower bound on the snapshot size.
  auto snapshot = takeSnapshot(timer, updateValues);
  ASSERT_NE(0u, snapshot.size());
  EXPECT_NEAR(20.0, snapshot.getMedian(), 0.001);
  EXPECT_NEAR(30.0, snapshot.get75thPercentile(), 0.001);
  EXPECT_NEAR(40, snapshot.get99thPercentile(), 0.001);
  EXPECT_EQ(50, snapshot.size());
}

test/test_timer.cc:138

  • Similarly, if takeSnapshot retries and repopulates, the snapshot can contain more than 10 samples. Asserting an exact size makes this test unnecessarily brittle.
  auto snapshot = takeSnapshot(timer, updateValues);
  EXPECT_NEAR(1e-6, snapshot.getMedian(), 1e-9);
  EXPECT_NEAR(1e-6, snapshot.get75thPercentile(), 1e-9);
  EXPECT_NEAR(1e-6, snapshot.get99thPercentile(), 1e-9);
  EXPECT_EQ(10, snapshot.size());
}

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

Comment thread test/test_meter.cc Resolved
Comment thread CMakeLists.txt Resolved
Comment thread CMakeLists.txt Resolved
dmkozh added 5 commits June 24, 2026 12:08
- Make tracy optional
- Fix test that used incorrect API
- Some Windows-specific fixes for cmake files
Common reasons for flakiness were incorrect expectations about metric windows (test assumed 1s is enough, however window is based on the wall time), and insufficient tolerance for tests that use real clocks sleeps, that in practice may be pretty noisy.
Every Mark used to acquire the mutex, which is unnecessary and can be worked around with atomics in EWMS and a simple atomic-based guard for the Tick processing.

Removing the mutex dramatically reduces contention for the cases where the same meter is used by multiple threads.
The buffered-batch merge inserted each value mid-vector with vector::emplace and compress() removed items with vector::erase, which resulted in N^2 complexity. Instead we do a linear-time merge of sorted vectors, and a linear-time compaction pass.

Both follow the exact semantics that the original code had; I'm sure this can be improved, but I don't see a good reason to spend more time on that, given that the current rewrite is sufficient fast.
- Replace the histogram's recursive_mutex with a plain mutex (the recursion was only public methods calling each other; use unlocked private helpers instead).

- Add UpdateMany to Sample (default loop), CKMSSample, Histogram and Timer: recording N values with a single lock acquisition and a single sample-window timestamp, otherwise equivalent to N Update calls. This lets callers that batch samples to avoid per-sample locking.
Comment thread src/medida/stats/ckms.cc Outdated
// computed from next's position in (and size of) the evolving vector.
std::size_t const n = sample_.size();
std::vector<Item> out;
out.reserve(n);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Instead of creating a new vector, can't we do the folding in-place in the same vector (and still not do the extra work for erasing)?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done, I doubt it would make a measurable difference, but OTOH it doesn't really make the code any more complex.

@graydon graydon left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nice work!

@graydon
graydon merged commit 2bf1afa into stellar:master Jun 30, 2026
2 checks passed
pull Bot pushed a commit to DIGIIX-Ltd/stellar-core that referenced this pull request Jul 16, 2026
Bump medida to take stellar/medida#38 (speeding
up metrics and adding batch interfaces) and then cherry-picking in a
couple commits @dmkozh did to further optimize metrics usage on top.
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.

4 participants