Skip to content

fix: bound observation buffering during collection - #2336

Merged
zeitlinger merged 7 commits into
mainfrom
agent/bound-observation-buffer
Sep 14, 2026
Merged

zeitlinger merged 7 commits into
mainfrom
agent/bound-observation-buffer

Conversation

@zeitlinger

@zeitlinger zeitlinger commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

Summary

  • bound the collection spin wait and observation buffer
  • coordinate collection through explicit buffer generations and phase transitions
  • replay buffered observations before surfacing a collection timeout
  • skip timed-out native-histogram maintenance rather than throwing from observe()
  • document the generation handoff and striped-count protocol

This is stacked on the focused #2282 fix so the two Buffer concerns can be reviewed separately. It replaces the #2287 portion of #2297.

Fixes #2287

Ongoing discussion

  • Should the five-second collection deadline remain an internal default, or become publicly configurable? See the earlier discussion.
  • The bounded buffer currently applies backpressure rather than dropping observations. The earlier review suggested drop-on-overflow; this version avoids silent data loss but can block an observer while the generation remains active. See the earlier discussion.
  • The generation/phase handoff is a substantial concurrency change and should be reviewed independently of the simple stripe-index fix.

The earlier concerns about an unbounded second wait and exceptions escaping from native-histogram maintenance are addressed by this implementation.

Validation

  • mise run lint:fix
  • mise run build
  • ./mvnw test -pl prometheus-metrics-core -Dcoverage.skip=true -Dcheckstyle.skip=true
Signed-off-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
Signed-off-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ API changes detected — maintainer review required

This PR modifies the published API diff for the following module(s):

  • prometheus-metrics-core

Please review the changes in docs/apidiffs/current_vs_latest/ carefully before approving.

Signed-off-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
Base automatically changed from agent/fix-buffer-stripe-index to main July 31, 2026 12:47
@zeitlinger
zeitlinger marked this pull request as ready for review August 18, 2026 08:38

@jaydeluca jaydeluca 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.

Two things I think block merge:

  1. The == → >= change is hiding a real accounting bug. The phase
    gate in append() created a class of observation that increments its stripe after the
    collector's getAndAdd — so it is excluded from expectedCount — yet still increments count.
    main could not produce that, which is why == was exact there and hangs here. Normally >=
    absorbs it, but when maybeReset() calls count.reset() the offset absorbs only the snapshot,
    not that observation, so expectedCount stays permanently one too high. I reproduced a
    permanently failing collect() (details inline on Buffer.java).
  2. observeDirect() takes a lock on every observation in steady state. JMH from
    HistogramBenchmark, both trees built from source (-f 1 -wi 3 -i 5 -r 2s -w 2s):
    prometheusClassicSingleThread −38%, prometheusClassicPerThread −44% (uncontended!),
    prometheusClassic −72%, prometheusNative −73%. The exclusion is only needed while a
    collection is in flight.
Signed-off-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
@github-actions

github-actions Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark results

Benchmark run succeeded for a1657911077e0905b4281eec8e6d4c3a466ac779.

Prometheus Java Client Benchmarks

Run Information

  • Date: 2026-08-28T14:05:30Z
  • Commit: a165791
  • JDK: 25.0.3 (OpenJDK 64-Bit Server VM)
  • Benchmark config: 3 fork(s), 3 warmup, 5 measurement, 4 threads
  • Hardware: AMD EPYC 7763 64-Core Processor, 4 cores, 16 GB RAM
  • OS: Linux 6.17.0-1022-azure

Comparison with base

  • Head: a165791
  • Base: 6f88666
  • Metric direction: Throughput scores are higher-is-better; positive Head vs base deltas indicate faster performance.
  • Note: Base and head are compared on the same runner within each topic.
