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..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 @@ -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; @@ -41,11 +43,24 @@ class DeltaSynchronousMetricStorage private final MemoryMode memoryMode; private volatile AggregatorHolder aggregatorHolder = new AggregatorHolder<>(); + // Only populated if memoryMode == REUSABLE_DATA + @Nullable private volatile ConcurrentHashMap> - previousCollectionAggregatorHandles = new 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 PointCollector pointCollector = new PointCollector(); private final ConcurrentLinkedQueue> aggregatorHandlePool = new ConcurrentLinkedQueue<>(); @@ -109,9 +124,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, @@ -123,47 +160,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 { - // 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; - } - // 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 { @@ -171,6 +194,57 @@ private DeltaAggregatorHandle tryAcquireHandleForRecord( } } + // 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; + DeltaAggregatorHandle candidate = + 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; + } + + @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) { + // 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; + } + return handle; + } + } finally { + holder.releaseNewSeries(); + } + } + @Override public BoundStorageHandle bind(Attributes attributes) { Attributes processed = attributesFilter.apply(attributes); @@ -178,8 +252,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), @@ -193,6 +268,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( @@ -205,17 +281,18 @@ private DeltaAggregatorHandle bindHandle(Attributes attributes) { attributes = MetricStorage.CARDINALITY_OVERFLOW; handle = aggregatorHandles.get(attributes); } - if (handle == null) { - DeltaAggregatorHandle newDeltaHandle = aggregatorHandlePool.poll(); - if (newDeltaHandle == null) { - newDeltaHandle = - new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); + if (draining != null) { + handle = acquireWhileCollecting(holder, attributes, /* record= */ false); + if (handle == null) { + continue; } - DeltaAggregatorHandle existing = - aggregatorHandles.putIfAbsent(attributes, newDeltaHandle); - handle = existing != null ? existing : newDeltaHandle; + } else { + if (handle == null) { + handle = insertHandle(holder, attributes); + } + handle.bound = true; } - handle.bound = true; + hasBoundHandles = true; return handle; } finally { holder.releaseNewSeries(); @@ -233,6 +310,8 @@ 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 @@ -241,33 +320,35 @@ public MetricData collect( // 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<>(); - holder.aggregatorHandles.forEach((attributes, handle) -> { - if (handle.bound) { - newHolderHandles.put(attributes, handle); - } - }); - this.aggregatorHolder = new AggregatorHolder<>(newHolderHandles); - ConcurrentHashMap> aggregatorHandles = holder.aggregatorHandles; - - // 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(); - } - }); + ConcurrentHashMap> previous = + previousCollectionAggregatorHandles; + ConcurrentHashMap> newHolderHandles = + previous == null ? new ConcurrentHashMap<>() : previous; + previousCollectionAggregatorHandles = null; + AggregatorHolder next = new AggregatorHolder<>(newHolderHandles); + if (memoryMode == REUSABLE_DATA) { + next.draining = aggregatorHandles; + } + 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(); + } + this.aggregatorHolder = next; List points; if (memoryMode == REUSABLE_DATA) { @@ -277,29 +358,8 @@ 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); - } - }); - } - } + 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. @@ -308,33 +368,32 @@ 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); - } - }); + 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) { - previousCollectionAggregatorHandles = aggregatorHandles; + 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); + } + }); + } + previousCollectionAggregatorHandles = aggregatorHandles; + next.draining = null; + } } if (points.isEmpty() || !enabled) { @@ -345,6 +404,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 @@ -385,6 +479,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. @@ -544,7 +641,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); @@ -563,13 +660,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 a13149077c0..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 @@ -11,7 +11,10 @@ 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.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -20,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; @@ -29,10 +33,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 +52,24 @@ 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; 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; @SuppressLogger(DefaultSynchronousMetricStorage.class) @@ -365,8 +384,13 @@ 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()); + // 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); assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) .hasDoubleSumSatisfying(sum -> @@ -381,10 +405,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 +447,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 +614,395 @@ void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); } + @ParameterizedTest + @CsvSource({"0, false", "1, false", "2, false", "2, true"}) + void recordDuringDeltaCollection_DoesNotRetainBothHandles(int setup, boolean bindDuringCollection) + 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 (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( + invocation -> { + @SuppressWarnings("unchecked") + AggregatorHandle created = + (AggregatorHandle) invocation.callRealMethod(); + AggregatorHandle handle = spy(created); + doAnswer( + check -> { + if (armed.get()) { + 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"); + 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 { + Future first = + executor.submit(() -> storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)); + Assertions.assertThat(collecting.await(10, TimeUnit.SECONDS)).isTrue(); + if (bindDuringCollection) { + storage.bind(attributes).recordDouble(1, Context.root()); + storage.bind(attributes).recordDouble(1, Context.root()); + } else { + storage.recordDouble(2, attributes, Context.root()); + } + storage.recordDouble(3, attributes, Context.root()); + recorded.countDown(); + + assertThat(first.get(10, TimeUnit.SECONDS)) + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(3))); + assertThat(storage) + .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()); + 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 { + recorded.countDown(); + executor.shutdownNow(); + } + } + + @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); + + 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); + 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 +1051,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); @@ -661,8 +1079,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 = @@ -676,123 +1095,86 @@ 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()); + 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(firstIntervalSeries))); - // 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 + // Last interval's unused handles must not consume this interval's cardinality. deltaReader.setLastCollectEpochNanos(10); - for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { - storage.recordDouble( - 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + Attributes newSeries = Attributes.builder().put("key", "new-series").build(); + 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))); - // This switches maps again, so next recordings will be to the first map - storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20); + // 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); - // 3rd recording: We're recording unseen attributes to a map we know is full, - // since it was filled during 1st recording + // Reusing the first map must not let its idle keys claim the new interval's capacity. 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()); - } + 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))); + } - MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30); + @Test + void recordAndCollect_DeltaAtLimit_ReclaimsInactiveRetainedSeries() { + initialize(MemoryMode.REUSABLE_DATA); - assertOnlyOverflowWasRecorded(metricData, 20, 30, 15 * 3); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + /* maxCardinality= */ 3, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); - // 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()); + 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); } - metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 40); - - assertOnlyOverflowWasRecorded(metricData, 30, 40, 15 * 3); + 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); - // 5th recording: Map should be empty, since all handlers were removed due to - // no recording being done to them + // 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); - 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) - .hasDoubleSumSatisfying(sum -> - sum.satisfies(sumData -> assertThat(sumData.getPoints()).hasSize(numberOfPoints))); - } - - 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); - }))); - } - - private static void assertOverflowDoesNotExists(MetricData metricData) { - assertThat(metricData) - .hasDoubleSumSatisfying(sum -> - sum.satisfies(sumData -> - assertThat(sumData.getPoints()) - .noneMatch(point -> - point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW)))); + 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 @@ -884,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(); + } + } }