From 207e1ca5346e7401496c8223e4909c374ff4c7bb Mon Sep 17 00:00:00 2001 From: DOKL57 Date: Sun, 22 Nov 2026 09:18:41 +0300 Subject: [PATCH 1/5] Reuse drained delta metric handles across collections --- .../state/DeltaSynchronousMetricStorage.java | 154 ++++++---- .../state/SynchronousMetricStorageTest.java | 273 ++++++++++-------- 2 files changed, 241 insertions(+), 186 deletions(-) diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java index 13abd386b3a..2e83d7d3c51 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java @@ -41,9 +41,13 @@ class DeltaSynchronousMetricStorage private final MemoryMode memoryMode; private volatile AggregatorHolder aggregatorHolder = new AggregatorHolder<>(); - // Only populated if memoryMode == REUSABLE_DATA + + // Reset unbound handles from the preceding collection, published after it drains. + // Only populated in REUSABLE_DATA mode. + @Nullable private volatile ConcurrentHashMap> - previousCollectionAggregatorHandles = new ConcurrentHashMap<>(); + previousCollectionAggregatorHandles; + // Only populated if memoryMode == REUSABLE_DATA private final ArrayList reusableResultList = new ArrayList<>(); private final ConcurrentLinkedQueue> aggregatorHandlePool = @@ -148,19 +152,7 @@ private DeltaAggregatorHandle tryAcquireHandleForRecord( return null; } try { - // Get handle from pool if available, else create a new one. - // Note: pooled handles retain their original creationEpochNanos, but delta storage does not - // use the handle's creation time for the start epoch — it uses the reader's last collect time - // directly in collect(). So the stale creation time on a recycled handle does not affect - // correctness. - DeltaAggregatorHandle newDeltaHandle = aggregatorHandlePool.poll(); - if (newDeltaHandle == null) { - newDeltaHandle = new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); - } - handle = aggregatorHandles.putIfAbsent(attributes, newDeltaHandle); - if (handle == null) { - handle = newDeltaHandle; - } + handle = insertHandleForNewSeries(aggregatorHandles, attributes); // Pre-increment per-handle state while the holder gate is still held. The collect // thread's lock pass cannot start until all threads release the holder gate, so this // increment is guaranteed to be observed by the lock pass before it runs. @@ -171,6 +163,33 @@ private DeltaAggregatorHandle tryAcquireHandleForRecord( } } + // Called with the holder gate acquired, so the collector cannot recycle the map while in use. + private DeltaAggregatorHandle insertHandleForNewSeries( + ConcurrentHashMap> aggregatorHandles, + Attributes attributes) { + ConcurrentHashMap> previous = + previousCollectionAggregatorHandles; + // Delta timestamps do not depend on the handle's original creation time. + DeltaAggregatorHandle candidate = + previous == null ? aggregatorHandlePool.poll() : previous.remove(attributes); + boolean reused = candidate != null; + if (candidate == null) { + candidate = new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); + } + + DeltaAggregatorHandle existing = aggregatorHandles.putIfAbsent(attributes, candidate); + // A collection may have published its reset handles since the lookup above. Once a series + // has an active handle, its reset handle is redundant. The collector also checks for series + // inserted before publication, so the two maps cannot retain separate idle copies. + if (!reused && memoryMode == REUSABLE_DATA) { + previous = previousCollectionAggregatorHandles; + if (previous != null) { + previous.remove(attributes); + } + } + return existing == null ? candidate : existing; + } + @Override public BoundStorageHandle bind(Attributes attributes) { Attributes processed = attributesFilter.apply(attributes); @@ -206,14 +225,7 @@ private DeltaAggregatorHandle bindHandle(Attributes attributes) { handle = aggregatorHandles.get(attributes); } if (handle == null) { - DeltaAggregatorHandle newDeltaHandle = aggregatorHandlePool.poll(); - if (newDeltaHandle == null) { - newDeltaHandle = - new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); - } - DeltaAggregatorHandle existing = - aggregatorHandles.putIfAbsent(attributes, newDeltaHandle); - handle = existing != null ? existing : newDeltaHandle; + handle = insertHandleForNewSeries(aggregatorHandles, attributes); } handle.bound = true; return handle; @@ -234,26 +246,46 @@ public MetricData collect( // we are about to stop recording into. holder.lockForCollectAndAwait(); - // Seed the new holder with the bound handles, so that (a) the bound wrappers survive the swap - // (their bound instruments hold direct references), (b) a series recorded both bound and - // unbound continues to share one wrapper, and (c) bound series are collected every interval. - // In REUSABLE_DATA we ping-pong between two maps, so the bound wrappers are copied into the - // next - // map; in IMMUTABLE_DATA the old map is abandoned and the new map starts with only the bound - // wrappers. - ConcurrentHashMap> newHolderHandles = - (memoryMode == REUSABLE_DATA) - ? previousCollectionAggregatorHandles - : new ConcurrentHashMap<>(); + ConcurrentHashMap> aggregatorHandles = + holder.aggregatorHandles; + ConcurrentHashMap> previous = + previousCollectionAggregatorHandles; + if (memoryMode == REUSABLE_DATA && aggregatorHandles.isEmpty()) { + // No series were admitted. Keep the cache below the limit without moving its entries. + if (previous != null && previous.size() >= maxCardinality) { + previous.clear(); + } + reusableResultList.clear(); + this.aggregatorHolder = new AggregatorHolder<>(aggregatorHandles); + return EmptyMetricData.getInstance(); + } + boolean keepUnused = + previous != null && aggregatorHandles.size() + previous.size() < maxCardinality; + // For a sparse interval, leave the larger map of idle handles in place and add only the + // drained active handles to it. For a busy interval, recycle that map for new recordings. + boolean keepCacheMap = + previous != null && keepUnused && previous.size() >= aggregatorHandles.size(); + ConcurrentHashMap> nextHandles; + if (previous == null || keepCacheMap) { + nextHandles = new ConcurrentHashMap<>(); + } else { + // The holder gate excludes cache lookups until the next holder is published. + previousCollectionAggregatorHandles = null; + if (keepUnused) { + aggregatorHandles.putAll(previous); + } + previous.clear(); + nextHandles = previous; + } + + // Bound instruments hold direct references. Carry their handles into the new holder so bound + // and unbound recordings for those series continue to share the same wrapper. holder.aggregatorHandles.forEach((attributes, handle) -> { if (handle.bound) { - newHolderHandles.put(attributes, handle); + nextHandles.put(attributes, handle); } }); - this.aggregatorHolder = new AggregatorHolder<>(newHolderHandles); - - ConcurrentHashMap> aggregatorHandles = - holder.aggregatorHandles; + this.aggregatorHolder = new AggregatorHolder<>(nextHandles); // Lock and drain unbound handles (unchanged from the unbound-only path). Bound handles are // handled separately below with a tight per-handle lock window so that recording to a bound @@ -277,30 +309,6 @@ public MetricData collect( points = new ArrayList<>(aggregatorHandles.size()); } - // In DELTA aggregation temporality each Attributes is reset to 0 - // every time we perform a collection (by definition of DELTA). - // In IMMUTABLE_DATA MemoryMode, this is accomplished by swapping in a new empty holder, - // abandoning the old map so each new recording in the next interval starts fresh from 0. - // In REUSABLE_DATA MemoryMode, we strive for zero allocations. Since even removing - // a key-value from a map and putting it again on next recording will cost an allocation, - // we are keeping the aggregator handles in their map, and only reset their value once - // we finish collecting the aggregated value from each one. - // The SDK must adhere to keeping no more than maxCardinality unique Attributes in memory, - // hence during collect(), when the map is at full capacity, we try to clear away unused - // aggregator handles, so on next recording cycle using this map, there will be room for newly - // recorded Attributes. This comes at the expanse of memory allocations. This can be avoided - // if the user chooses to increase the maxCardinality. - // Bound handles are kept unconditionally since their bound instruments hold direct references. - if (memoryMode == REUSABLE_DATA) { - if (aggregatorHandles.size() >= maxCardinality) { - aggregatorHandles.forEach((attribute, handle) -> { - if (!handle.bound && !handle.handle.hasRecordedValues()) { - aggregatorHandles.remove(attribute); - } - }); - } - } - // Start time for synchronous delta instruments is the later of the previous collection // and instrument creation, so newly created instruments never predate their creation. long startEpochNanos = @@ -334,7 +342,25 @@ public MetricData collect( }); if (memoryMode == REUSABLE_DATA) { - previousCollectionAggregatorHandles = aggregatorHandles; + if (keepCacheMap && previous != null) { + // Recorders can be using the cache while we add the drained handles. An active + // insertion removes a cached duplicate; check again in case it won the race. + aggregatorHandles.forEach((attributes, handle) -> { + if (!nextHandles.containsKey(attributes)) { + previous.put(attributes, handle); + if (nextHandles.containsKey(attributes)) { + previous.remove(attributes, handle); + } + } + }); + } else { + previousCollectionAggregatorHandles = aggregatorHandles; + aggregatorHandles.forEach((attributes, handle) -> { + if (nextHandles.containsKey(attributes)) { + aggregatorHandles.remove(attributes, handle); + } + }); + } } if (points.isEmpty() || !enabled) { diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java index a13149077c0..2c06218d220 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java @@ -11,7 +11,9 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; import static org.assertj.core.api.BDDAssertions.as; import static org.assertj.core.api.InstanceOfAssertFactories.collection; +import static org.assertj.core.api.InstanceOfAssertFactories.map; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -29,10 +31,12 @@ import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoublePointData; import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorHandle; import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; @@ -46,11 +50,17 @@ import io.opentelemetry.sdk.testing.time.TestClock; import java.time.Duration; import java.time.Instant; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.event.Level; @SuppressLogger(DefaultSynchronousMetricStorage.class) @@ -365,8 +375,8 @@ void recordAndCollect_DeltaResets_ReusableData() { // Record measurement and collect at time 30 storage.recordDouble(3, Attributes.empty(), Context.current()); - // We're switched to secondary map so a handle will be created - verify(aggregator, times(2)).createHandle(testClock.now()); + // Reuse the reset handle for this series in the new interval. + verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) .hasDoubleSumSatisfying(sum -> @@ -381,10 +391,8 @@ void recordAndCollect_DeltaResets_ReusableData() { storage.recordDouble(2, Attributes.empty(), Context.current()); storage.recordDouble(4, Attributes.of(AttributeKey.stringKey("foo"), "bar"), Context.current()); - // We don't delete aggregator handles unless max cardinality reached, hence - // aggregator handle is still there, thus no handle was created for empty(), but it will for - // the "foo" - verify(aggregator, times(3)).createHandle(testClock.now()); + // Reuse the reset handle for empty attributes and create one for the new series. + verify(aggregator, times(2)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35); @@ -425,6 +433,15 @@ void recordAndCollect_DeltaResets_ReusableData() { assertThat(point.getAttributes()) .isEqualTo(Attributes.of(AttributeKey.stringKey("foo"), "bar")); }))); + + deltaReader.setLastCollectEpochNanos(45); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 50)) + .isEqualTo(EmptyMetricData.getInstance()); + deltaReader.setLastCollectEpochNanos(50); + storage.recordDouble(8, Attributes.of(AttributeKey.stringKey("foo"), "bar"), Context.root()); + verify(aggregator, times(2)).createHandle(anyLong()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 55)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(8))); } @ParameterizedTest @@ -583,6 +600,118 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void recordDuringDeltaCollection_DoesNotRetainBothHandles(boolean idleCache) throws Exception { + initialize(MemoryMode.REUSABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + if (idleCache) { + storage.recordDouble(1, Attributes.builder().put("series", "idle1").build(), Context.root()); + storage.recordDouble(2, Attributes.builder().put("series", "idle2").build(), Context.root()); + storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 5); + deltaReader.setLastCollectEpochNanos(5); + } + + CountDownLatch collecting = new CountDownLatch(1); + CountDownLatch recorded = new CountDownLatch(1); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + AggregatorHandle created = + (AggregatorHandle) invocation.callRealMethod(); + AggregatorHandle handle = spy(created); + doAnswer( + check -> { + collecting.countDown(); + Assertions.assertThat(recorded.await(10, TimeUnit.SECONDS)).isTrue(); + return check.callRealMethod(); + }) + .when(handle) + .hasRecordedValues(); + return handle; + }) + .doCallRealMethod() + .when(aggregator) + .createHandle(anyLong()); + + Attributes attributes = Attributes.of(AttributeKey.stringKey("series"), "a"); + storage.recordDouble(3, attributes, Context.root()); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future first = + executor.submit(() -> storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)); + Assertions.assertThat(collecting.await(10, TimeUnit.SECONDS)).isTrue(); + storage.recordDouble(5, attributes, Context.root()); + recorded.countDown(); + + assertThat(first.get(10, TimeUnit.SECONDS)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(3))); + assertThat(storage) + .extracting( + "previousCollectionAggregatorHandles", as(map(Attributes.class, Object.class))) + .doesNotContainKey(attributes); + deltaReader.setLastCollectEpochNanos(10); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(5))); + deltaReader.setLastCollectEpochNanos(20); + storage.recordDouble(7, attributes, Context.root()); + verify(aggregator, times(idleCache ? 4 : 2)).createHandle(anyLong()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(7))); + } finally { + recorded.countDown(); + executor.shutdownNow(); + } + } + + @Test + void bindAfterDeltaCollection_ReusesHandleAndKeepsIdleSeriesBelowLimit() { + initialize(MemoryMode.REUSABLE_DATA); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + Attributes boundSeries = Attributes.builder().put("series", "bound").build(); + Attributes idleSeries = Attributes.builder().put("series", "idle").build(); + storage.recordDouble(3, boundSeries, Context.root()); + storage.recordDouble(4, idleSeries, Context.root()); + MetricData first = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10); + deltaReader.setLastCollectEpochNanos(10); + + storage.bind(boundSeries).recordDouble(5, Context.root()); + storage.recordDouble(7, boundSeries, Context.root()); + verify(aggregator, times(2)).createHandle(anyLong()); + assertThat(first.getDoubleSumData().getPoints()) + .extracting(DoublePointData::getValue) + .containsExactlyInAnyOrder(3.0, 4.0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(boundSeries).hasValue(12))); + + // Collection rotates the bound accumulator. Recording to the idle series reuses its handle. + storage.recordDouble(9, idleSeries, Context.root()); + verify(aggregator, times(3)).createHandle(anyLong()); + } + @Test void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode() { initialize(MemoryMode.REUSABLE_DATA); @@ -631,10 +760,8 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode() { 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); } - // After first collection, we expect the secondary map which is empty to be used, - // hence handle creation will still take place - // The +1 is for the overflow handle - verify(aggregator, times((CARDINALITY_LIMIT - 1) * 2 + 1)).createHandle(testClock.now()); + // The existing series reuse their handles. Only the overflow series needs a new one. + verify(aggregator, times(CARDINALITY_LIMIT)).createHandle(testClock.now()); // Second collect metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20); @@ -676,123 +803,25 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused() { /* enabled= */ true, /* contextScopedAttributesFilter= */ null); - // 1st recording: Recording goes to active map - for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { - storage.recordDouble( - 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); - } - - // This will switch next recordings to the secondary map (which is empty) - // by making it the active map - storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10); - - // 2nd recording - deltaReader.setLastCollectEpochNanos(10); for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { - storage.recordDouble( - 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + storage.recordDouble(3, Attributes.builder().put("key", "value" + i).build(), Context.root()); } - - // This switches maps again, so next recordings will be to the first map - storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20); - - // 3rd recording: We're recording unseen attributes to a map we know is full, - // since it was filled during 1st recording - deltaReader.setLastCollectEpochNanos(20); - for (int i = CARDINALITY_LIMIT - 1; i < (CARDINALITY_LIMIT - 1) + 15; i++) { - storage.recordDouble( - 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); - } - - MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30); - - assertOnlyOverflowWasRecorded(metricData, 20, 30, 15 * 3); - - // 4th recording: We're recording unseen attributes to a map we know is full, - // since it was filled during *2nd* recording - deltaReader.setLastCollectEpochNanos(30); - for (int i = CARDINALITY_LIMIT - 1; i < (CARDINALITY_LIMIT - 1) + 15; i++) { - storage.recordDouble( - 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); - } - - metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 40); - - assertOnlyOverflowWasRecorded(metricData, 30, 40, 15 * 3); - - // 5th recording: Map should be empty, since all handlers were removed due to - // no recording being done to them - deltaReader.setLastCollectEpochNanos(40); - for (int i = 0; i < 10; i++) { - storage.recordDouble( - 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); - } - - metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 50); - - assertNumberOfPoints(metricData, 10); - assertAllPointsWithValue(metricData, 40, 50, 3); - assertOverflowDoesNotExists(metricData); - - // 6th recording: Map should be empty (we switched to secondary map), since all handlers - // were removed due to no recordings being done to them - deltaReader.setLastCollectEpochNanos(50); - for (int i = 0; i < 12; i++) { - storage.recordDouble( - 4, Attributes.builder().put("key", "value" + i).build(), Context.current()); - } - - metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 60); - - assertNumberOfPoints(metricData, 12); - assertAllPointsWithValue(metricData, 50, 60, 4); - assertOverflowDoesNotExists(metricData); - } - - @SuppressWarnings("SameParameterValue") - private static void assertOnlyOverflowWasRecorded( - MetricData metricData, long startTime, long endTime, double value) { - - assertThat(metricData) - .hasDoubleSumSatisfying(sum -> - sum.satisfies(sumData -> - assertThat(sumData.getPoints()) - .hasSize(1) - .allSatisfy(point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(startTime); - assertThat(point.getEpochNanos()).isEqualTo(endTime); - assertThat(point.getValue()).isEqualTo(value); - assertThat(point.getAttributes()) - .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW); - }))); - } - - private static void assertNumberOfPoints(MetricData metricData, int numberOfPoints) { - assertThat(metricData) + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) .hasDoubleSumSatisfying(sum -> - sum.satisfies(sumData -> assertThat(sumData.getPoints()).hasSize(numberOfPoints))); - } + sum.satisfies(data -> assertThat(data.getPoints()).hasSize(CARDINALITY_LIMIT - 1))); - private static void assertAllPointsWithValue( - MetricData metricData, long startTime, long endTime, double value) { - assertThat(metricData) - .hasDoubleSumSatisfying(sum -> - sum.satisfies(sumData -> - assertThat(sumData.getPoints()) - .allSatisfy(point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(startTime); - assertThat(point.getEpochNanos()).isEqualTo(endTime); - assertThat(point.getValue()).isEqualTo(value); - }))); - } + // Last interval's unused handles must not consume this interval's cardinality. + deltaReader.setLastCollectEpochNanos(10); + Attributes newSeries = Attributes.builder().put("key", "new-series").build(); + storage.recordDouble(5, newSeries, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(newSeries).hasValue(5))); - private static void assertOverflowDoesNotExists(MetricData metricData) { - assertThat(metricData) - .hasDoubleSumSatisfying(sum -> - sum.satisfies(sumData -> - assertThat(sumData.getPoints()) - .noneMatch(point -> - point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW)))); + // Once the retained series reach the limit, keep only the ones used this interval. + assertThat(storage) + .extracting("previousCollectionAggregatorHandles", as(map(Attributes.class, Object.class))) + .containsOnlyKeys(newSeries); } @ParameterizedTest From a417de146667376a98a961773d8cf4d42b2873bc Mon Sep 17 00:00:00 2001 From: DOKL57 Date: Sun, 22 Nov 2026 09:46:00 +0300 Subject: [PATCH 2/5] Reuse delta handles without moving map entries --- .../state/DeltaSynchronousMetricStorage.java | 293 ++++++++++-------- .../state/SynchronousMetricStorageTest.java | 70 ++++- 2 files changed, 225 insertions(+), 138 deletions(-) diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java index 2e83d7d3c51..efb6fce9cce 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java @@ -42,12 +42,20 @@ class DeltaSynchronousMetricStorage private volatile AggregatorHolder aggregatorHolder = new AggregatorHolder<>(); - // Reset unbound handles from the preceding collection, published after it drains. - // Only populated in REUSABLE_DATA mode. + // Only populated if memoryMode == REUSABLE_DATA @Nullable private volatile ConcurrentHashMap> previousCollectionAggregatorHandles; + // Only accessed by the serialized collector. + private boolean reusableMapsMayDiffer; + // Admission marks this under the current holder's gate. The collector consumes and resets + // it after closing that gate. During the handoff, writers and the collector also hold the + // new holder's monitor. + private volatile boolean currentMapChanged; + // Set under the holder gate. Bound series survive every subsequent collection. + private volatile boolean hasBoundHandles; + // Only populated if memoryMode == REUSABLE_DATA private final ArrayList reusableResultList = new ArrayList<>(); private final ConcurrentLinkedQueue> aggregatorHandlePool = @@ -113,9 +121,31 @@ private DeltaAggregatorHandle tryAcquireHandleForRecord( AggregatorHolder holder, Attributes attributes) { Objects.requireNonNull(attributes, "attributes"); attributes = attributesFilter.apply(attributes); + // Read this before looking up the handle. Once it is null, no replacement in this + // holder can still be in progress. + ConcurrentHashMap> draining = holder.draining; + DeltaAggregatorHandle handle = holder.aggregatorHandles.get(attributes); + if (handle == null || draining != null) { + return acquireOnMissOrDuringHandoff(holder, attributes, handle, draining); + } + if (!handle.tryAcquireForRecord()) { + return null; + } + if (holder.isLockedForCollect()) { + handle.releaseRecord(); + return null; + } + return handle; + } + + @Nullable + private DeltaAggregatorHandle acquireOnMissOrDuringHandoff( + AggregatorHolder holder, + Attributes attributes, + @Nullable DeltaAggregatorHandle handle, + @Nullable ConcurrentHashMap> draining) { ConcurrentHashMap> aggregatorHandles = holder.aggregatorHandles; - DeltaAggregatorHandle handle = aggregatorHandles.get(attributes); if (handle == null && aggregatorHandles.size() >= maxCardinality) { logger.log( Level.WARNING, @@ -127,35 +157,33 @@ private DeltaAggregatorHandle tryAcquireHandleForRecord( attributes = MetricStorage.CARDINALITY_OVERFLOW; handle = aggregatorHandles.get(attributes); } + if (draining != null + && (handle == null || (!handle.bound && draining.get(attributes) == handle))) { + return acquireWhileCollecting(holder, attributes, /* record= */ true); + } if (handle != null) { // Existing series: try to acquire a recording slot. Returns false if the collector has // locked this handle (odd state), meaning we should retry with the new holder. if (!handle.tryAcquireForRecord()) { return null; } - // Also check the holder-level gate. The collect thread sets it to locked (odd) and never - // resets it. This catches the window after the collect thread's awaitRecordersAndUnlock() - // decrements the per-handle state back to even but before collection finishes: a stale - // thread that read the old holder can still reach here with an even per-handle state. The - // hb chain (CT's holder lock → CT's awaitRecordersAndUnlock() decrement → this - // tryAcquireForRecord) guarantees we see the holder gate as locked at that point. - if (holder.isLockedForCollect()) { + // A stale recorder must check the holder after acquiring its recording slot. Once the + // collector closes the holder, only slots that were already admitted can record. + if (holder.isLockedForCollect() + || (draining != null && aggregatorHandles.get(attributes) != handle)) { handle.releaseRecord(); return null; } return handle; } - // New series: acquire the holder gate to coordinate with the collect thread. - // The gate ensures (a) we don't insert into a holder whose lock pass has already run, - // and (b) the per-handle pre-increment below is visible to the collect thread's lock pass. + // Reserve the new series before the collector closes this holder. if (!holder.tryAcquireForNewSeries()) { return null; } try { - handle = insertHandleForNewSeries(aggregatorHandles, attributes); - // Pre-increment per-handle state while the holder gate is still held. The collect - // thread's lock pass cannot start until all threads release the holder gate, so this - // increment is guaranteed to be observed by the lock pass before it runs. + handle = insertHandle(holder, attributes); + // Reserve a recording slot before releasing the holder gate, so the collector waits + // for this measurement. handle.acquireForRecord(); return handle; } finally { @@ -163,31 +191,54 @@ private DeltaAggregatorHandle tryAcquireHandleForRecord( } } - // Called with the holder gate acquired, so the collector cannot recycle the map while in use. - private DeltaAggregatorHandle insertHandleForNewSeries( - ConcurrentHashMap> aggregatorHandles, - Attributes attributes) { + // Called while the holder gate is held. In reusable mode copy only the reference to the + // reset handle, leaving the map entry in place for the next exchange. + private DeltaAggregatorHandle insertHandle(AggregatorHolder holder, Attributes attributes) { ConcurrentHashMap> previous = previousCollectionAggregatorHandles; - // Delta timestamps do not depend on the handle's original creation time. DeltaAggregatorHandle candidate = - previous == null ? aggregatorHandlePool.poll() : previous.remove(attributes); - boolean reused = candidate != null; + previous == null ? aggregatorHandlePool.poll() : previous.get(attributes); if (candidate == null) { candidate = new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); } + DeltaAggregatorHandle existing = holder.aggregatorHandles.putIfAbsent(attributes, candidate); + if (existing == null && memoryMode == REUSABLE_DATA) { + currentMapChanged = true; + } + return existing == null ? candidate : existing; + } - DeltaAggregatorHandle existing = aggregatorHandles.putIfAbsent(attributes, candidate); - // A collection may have published its reset handles since the lookup above. Once a series - // has an active handle, its reset handle is redundant. The collector also checks for series - // inserted before publication, so the two maps cannot retain separate idle copies. - if (!reused && memoryMode == REUSABLE_DATA) { - previous = previousCollectionAggregatorHandles; - if (previous != null) { - previous.remove(attributes); + @Nullable + private DeltaAggregatorHandle acquireWhileCollecting( + AggregatorHolder holder, Attributes attributes, boolean record) { + if (!holder.tryAcquireForNewSeries()) { + return null; + } + try { + synchronized (holder) { + ConcurrentHashMap> draining = holder.draining; + if (draining == null) { + // Retry against the final mapping. The collector may have just handed it back. + return null; + } + DeltaAggregatorHandle handle = holder.aggregatorHandles.get(attributes); + if (handle == null || (!handle.bound && draining.get(attributes) == handle)) { + handle = new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); + holder.aggregatorHandles.put(attributes, handle); + currentMapChanged = true; + } + if (record) { + if (!handle.tryAcquireForRecord()) { + return null; + } + } else { + handle.bound = true; + } + return handle; } + } finally { + holder.releaseNewSeries(); } - return existing == null ? candidate : existing; } @Override @@ -197,8 +248,9 @@ public BoundStorageHandle bind(Attributes attributes) { } @SuppressWarnings("ThreadPriorityCheck") - private DeltaAggregatorHandle bindHandle(Attributes attributes) { + private DeltaAggregatorHandle bindHandle(Attributes processed) { while (true) { + Attributes attributes = processed; AggregatorHolder holder = this.aggregatorHolder; // Always coordinate through the holder gate, even for an existing series: this serializes the // bound flag write with collect()'s bound-handle scan (which runs while the gate is locked), @@ -212,6 +264,7 @@ private DeltaAggregatorHandle bindHandle(Attributes attributes) { try { ConcurrentHashMap> aggregatorHandles = holder.aggregatorHandles; + ConcurrentHashMap> draining = holder.draining; DeltaAggregatorHandle handle = aggregatorHandles.get(attributes); if (handle == null && aggregatorHandles.size() >= maxCardinality) { logger.log( @@ -224,10 +277,18 @@ private DeltaAggregatorHandle bindHandle(Attributes attributes) { attributes = MetricStorage.CARDINALITY_OVERFLOW; handle = aggregatorHandles.get(attributes); } - if (handle == null) { - handle = insertHandleForNewSeries(aggregatorHandles, attributes); + if (draining != null) { + handle = acquireWhileCollecting(holder, attributes, /* record= */ false); + if (handle == null) { + continue; + } + } else { + if (handle == null) { + handle = insertHandle(holder, attributes); + } + handle.bound = true; } - handle.bound = true; + hasBoundHandles = true; return handle; } finally { holder.releaseNewSeries(); @@ -245,61 +306,45 @@ public MetricData collect( // holder, so the bound-handle scan below sees a stable set and no bind() can land in the holder // we are about to stop recording into. holder.lockForCollectAndAwait(); - + reusableMapsMayDiffer |= currentMapChanged; + currentMapChanged = false; + + // Seed the new holder with the bound handles, so that (a) the bound wrappers survive the swap + // (their bound instruments hold direct references), (b) a series recorded both bound and + // unbound continues to share one wrapper, and (c) bound series are collected every interval. + // In REUSABLE_DATA we ping-pong between two maps, so the bound wrappers are copied into the + // next + // map; in IMMUTABLE_DATA the old map is abandoned and the new map starts with only the bound + // wrappers. ConcurrentHashMap> aggregatorHandles = holder.aggregatorHandles; ConcurrentHashMap> previous = previousCollectionAggregatorHandles; - if (memoryMode == REUSABLE_DATA && aggregatorHandles.isEmpty()) { - // No series were admitted. Keep the cache below the limit without moving its entries. - if (previous != null && previous.size() >= maxCardinality) { - previous.clear(); - } - reusableResultList.clear(); - this.aggregatorHolder = new AggregatorHolder<>(aggregatorHandles); - return EmptyMetricData.getInstance(); + ConcurrentHashMap> newHolderHandles = + previous == null ? new ConcurrentHashMap<>() : previous; + previousCollectionAggregatorHandles = null; + AggregatorHolder next = new AggregatorHolder<>(newHolderHandles); + if (memoryMode == REUSABLE_DATA) { + next.draining = aggregatorHandles; } - boolean keepUnused = - previous != null && aggregatorHandles.size() + previous.size() < maxCardinality; - // For a sparse interval, leave the larger map of idle handles in place and add only the - // drained active handles to it. For a busy interval, recycle that map for new recordings. - boolean keepCacheMap = - previous != null && keepUnused && previous.size() >= aggregatorHandles.size(); - ConcurrentHashMap> nextHandles; - if (previous == null || keepCacheMap) { - nextHandles = new ConcurrentHashMap<>(); - } else { - // The holder gate excludes cache lookups until the next holder is published. - previousCollectionAggregatorHandles = null; - if (keepUnused) { - aggregatorHandles.putAll(previous); - } - previous.clear(); - nextHandles = previous; + if (hasBoundHandles) { + aggregatorHandles.forEach((attributes, handle) -> { + if (handle.bound) { + newHolderHandles.put(attributes, handle); + } + }); + } + if (previous != null && previous.size() >= maxCardinality && reusableMapsMayDiffer) { + // A saturated map from two intervals ago may still contain series evicted from the + // just-finished interval. Drop those idle entries before admitting new measurements. + previous.forEach((attributes, handle) -> { + if (!aggregatorHandles.containsKey(attributes)) { + previous.remove(attributes, handle); + } + }); + reusableMapsMayDiffer = previous.size() != aggregatorHandles.size(); } - - // Bound instruments hold direct references. Carry their handles into the new holder so bound - // and unbound recordings for those series continue to share the same wrapper. - holder.aggregatorHandles.forEach((attributes, handle) -> { - if (handle.bound) { - nextHandles.put(attributes, handle); - } - }); - this.aggregatorHolder = new AggregatorHolder<>(nextHandles); - - // Lock and drain unbound handles (unchanged from the unbound-only path). Bound handles are - // handled separately below with a tight per-handle lock window so that recording to a bound - // series never blocks for the duration of the whole collection. - aggregatorHandles.forEach((attributes, handle) -> { - if (!handle.bound) { - handle.lockForCollect(); - } - }); - aggregatorHandles.forEach((attributes, handle) -> { - if (!handle.bound) { - handle.awaitRecordersAndUnlock(); - } - }); + this.aggregatorHolder = next; List points; if (memoryMode == REUSABLE_DATA) { @@ -309,6 +354,9 @@ public MetricData collect( points = new ArrayList<>(aggregatorHandles.size()); } + boolean atCardinalityLimit = + memoryMode == REUSABLE_DATA && aggregatorHandles.size() >= maxCardinality; + // Start time for synchronous delta instruments is the later of the previous collection // and instrument creation, so newly created instruments never predate their creation. long startEpochNanos = @@ -316,50 +364,45 @@ public MetricData collect( registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos), instrumentCreationEpochNanos); - // Grab aggregated points. aggregatorHandles.forEach((attributes, handle) -> { if (handle.bound) { collectBound(handle, attributes, startEpochNanos, epochNanos, points); return; } - if (!handle.handle.hasRecordedValues()) { - return; - } - T point = - handle.handle.aggregateThenMaybeReset( - startEpochNanos, epochNanos, attributes, /* reset= */ true); - - if (memoryMode == IMMUTABLE_DATA) { - // Return the handle to the pool. - // Only in IMMUTABLE_DATA memory mode: in REUSABLE_DATA we avoid using the pool - // since ConcurrentLinkedQueue.offer() allocates memory internally. - aggregatorHandlePool.offer(handle); - } - - if (point != null) { - points.add(point); + // The outgoing holder is already closed. Its unbound handles only need to drain + // admitted recorders. The incoming holder replaces any of these handles it needs + // before the handoff ends. + handle.awaitUnboundRecorders(); + if (handle.handle.hasRecordedValues()) { + T point = + handle.handle.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + if (point != null) { + points.add(point); + } + if (memoryMode == IMMUTABLE_DATA) { + aggregatorHandlePool.offer(handle); + } + } else if (atCardinalityLimit) { + aggregatorHandles.remove(attributes, handle); + reusableMapsMayDiffer = true; } }); if (memoryMode == REUSABLE_DATA) { - if (keepCacheMap && previous != null) { - // Recorders can be using the cache while we add the drained handles. An active - // insertion removes a cached duplicate; check again in case it won the race. - aggregatorHandles.forEach((attributes, handle) -> { - if (!nextHandles.containsKey(attributes)) { - previous.put(attributes, handle); - if (nextHandles.containsKey(attributes)) { - previous.remove(attributes, handle); + synchronized (next) { + // A recording in the next interval may have needed a replacement while the old + // accumulator was being drained. Point both existing map entries to the live handle. + if (currentMapChanged) { + aggregatorHandles.forEach((attributes, handle) -> { + DeltaAggregatorHandle replacement = newHolderHandles.get(attributes); + if (replacement != null && replacement != handle) { + aggregatorHandles.replace(attributes, handle, replacement); } - } - }); - } else { + }); + } previousCollectionAggregatorHandles = aggregatorHandles; - aggregatorHandles.forEach((attributes, handle) -> { - if (nextHandles.containsKey(attributes)) { - aggregatorHandles.remove(attributes, handle); - } - }); + next.draining = null; } } @@ -411,6 +454,9 @@ private void collectBound( private static class AggregatorHolder { private final ConcurrentHashMap> aggregatorHandles; + // The outgoing map may share handles with this holder. Replacements and the end of the + // handoff are serialized on this holder, so replacements cannot occur once this is null. + @Nullable private volatile ConcurrentHashMap> draining; // Guards new-series creation using an even/odd protocol: // - Threads creating a new series increment by 2 (keeping the value even while unlocked) // and decrement by 2 on release. @@ -570,7 +616,7 @@ boolean tryAcquireForRecord() { /** * Acquires a recording slot unconditionally. Only safe to call while the holder gate is held, - * which prevents the collector from starting its lock pass. + * which prevents the collector from draining this slot prematurely. */ void acquireForRecord() { state.addAndGet(2); @@ -589,13 +635,12 @@ void lockForCollect() { state.addAndGet(1); } - /** Waits for all in-flight recorders to finish, then clears the collection lock. */ + /** Waits for recording slots to drain after the outgoing holder has been closed. */ @SuppressWarnings("ThreadPriorityCheck") - void awaitRecordersAndUnlock() { - while (state.get() > 1) { + void awaitUnboundRecorders() { + while (state.get() != 0) { Thread.yield(); } - state.addAndGet(-1); } /** diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java index 2c06218d220..4b061d937ac 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java @@ -55,6 +55,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -375,6 +376,11 @@ void recordAndCollect_DeltaResets_ReusableData() { // Record measurement and collect at time 30 storage.recordDouble(3, Attributes.empty(), Context.current()); + // The inactive map keeps its entry so alternating intervals can reuse the map nodes. + assertThat(storage) + .extracting("previousCollectionAggregatorHandles", as(map(Attributes.class, Object.class))) + .containsKey(Attributes.empty()); + // Reuse the reset handle for this series in the new interval. verify(aggregator, times(1)).createHandle(testClock.now()); assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); @@ -601,8 +607,8 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { } @ParameterizedTest - @ValueSource(booleans = {false, true}) - void recordDuringDeltaCollection_DoesNotRetainBothHandles(boolean idleCache) throws Exception { + @ValueSource(ints = {0, 1, 2}) + void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup) throws Exception { initialize(MemoryMode.REUSABLE_DATA); DefaultSynchronousMetricStorage storage = @@ -616,13 +622,14 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(boolean idleCache) thr /* enabled= */ true, /* contextScopedAttributesFilter= */ null); - if (idleCache) { + if (setup == 1) { storage.recordDouble(1, Attributes.builder().put("series", "idle1").build(), Context.root()); storage.recordDouble(2, Attributes.builder().put("series", "idle2").build(), Context.root()); storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 5); deltaReader.setLastCollectEpochNanos(5); } + AtomicBoolean armed = new AtomicBoolean(); CountDownLatch collecting = new CountDownLatch(1); CountDownLatch recorded = new CountDownLatch(1); doAnswer( @@ -633,8 +640,10 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(boolean idleCache) thr AggregatorHandle handle = spy(created); doAnswer( check -> { - collecting.countDown(); - Assertions.assertThat(recorded.await(10, TimeUnit.SECONDS)).isTrue(); + if (armed.get()) { + collecting.countDown(); + Assertions.assertThat(recorded.await(10, TimeUnit.SECONDS)).isTrue(); + } return check.callRealMethod(); }) .when(handle) @@ -646,7 +655,18 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(boolean idleCache) thr .createHandle(anyLong()); Attributes attributes = Attributes.of(AttributeKey.stringKey("series"), "a"); + if (setup == 2) { + // Seed both maps with the same handle. The overlapping write must replace that reference. + storage.recordDouble(1, attributes, Context.root()); + storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 5); + deltaReader.setLastCollectEpochNanos(5); + storage.recordDouble(2, attributes, Context.root()); + verify(aggregator, times(1)).createHandle(anyLong()); + storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 7); + deltaReader.setLastCollectEpochNanos(7); + } storage.recordDouble(3, attributes, Context.root()); + armed.set(true); ExecutorService executor = Executors.newSingleThreadExecutor(); try { @@ -659,15 +679,23 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(boolean idleCache) thr assertThat(first.get(10, TimeUnit.SECONDS)) .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(3))); assertThat(storage) - .extracting( - "previousCollectionAggregatorHandles", as(map(Attributes.class, Object.class))) - .doesNotContainKey(attributes); + .extracting("aggregatorHolder.aggregatorHandles", as(map(Attributes.class, Object.class))) + .hasEntrySatisfying( + attributes, + active -> + assertThat(storage) + .extracting( + "previousCollectionAggregatorHandles", + as(map(Attributes.class, Object.class))) + .hasEntrySatisfying( + attributes, + previous -> Assertions.assertThat(previous).isSameAs(active))); deltaReader.setLastCollectEpochNanos(10); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(5))); deltaReader.setLastCollectEpochNanos(20); storage.recordDouble(7, attributes, Context.root()); - verify(aggregator, times(idleCache ? 4 : 2)).createHandle(anyLong()); + verify(aggregator, times(setup == 1 ? 4 : 2)).createHandle(anyLong()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(7))); } finally { @@ -788,8 +816,9 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode() { logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); } - @Test - void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused() { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused(boolean bindNewSeries) { initialize(MemoryMode.REUSABLE_DATA); DefaultSynchronousMetricStorage storage = @@ -803,17 +832,22 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused() { /* enabled= */ true, /* contextScopedAttributesFilter= */ null); - for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + int firstIntervalSeries = CARDINALITY_LIMIT - (bindNewSeries ? 2 : 1); + for (int i = 0; i < firstIntervalSeries; i++) { storage.recordDouble(3, Attributes.builder().put("key", "value" + i).build(), Context.root()); } assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) .hasDoubleSumSatisfying(sum -> - sum.satisfies(data -> assertThat(data.getPoints()).hasSize(CARDINALITY_LIMIT - 1))); + sum.satisfies(data -> assertThat(data.getPoints()).hasSize(firstIntervalSeries))); // Last interval's unused handles must not consume this interval's cardinality. deltaReader.setLastCollectEpochNanos(10); Attributes newSeries = Attributes.builder().put("key", "new-series").build(); - storage.recordDouble(5, newSeries, Context.root()); + if (bindNewSeries) { + storage.bind(newSeries).recordDouble(5, Context.root()); + } else { + storage.recordDouble(5, newSeries, Context.root()); + } assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) .hasDoubleSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(newSeries).hasValue(5))); @@ -822,6 +856,14 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused() { assertThat(storage) .extracting("previousCollectionAggregatorHandles", as(map(Attributes.class, Object.class))) .containsOnlyKeys(newSeries); + + // Reusing the first map must not let its idle keys claim the new interval's capacity. + deltaReader.setLastCollectEpochNanos(20); + Attributes thirdSeries = Attributes.builder().put("key", "third-series").build(); + storage.recordDouble(7, thirdSeries, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(thirdSeries).hasValue(7))); } @ParameterizedTest From 0e35619b5e7b8bf8c33848c1a3797b9a222db4b8 Mon Sep 17 00:00:00 2001 From: DOKL57 Date: Sun, 22 Nov 2026 09:50:01 +0300 Subject: [PATCH 3/5] Reuse the delta collection callback --- .../state/DeltaSynchronousMetricStorage.java | 72 ++++++++++++------- 1 file changed, 48 insertions(+), 24 deletions(-) diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java index efb6fce9cce..f61dd460659 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java @@ -24,11 +24,13 @@ import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import io.opentelemetry.sdk.resources.Resource; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.logging.Level; @@ -58,6 +60,7 @@ class DeltaSynchronousMetricStorage // Only populated if memoryMode == REUSABLE_DATA private final ArrayList reusableResultList = new ArrayList<>(); + private final PointCollector pointCollector = new PointCollector(); private final ConcurrentLinkedQueue> aggregatorHandlePool = new ConcurrentLinkedQueue<>(); @@ -364,30 +367,16 @@ public MetricData collect( registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos), instrumentCreationEpochNanos); - aggregatorHandles.forEach((attributes, handle) -> { - if (handle.bound) { - collectBound(handle, attributes, startEpochNanos, epochNanos, points); - return; - } - // The outgoing holder is already closed. Its unbound handles only need to drain - // admitted recorders. The incoming holder replaces any of these handles it needs - // before the handoff ends. - handle.awaitUnboundRecorders(); - if (handle.handle.hasRecordedValues()) { - T point = - handle.handle.aggregateThenMaybeReset( - startEpochNanos, epochNanos, attributes, /* reset= */ true); - if (point != null) { - points.add(point); - } - if (memoryMode == IMMUTABLE_DATA) { - aggregatorHandlePool.offer(handle); - } - } else if (atCardinalityLimit) { - aggregatorHandles.remove(attributes, handle); - reusableMapsMayDiffer = true; - } - }); + pointCollector.points = points; + pointCollector.pruneFrom = atCardinalityLimit ? aggregatorHandles : null; + pointCollector.startEpochNanos = startEpochNanos; + pointCollector.epochNanos = epochNanos; + try { + aggregatorHandles.forEach(pointCollector); + } finally { + pointCollector.points = Collections.emptyList(); + pointCollector.pruneFrom = null; + } if (memoryMode == REUSABLE_DATA) { synchronized (next) { @@ -414,6 +403,41 @@ public MetricData collect( resource, instrumentationScopeInfo, metricDescriptor, points, DELTA); } + // Collection is serialized. Reuse the visitor to avoid a capturing lambda per collection, + // including when a retained map has no recorded points. + private final class PointCollector implements BiConsumer> { + private List points = Collections.emptyList(); + @Nullable private ConcurrentHashMap> pruneFrom; + private long startEpochNanos; + private long epochNanos; + + @Override + public void accept(Attributes attributes, DeltaAggregatorHandle handle) { + if (handle.bound) { + collectBound(handle, attributes, startEpochNanos, epochNanos, points); + return; + } + // The outgoing holder is already closed. Its unbound handles only need to drain + // admitted recorders. The incoming holder replaces any of these handles it needs + // before the handoff ends. + handle.awaitUnboundRecorders(); + if (handle.handle.hasRecordedValues()) { + T point = + handle.handle.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + if (point != null) { + points.add(point); + } + if (memoryMode == IMMUTABLE_DATA) { + aggregatorHandlePool.offer(handle); + } + } else if (pruneFrom != null) { + pruneFrom.remove(attributes, handle); + reusableMapsMayDiffer = true; + } + } + } + /** * Collects a bound handle by rotation: drain in-flight recorders, swap in a fresh (already-zero) * accumulator while locked, unlock so recorders resume on the fresh accumulator, then aggregate From 494ae01594d15e80c600585764d9f62c3a7d358b Mon Sep 17 00:00:00 2001 From: DOKL57 Date: Sun, 22 Nov 2026 11:52:18 +0300 Subject: [PATCH 4/5] Cover DELTA storage handoff and idle eviction --- .../state/SynchronousMetricStorageTest.java | 123 +++++++++++++++++- 1 file changed, 119 insertions(+), 4 deletions(-) diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java index 4b061d937ac..5ac5edd561e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java @@ -60,6 +60,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.event.Level; @@ -607,8 +608,9 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { } @ParameterizedTest - @ValueSource(ints = {0, 1, 2}) - void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup) throws Exception { + @CsvSource({"0, false", "1, false", "2, false", "2, true"}) + void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup, boolean bindDuringCollection) + throws Exception { initialize(MemoryMode.REUSABLE_DATA); DefaultSynchronousMetricStorage storage = @@ -673,7 +675,12 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup) throws Exce Future first = executor.submit(() -> storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)); Assertions.assertThat(collecting.await(10, TimeUnit.SECONDS)).isTrue(); - storage.recordDouble(5, attributes, Context.root()); + if (bindDuringCollection) { + storage.bind(attributes).recordDouble(2, Context.root()); + } else { + storage.recordDouble(2, attributes, Context.root()); + } + storage.recordDouble(3, attributes, Context.root()); recorded.countDown(); assertThat(first.get(10, TimeUnit.SECONDS)) @@ -695,7 +702,11 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup) throws Exce .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(5))); deltaReader.setLastCollectEpochNanos(20); storage.recordDouble(7, attributes, Context.root()); - verify(aggregator, times(setup == 1 ? 4 : 2)).createHandle(anyLong()); + int expectedHandles = setup == 1 ? 4 : 2; + if (bindDuringCollection) { + expectedHandles++; + } + verify(aggregator, times(expectedHandles)).createHandle(anyLong()); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(7))); } finally { @@ -704,6 +715,62 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup) throws Exce } } + @Test + void recordAfterDeltaHolderCloses_RetriesInNextInterval() throws Exception { + initialize(MemoryMode.REUSABLE_DATA); + + AtomicBoolean pauseNextRecord = new AtomicBoolean(); + CountDownLatch filtering = new CountDownLatch(1); + CountDownLatch resumeRecord = new CountDownLatch(1); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + attributes -> { + if (pauseNextRecord.compareAndSet(true, false)) { + // The recorder has read the holder but has not looked up the series yet. + filtering.countDown(); + try { + assertThat(resumeRecord.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + } + return attributes; + }, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + Attributes attributes = Attributes.of(AttributeKey.stringKey("series"), "a"); + storage.recordDouble(3, attributes, Context.root()); + pauseNextRecord.set(true); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future record = executor.submit(() -> storage.recordDouble(5, attributes, Context.root())); + assertThat(filtering.await(10, TimeUnit.SECONDS)).isTrue(); + + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(attributes).hasValue(3))); + deltaReader.setLastCollectEpochNanos(10); + resumeRecord.countDown(); + record.get(10, TimeUnit.SECONDS); + + verify(aggregator, times(1)).createHandle(anyLong()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(attributes).hasValue(5))); + } finally { + resumeRecord.countDown(); + executor.shutdownNow(); + } + } + @Test void bindAfterDeltaCollection_ReusesHandleAndKeepsIdleSeriesBelowLimit() { initialize(MemoryMode.REUSABLE_DATA); @@ -866,6 +933,54 @@ void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused(boolean b sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(thirdSeries).hasValue(7))); } + @Test + void recordAndCollect_DeltaAtLimit_ReclaimsInactiveRetainedSeries() { + initialize(MemoryMode.REUSABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + /* maxCardinality= */ 3, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + AttributeKey key = AttributeKey.stringKey("series"); + Attributes active = Attributes.of(key, "active"); + Attributes idle = Attributes.of(key, "idle"); + Attributes newcomer = Attributes.of(key, "new"); + + // Fill both maps up to the limit for regular series. + for (long end : new long[] {10, 20}) { + storage.recordDouble(1, active, Context.root()); + storage.recordDouble(2, idle, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, end)) + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasAttributes(active).hasValue(1), + point -> point.hasAttributes(idle).hasValue(2))); + deltaReader.setLastCollectEpochNanos(end); + } + + storage.recordDouble(3, active, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(active).hasValue(3))); + deltaReader.setLastCollectEpochNanos(30); + + // Let the collector exchange the maps again before admitting a new series. + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 40)) + .isSameAs(EmptyMetricData.getInstance()); + deltaReader.setLastCollectEpochNanos(40); + storage.recordDouble(5, newcomer, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 50)) + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasAttributes(newcomer).hasValue(5))); + } + @ParameterizedTest @EnumSource(MemoryMode.class) void enabledThenDisable_isEnabled(MemoryMode memoryMode) { From 7f21c3a7e3d7867ec7fe577213f22edf46050fab Mon Sep 17 00:00:00 2001 From: DOKL57 Date: Sun, 22 Nov 2026 12:44:44 +0300 Subject: [PATCH 5/5] Cover the remaining DELTA collection branches --- .../state/DeltaSynchronousMetricStorage.java | 7 +- .../state/SynchronousMetricStorageTest.java | 251 +++++++++++++++++- 2 files changed, 254 insertions(+), 4 deletions(-) diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java index f61dd460659..b254b85a93a 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java @@ -231,9 +231,10 @@ private DeltaAggregatorHandle acquireWhileCollecting( currentMapChanged = true; } if (record) { - if (!handle.tryAcquireForRecord()) { - return null; - } + // The caller only enters this path for a missing or shared unbound series. + // The selected handle is independent of the outgoing collector, and the holder + // gate prevents the incoming collector from closing it before admission. + handle.acquireForRecord(); } else { handle.bound = true; } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java index 5ac5edd561e..8ab3f8667a5 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java @@ -14,6 +14,7 @@ import static org.assertj.core.api.InstanceOfAssertFactories.map; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -22,6 +23,7 @@ import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.context.Context; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; @@ -50,12 +52,17 @@ import io.opentelemetry.sdk.testing.time.TestClock; import java.time.Duration; import java.time.Instant; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -676,7 +683,8 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup, boolean bin executor.submit(() -> storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)); Assertions.assertThat(collecting.await(10, TimeUnit.SECONDS)).isTrue(); if (bindDuringCollection) { - storage.bind(attributes).recordDouble(2, Context.root()); + storage.bind(attributes).recordDouble(1, Context.root()); + storage.bind(attributes).recordDouble(1, Context.root()); } else { storage.recordDouble(2, attributes, Context.root()); } @@ -715,6 +723,194 @@ void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup, boolean bin } } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void recordOrBindUsingStaleHandoff_RetriesOnLiveHandle(boolean bind) throws Exception { + initialize(MemoryMode.REUSABLE_DATA); + + CountDownLatch lookingUp = new CountDownLatch(1); + CountDownLatch resumeLookup = new CountDownLatch(1); + AtomicReference recorder = new AtomicReference<>(); + AtomicInteger lookups = new AtomicInteger(); + Attributes attributes = + new LookupControlledAttributes( + Attributes.of(AttributeKey.stringKey("series"), "a"), + () -> { + // Pause a bind on the incoming lookup, or a record on the outgoing lookup. + if (Thread.currentThread() == recorder.get() + && lookups.incrementAndGet() == (bind ? 1 : 2)) { + lookingUp.countDown(); + awaitLatch(resumeLookup); + } + }); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + CountDownLatch collecting = new CountDownLatch(1); + CountDownLatch resumeCollect = new CountDownLatch(1); + pauseCollectionAtRecordedValues(3, collecting, resumeCollect); + + // Populate both maps with the same unbound handle. + for (long end : new long[] {5, 7}) { + storage.recordDouble(1, attributes, Context.root()); + storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, end); + deltaReader.setLastCollectEpochNanos(end); + } + storage.recordDouble(3, attributes, Context.root()); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future collected = + executor.submit(() -> storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)); + awaitLatch(collecting); + Future lateRecord = + executor.submit(() -> { + recorder.set(Thread.currentThread()); + if (bind) { + storage.bind(attributes).recordDouble(7, Context.root()); + } else { + storage.recordDouble(7, attributes, Context.root()); + } + }); + awaitLatch(lookingUp); + // Replace the shared handle, then finish the handoff while the lookup is paused. + storage.recordDouble(5, attributes, Context.root()); + if (bind) { + // The replacement already belongs to the incoming interval and can be bound as is. + storage.bind(attributes); + } + resumeCollect.countDown(); + assertThat(collected.get(10, TimeUnit.SECONDS)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(3))); + deltaReader.setLastCollectEpochNanos(10); + + resumeLookup.countDown(); + lateRecord.get(10, TimeUnit.SECONDS); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(12))); + } finally { + resumeCollect.countDown(); + resumeLookup.countDown(); + executor.shutdownNow(); + } + } + + @Test + void recordWhileBoundHandleRotates_RetriesInNextInterval() throws Exception { + initialize(IMMUTABLE_DATA); + + AtomicInteger attempts = new AtomicInteger(); + CountDownLatch retrying = new CountDownLatch(1); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + attributes -> { + if (attempts.incrementAndGet() == 3) { + // Binding called the filter once, followed by two attempts to record. + retrying.countDown(); + } + return attributes; + }, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + CountDownLatch collecting = new CountDownLatch(1); + CountDownLatch resumeCollect = new CountDownLatch(1); + pauseCollectionAtRecordedValues(1, collecting, resumeCollect); + Attributes attributes = Attributes.of(AttributeKey.stringKey("series"), "a"); + storage.bind(attributes).recordDouble(3, Context.root()); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future collected = + executor.submit(() -> storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)); + awaitLatch(collecting); + Future record = executor.submit(() -> storage.recordDouble(5, attributes, Context.root())); + awaitLatch(retrying); + resumeCollect.countDown(); + + assertThat(collected.get(10, TimeUnit.SECONDS)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(3))); + record.get(10, TimeUnit.SECONDS); + deltaReader.setLastCollectEpochNanos(10); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(5))); + } finally { + resumeCollect.countDown(); + executor.shutdownNow(); + } + } + + @Test + void recordAndCollect_DeltaSkipsAbsentPoint() { + initialize(MemoryMode.REUSABLE_DATA); + Attributes attributes = Attributes.of(AttributeKey.stringKey("series"), "a"); + AggregatorHandle handle = spy(aggregator.createHandle(testClock.now())); + doReturn(handle).when(aggregator).createHandle(anyLong()); + doAnswer( + invocation -> { + invocation.callRealMethod(); + return null; + }) + .when(handle) + .aggregateThenMaybeReset(0, 10, attributes, /* reset= */ true); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + storage.recordDouble(3, attributes, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .isSameAs(EmptyMetricData.getInstance()); + deltaReader.setLastCollectEpochNanos(10); + + storage.recordDouble(5, attributes, Context.root()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(5))); + } + + private void pauseCollectionAtRecordedValues( + int collection, CountDownLatch collecting, CountDownLatch resumeCollect) { + AggregatorHandle handle = spy(aggregator.createHandle(testClock.now())); + doReturn(handle).doCallRealMethod().when(aggregator).createHandle(anyLong()); + AtomicInteger collections = new AtomicInteger(); + doAnswer( + invocation -> { + if (collections.incrementAndGet() == collection) { + collecting.countDown(); + awaitLatch(resumeCollect); + } + return invocation.callRealMethod(); + }) + .when(handle) + .hasRecordedValues(); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + } + @Test void recordAfterDeltaHolderCloses_RetriesInNextInterval() throws Exception { initialize(MemoryMode.REUSABLE_DATA); @@ -1070,4 +1266,57 @@ void enabledThenDisableThenEnable_recordAndCollect(MemoryMode memoryMode) { assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10).isEmpty()).isFalse(); } + + private static final class LookupControlledAttributes implements Attributes { + private final Attributes delegate; + private final Runnable onLookup; + + private LookupControlledAttributes(Attributes delegate, Runnable onLookup) { + this.delegate = delegate; + this.onLookup = onLookup; + } + + @Override + @Nullable + public T get(AttributeKey key) { + return delegate.get(key); + } + + @Override + public void forEach(BiConsumer, ? super Object> consumer) { + delegate.forEach(consumer); + } + + @Override + public int size() { + return delegate.size(); + } + + @Override + public boolean isEmpty() { + return delegate.isEmpty(); + } + + @Override + public Map, Object> asMap() { + return delegate.asMap(); + } + + @Override + public AttributesBuilder toBuilder() { + return delegate.toBuilder(); + } + + @Override + public boolean equals(Object other) { + return other instanceof LookupControlledAttributes + && delegate.equals(((LookupControlledAttributes) other).delegate); + } + + @Override + public int hashCode() { + onLookup.run(); + return delegate.hashCode(); + } + } }