Benchmark PR Base Head vs base Regression verdict
CounterBenchmark.codahaleIncNoLabels 26.19K 25.68K +2.0% within noise
CounterBenchmark.openTelemetryAdd 12.66K 12.84K -1.4% within noise
CounterBenchmark.openTelemetryInc 14.42K 14.85K -2.9% within noise
CounterBenchmark.openTelemetryIncNoLabels 16.06K 16.56K -3.0% within noise
CounterBenchmark.prometheusAdd 24.78K 25.20K -1.7% within noise
CounterBenchmark.prometheusInc 26.08K 25.92K +0.6% within noise
CounterBenchmark.prometheusNoLabelsInc 25.46K 25.46K +0.0% within noise
CounterBenchmark.simpleclientAdd 6.25K 6.20K +0.7% within noise
CounterBenchmark.simpleclientInc 6.34K 6.45K -1.7% within noise
CounterBenchmark.simpleclientNoLabelsInc 6.34K 6.27K +1.1% within noise
HistogramBenchmark.openTelemetryClassic 827.18 802.27 +3.1% within noise
HistogramBenchmark.openTelemetryExponential 745.96 715.89 +4.2% within noise
HistogramBenchmark.prometheusClassic 5.86K 4.57K +28.3% within noise
HistogramBenchmark.prometheusClassicPerThread 12.99K 13.80K -5.9% meaningful regression
HistogramBenchmark.prometheusClassicSingleThread 5.38K 5.29K +1.8% within noise
HistogramBenchmark.prometheusNative 2.87K 3.09K -7.0% within noise
HistogramBenchmark.simpleclient 4.55K 4.49K +1.3% within noise
HistogramTextFormatBenchmark.openMetricsWriteToNull 27.06K 27.07K -0.0% within noise
HistogramTextFormatBenchmark.prometheusWriteToNull 27.58K 27.63K -0.2% within noise
TextFormatUtilBenchmark.openMetricsWriteToByteArray 528.04K 533.07K -0.9% within noise
TextFormatUtilBenchmark.openMetricsWriteToNull 548.86K 547.71K +0.2% within noise
TextFormatUtilBenchmark.prometheusWriteToByteArray 565.81K 570.75K -0.9% within noise
TextFormatUtilBenchmark.prometheusWriteToNull 574.29K 577.72K -0.6% within noise

Results for PR head

CounterBenchmark

Benchmark Score Error Units
codahaleIncNoLabels 26.19K ± 627.28 ops/s
prometheusInc 26.08K ± 961.70 ops/s
prometheusNoLabelsInc 25.46K ± 278.59 ops/s
prometheusAdd 24.78K ± 451.12 ops/s
openTelemetryIncNoLabels 16.06K ± 302.54 ops/s
openTelemetryInc 14.42K ± 243.32 ops/s
openTelemetryAdd 12.66K ± 240.95 ops/s
simpleclientInc 6.34K ± 104.28 ops/s
simpleclientNoLabelsInc 6.34K ± 79.81 ops/s
simpleclientAdd 6.25K ± 65.61 ops/s

HistogramBenchmark

Benchmark Score Error Units
prometheusClassicPerThread 12.99K ± 28.57 ops/s
prometheusClassic 5.86K ± 2.29K ops/s
prometheusClassicSingleThread 5.38K ± 28.15 ops/s
simpleclient 4.55K ± 72.63 ops/s
prometheusNative 2.87K ± 185.56 ops/s
openTelemetryClassic 827.18 ± 11.29 ops/s
openTelemetryExponential 745.96 ± 19.02 ops/s

HistogramTextFormatBenchmark

Benchmark Score Error Units
prometheusWriteToNull 27.58K ± 285.64 ops/s
openMetricsWriteToNull 27.06K ± 292.28 ops/s

TextFormatUtilBenchmark

Benchmark Score Error Units
prometheusWriteToNull 574.29K ± 11.57K ops/s
prometheusWriteToByteArray 565.81K ± 8.33K ops/s
openMetricsWriteToNull 548.86K ± 5.61K ops/s
openMetricsWriteToByteArray 528.04K ± 2.78K ops/s

Raw Results

Benchmark                                            Mode  Cnt          Score        Error  Units
CounterBenchmark.codahaleIncNoLabels                thrpt   15      26187.219    ± 627.282  ops/s
CounterBenchmark.openTelemetryAdd                   thrpt   15      12655.997    ± 240.951  ops/s
CounterBenchmark.openTelemetryInc                   thrpt   15      14421.717    ± 243.318  ops/s
CounterBenchmark.openTelemetryIncNoLabels           thrpt   15      16056.137    ± 302.537  ops/s
CounterBenchmark.prometheusAdd                      thrpt   15      24775.796    ± 451.120  ops/s
CounterBenchmark.prometheusInc                      thrpt   15      26081.724    ± 961.700  ops/s
CounterBenchmark.prometheusNoLabelsInc              thrpt   15      25461.465    ± 278.585  ops/s
CounterBenchmark.simpleclientAdd                    thrpt   15       6246.013     ± 65.613  ops/s
CounterBenchmark.simpleclientInc                    thrpt   15       6342.061    ± 104.278  ops/s
CounterBenchmark.simpleclientNoLabelsInc            thrpt   15       6340.728     ± 79.808  ops/s
HistogramBenchmark.openTelemetryClassic             thrpt   15        827.185     ± 11.292  ops/s
HistogramBenchmark.openTelemetryExponential         thrpt   15        745.963     ± 19.017  ops/s
HistogramBenchmark.prometheusClassic                thrpt   15       5858.828   ± 2292.348  ops/s
HistogramBenchmark.prometheusClassicPerThread       thrpt   15      12985.067     ± 28.568  ops/s
HistogramBenchmark.prometheusClassicSingleThread    thrpt   15       5384.465     ± 28.147  ops/s
HistogramBenchmark.prometheusNative                 thrpt   15       2873.003    ± 185.562  ops/s
HistogramBenchmark.simpleclient                     thrpt   15       4550.964     ± 72.627  ops/s
HistogramTextFormatBenchmark.openMetricsWriteToNull  thrpt   15      27060.099    ± 292.277  ops/s
HistogramTextFormatBenchmark.prometheusWriteToNull  thrpt   15      27577.921    ± 285.638  ops/s
TextFormatUtilBenchmark.openMetricsWriteToByteArray  thrpt   15     528036.007   ± 2778.380  ops/s
TextFormatUtilBenchmark.openMetricsWriteToNull      thrpt   15     548861.655   ± 5612.671  ops/s
TextFormatUtilBenchmark.prometheusWriteToByteArray  thrpt   15     565814.788   ± 8329.161  ops/s
TextFormatUtilBenchmark.prometheusWriteToNull       thrpt   15     574286.644  ± 11570.037  ops/s

Notes

  • Score = the JMH primary metric; throughput is higher-is-better and latency is lower-is-better.
  • Error = 99.9% confidence interval
  • Regression verdict requires comparable benchmark metadata, non-overlapping JMH confidence intervals, and a change of at least 5%; otherwise it is marked "within noise" or "inconclusive".
  • Scores for different benchmark methods are not ranked against one another; they may measure different workloads.

Benchmark Descriptions

Benchmark Description
CounterBenchmark Counter increment performance: Prometheus, OpenTelemetry, simpleclient, Codahale
HistogramBenchmark Histogram observation performance (classic vs native/exponential)
TextFormatUtilBenchmark Metric exposition format writing speed
Signed-off-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
@zeitlinger
zeitlinger merged commit 43788f5 into main Sep 14, 2026
27 checks passed
@zeitlinger
zeitlinger deleted the agent/bound-observation-buffer branch September 14, 2026 11:57
zeitlinger added a commit that referenced this pull request Sep 15, 2026
## Problem

`Buffer.run()` sets the buffer-active bit on every striped observation
counter, waits for
in-flight observations to land, calls `createResult.get()`, and then
clears the bit again.
The surrounding `finally` only releases `runLock` — the bit-clearing
block sits inside the
`try`, so when `createResult.get()` throws, the bit is left set
permanently.


https://github.com/prometheus/client_java/blob/main/prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/Buffer.java#L90-L139

Two things follow from a bit that stays set:

- `append()` keeps returning `true`, so observations go into the buffer
instead of being
  recorded, and are replayed at an arbitrary later point.
- The next `run()` derives `expectedCount` from counters that still
carry the sign bit, so
`complete.apply(expectedCount)` may never be satisfied. The wait loop
then spins on
`Thread.yield()` indefinitely **while holding `runLock`**, which blocks
every subsequent
  scrape of that registry.

Whether the second case spins or instead produces a corrupt snapshot
depends on the number
of stripes, because `2 * Long.MIN_VALUE == 0`: the sign-bit
contributions cancel out for an
even `Runtime.getRuntime().availableProcessors()`. With an even stripe
count you get a run
whose buffer semantics are inverted (observations recorded directly
rather than buffered,
i.e. a torn snapshot) rather than a hang. With an odd count — including
the single
`AtomicLong` this code used before striping — the spin is deterministic.

Nothing clears the bit in-process, so the only recovery is a process
restart.

## Fix

Move the wait-and-create block into its own `try`, with the "signal that
the buffer is
inactive" step and the buffer drain in the matching `finally`.

The drain has to move with it rather than just the bit flip: leaving
`bufferPos` set makes
the next `run()` skip its own wait and replay stale values on top of the
new ones. The
arithmetic is unaffected on the exception path — `expectedCount` is
computed before the
throw, so `expectedBufferSize -= expectedCount` still holds.

## Test

`BufferTest.bufferIsDeactivatedWhenCreateResultThrows` asserts the
invariant rather than the
symptom: after `run()` returns *or* throws, the buffer must be inactive,
probed directly via
`append()`. Using `count -> true` for `complete` keeps the test
independent of the stripe
count, so it fails deterministically on any machine.

Verified both ways:

| | Result |
|---|---|
| With the fix, `BufferTest` | 2/2 pass |
| With the fix reverted | fails — `Expecting value to be false but was
true` |
| With the fix, full `prometheus-metrics-core` suite | 166/166 pass |

## How we hit this

Found in production in Alluxio on `prometheus-metrics-core` 1.0.0. An
`OutOfMemoryError`
raised inside `createResult.get()` — snapshot creation allocates several
arrays per data
point, so it is a likely place for an allocation to fail — left the bit
set and wedged the
`/metrics` endpoint of several workers for 4.5 days, until they were
restarted. Three
separate data points were poisoned within 12 seconds of each other,
consistent with a single
JVM-wide allocation failure rather than a race.

Note that `Buffer.run()` catches nothing, so an `Error` leaks the bit
exactly as an exception
does.

## Relation to #2287

#2287 reports two things about this class: unbounded growth of
`observationBuffer` in
`doAppend()`, and the `Thread.yield()` wait loop having no timeout. This
PR fixes neither of
those directly — it removes the error path that makes the second one
*permanent*. Without a
leaked active bit, the wait loop is a bounded spin over in-flight
observations; with one, it
never terminates. So the two changes are complementary rather than
overlapping, and I have
deliberately left the loop itself alone here to keep this diff
reviewable.

## Notes

- The unbounded `Thread.yield()` wait loop is left as-is; this change
only ensures a thrown
  exception cannot turn it into an infinite spin.
- Built and tested locally with JDK 24 (`-Dtest.java.version=24`), since
`test.java.version`
defaults to 25. Main sources are unaffected (`java.version=8`). I was
not able to run
  `mise run lint` locally, so please let CI arbitrate formatting.


## Update after merging main

The original production change above is now superseded by the
generation-based `Buffer`
implementation merged in #2336. This update merges the original PR with
current `main` and
retains the original production rationale for historical context; no
production code from this
PR remains in the resulting diff.

The retained regression coverage now exercises both
`IllegalStateException` and
`AssertionError` from snapshot creation. Each test appends while the
collection generation is
active, verifies the buffered observation is replayed exactly once,
verifies a later append takes
the direct path, and completes a subsequent collection successfully.
`BufferTest` passes 8/8,
`mise run lint:fix` passes, and `mise run build -- -DskipITs=true`
passes (Docker integration
services are unavailable in this environment).

Signed-off-by: Bin Fan <fanbin103@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
zeitlinger pushed a commit that referenced this pull request Sep 16, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.9.0](v1.8.0...v1.9.0)
(2026-09-16)


### Features

* support metric name filtering in OpenTelemetry exporter
([#2344](#2344))
([9b0ede8](9b0ede8))


### Bug Fixes

* avoid protobuf debug reflection in native images
([#2251](#2251))
([7f899e7](7f899e7))
* bound HTTPServer request resources
([#2333](#2333))
([33ec556](33ec556))
* bound observation buffering during collection
([#2336](#2336))
([43788f5](43788f5))
* bound scrape query parameters
([#2334](#2334))
([27e1912](27e1912))
* **ci:** skip benchmark report for skipped runs
([#2422](#2422))
([40eddb0](40eddb0))
* clarify benchmark regression report verdicts
([#2394](#2394))
([e5fa067](e5fa067))
* **deps:** update dependency com.google.guava:guava to v33.7.0-jre
([#2387](#2387))
([bf0db49](bf0db49))
* **deps:** update dependency io.dropwizard.metrics:metrics-core to
v4.2.40 ([#2432](#2432))
([dd88326](dd88326))
* **deps:** update dependency io.dropwizard.metrics5:metrics-core to
v5.0.8 ([#2433](#2433))
([42f3c8a](42f3c8a))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.29.0-alpha
([#2235](#2235))
([cf9f702](cf9f702))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.30.0-alpha
([#2328](#2328))
([1ca2716](1ca2716))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.30.0-alpha
([#2330](#2330))
([07623c1](07623c1))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.31.0-alpha
([#2401](#2401))
([6c26619](6c26619))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.31.0-alpha
([#2402](#2402))
([ac0d68a](ac0d68a))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.31.1-alpha
([#2409](#2409))
([5eea652](5eea652))
* **deps:** update dependency
io.opentelemetry.instrumentation:opentelemetry-instrumentation-bom-alpha
to v2.31.1-alpha
([#2410](#2410))
([0bcef89](0bcef89))
* **deps:** update dependency org.apache.tomcat.embed:tomcat-embed-core
to v11.0.23
([#2241](#2241))
([a017f80](a017f80))
* **deps:** update dependency org.apache.tomcat.embed:tomcat-embed-core
to v11.0.24
([#2294](#2294))
([63967bd](63967bd))
* **deps:** update dependency org.apache.tomcat.embed:tomcat-embed-core
to v11.0.25
([#2389](#2389))
([92f8344](92f8344))
* **deps:** update dependency org.apache.tomcat.embed:tomcat-embed-core
to v11.0.26
([#2477](#2477))
([05146c0](05146c0))
* **deps:** update dependency
org.springframework.boot:spring-boot-starter-parent to v4.1.1
([#2399](#2399))
([a0b0880](a0b0880))
* **deps:** update jetty monorepo to v12.1.11
([#2279](#2279))
([4dc54da](4dc54da))
* **deps:** update jetty monorepo to v12.1.12
([#2371](#2371))
([08967e0](08967e0))
* **deps:** update jetty monorepo to v12.1.13
([#2459](#2459))
([b217f05](b217f05))
* **deps:** update junit-framework monorepo to v6.1.2
([#2300](#2300))
([5966d1d](5966d1d))
* **deps:** update junit-framework monorepo to v6.1.3
([#2374](#2374))
([d1ade52](d1ade52))
* **deps:** update otel.instrumentation.version
([#2236](#2236))
([158230d](158230d))
* **deps:** update protobuf
([#2400](#2400))
([e2db1ed](e2db1ed))
* **deps:** update protobuf
([#2438](#2438))
([8ad6fa8](8ad6fa8))
* **deps:** update protobuf to v4.35.1
([#2221](#2221))
([cf17073](cf17073))
* disable micrometer compat build cache
([#2457](#2457))
([6a40eda](6a40eda))
* drop +Inf bound from OpenTelemetry classic histogram boundaries
([#2458](#2458))
([a3bce9a](a3bce9a))
* **exposition:** export internal package for OSGi resolution
([#2415](#2415))
([28b503d](28b503d))
* **httpserver:** make scrape error responses secure and configurable
([f6d9df5](f6d9df5))
* include counter names in negative value errors
([#2315](#2315))
([ea8f935](ea8f935))
* include license files in release source jars
([#2250](#2250))
([08cf925](08cf925)),
closes [#2216](#2216)
* keep late observations out of subsequent collection buffers
([#2471](#2471))
([d78b149](d78b149))
* keep PR title check required after rebases
([#2414](#2414))
([e3d4c3b](e3d4c3b))
* prevent buffer stripe index overflow
([#2331](#2331))
([b6cd000](b6cd000))
* redact invalid configuration values
([#2335](#2335))
([7e7e533](7e7e533))
* show uncertainty in benchmark comparisons
([#2476](#2476))
([398d087](398d087))
* stabilize OpenTelemetry exporter builder API
([#2257](#2257))
([09e6e2d](09e6e2d))
* Summary quantiles collapsing for targeted quantiles with 2*epsilon
&gt;= 1-quantile
([#2396](#2396))
([9c7479f](9c7479f))
* update component-prefixed action tags
([#2419](#2419))
([4acf481](4acf481))


### Performance Improvements

* skip snapshot rebuild in mergeDuplicates when names are unique
([#2441](#2441))
([8722230](8722230))


### Documentation

* add API design guideline to contributing docs
([#2350](#2350))
([23ae29a](23ae29a))
* document scrape query limits in request API
([#2391](#2391))
([ba8f5eb](ba8f5eb))
* document semantic PR title guidance
([#2318](#2318))
([5e813a0](5e813a0))

---
> [!IMPORTANT]
> Close and reopen this PR to trigger CI checks.

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

2 participants