From f394e0e6aaafefd55d717457ba779034ffb202bb Mon Sep 17 00:00:00 2001 From: QJ Yu Date: Fri, 27 Nov 2026 12:35:06 -0800 Subject: [PATCH 1/6] [Issue-3874] Add characterization test. --- opentelemetry-sdk/src/metrics/mod.rs | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/opentelemetry-sdk/src/metrics/mod.rs b/opentelemetry-sdk/src/metrics/mod.rs index 22ac9d030b..c2e5166564 100644 --- a/opentelemetry-sdk/src/metrics/mod.rs +++ b/opentelemetry-sdk/src/metrics/mod.rs @@ -335,6 +335,45 @@ mod tests { counter_aggregation_helper(Temporality::Cumulative); } + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn dropped_cumulative_instruments_remain_exported() { + let test_context = TestContext::new(Temporality::Cumulative); + let meter = test_context.meter(); + + for i in 0..3 { + let name = format!("subsystem_{i}_requests"); + let counter = meter.u64_counter(name).build(); + counter.add(1, &[]); + drop(counter); + + test_context.flush_metrics(); + let resource_metrics = test_context + .exporter + .get_finished_metrics() + .expect("metrics expected to be exported"); + let metrics: Vec<_> = resource_metrics + .iter() + .flat_map(|rm| &rm.scope_metrics) + .flat_map(|sm| &sm.metrics) + .collect(); + + assert_eq!( + metrics.len(), + i + 1, + "dropped instrument metrics continue to accumulate in later collections" + ); + for stale_i in 0..=i { + let stale_name = format!("subsystem_{stale_i}_requests"); + assert!( + metrics.iter().any(|metric| metric.name == stale_name), + "expected stale instrument {stale_name} to remain exported" + ); + } + + test_context.reset_metrics(); + } + } + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn counter_aggregation_no_attributes_cumulative() { let mut test_context = TestContext::new(Temporality::Cumulative); From ebb4921dc8fd0f37b18604880d164316cd23a85c Mon Sep 17 00:00:00 2001 From: QJ Yu Date: Sun, 29 Nov 2026 17:17:57 -0800 Subject: [PATCH 2/6] [3874] Add a mock API endpoint and tests for asserting new behaviors. --- opentelemetry-sdk/CHANGELOG.md | 2 + .../src/metrics/meter_provider.rs | 7 +- opentelemetry-sdk/src/metrics/mod.rs | 101 ++++++++++++------ 3 files changed, 79 insertions(+), 31 deletions(-) diff --git a/opentelemetry-sdk/CHANGELOG.md b/opentelemetry-sdk/CHANGELOG.md index 09c0ee80cc..4c29fdec5e 100644 --- a/opentelemetry-sdk/CHANGELOG.md +++ b/opentelemetry-sdk/CHANGELOG.md @@ -2,6 +2,8 @@ ## vNext +- Add a stub `SdkMeterProvider::expire_series` API for expiring a metric series + by instrument name and attributes. The method currently does nothing. - Improved metrics measurement performance by speeding up attribute set lookups (faster `KeyValue` equality and boxed attribute keys). ([#3787](https://github.com/open-telemetry/opentelemetry-rust/pull/3787)) diff --git a/opentelemetry-sdk/src/metrics/meter_provider.rs b/opentelemetry-sdk/src/metrics/meter_provider.rs index e79477313f..69ca2a9c0f 100644 --- a/opentelemetry-sdk/src/metrics/meter_provider.rs +++ b/opentelemetry-sdk/src/metrics/meter_provider.rs @@ -1,7 +1,7 @@ use core::fmt; use opentelemetry::{ metrics::{Meter, MeterProvider}, - otel_debug, otel_error, otel_info, InstrumentationScope, + otel_debug, otel_error, otel_info, InstrumentationScope, KeyValue, }; use std::time::Duration; use std::{ @@ -104,6 +104,11 @@ impl SdkMeterProvider { self.inner.force_flush() } + /// Expires a metric series identified by its instrument name and attributes. + /// + /// This method currently does nothing. + pub fn expire_series(&self, _instrument_name: &str, _attributes: &[KeyValue]) {} + /// Shuts down the meter provider flushing all pending telemetry and releasing /// any held computational resources. /// diff --git a/opentelemetry-sdk/src/metrics/mod.rs b/opentelemetry-sdk/src/metrics/mod.rs index c2e5166564..0e657a3b8e 100644 --- a/opentelemetry-sdk/src/metrics/mod.rs +++ b/opentelemetry-sdk/src/metrics/mod.rs @@ -336,42 +336,83 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] - async fn dropped_cumulative_instruments_remain_exported() { + async fn expired_series_are_not_collected() { let test_context = TestContext::new(Temporality::Cumulative); let meter = test_context.meter(); + let stale_name = "subsystem_stale_requests"; + let live_name = "subsystem_live_requests"; + let stale_counter = meter.u64_counter(stale_name).build(); + let live_counter = meter.u64_counter(live_name).build(); + stale_counter.add(1, &[]); + live_counter.add(1, &[]); - for i in 0..3 { - let name = format!("subsystem_{i}_requests"); - let counter = meter.u64_counter(name).build(); - counter.add(1, &[]); - drop(counter); + test_context.flush_metrics(); + drop(stale_counter); + test_context.meter_provider.expire_series(stale_name, &[]); + test_context.reset_metrics(); + test_context.flush_metrics(); + let resource_metrics = test_context + .exporter + .get_finished_metrics() + .expect("metrics expected to be exported"); + let metrics: Vec<_> = resource_metrics + .iter() + .flat_map(|rm| &rm.scope_metrics) + .flat_map(|sm| &sm.metrics) + .collect(); - test_context.flush_metrics(); - let resource_metrics = test_context - .exporter - .get_finished_metrics() - .expect("metrics expected to be exported"); - let metrics: Vec<_> = resource_metrics - .iter() - .flat_map(|rm| &rm.scope_metrics) - .flat_map(|sm| &sm.metrics) - .collect(); + assert!( + !metrics.iter().any(|metric| metric.name == stale_name), + "expired series should no longer be collected" + ); + assert!( + metrics.iter().any(|metric| metric.name == live_name), + "expiration should not remove an unrelated live series" + ); + } - assert_eq!( - metrics.len(), - i + 1, - "dropped instrument metrics continue to accumulate in later collections" - ); - for stale_i in 0..=i { - let stale_name = format!("subsystem_{stale_i}_requests"); - assert!( - metrics.iter().any(|metric| metric.name == stale_name), - "expected stale instrument {stale_name} to remain exported" - ); - } + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn expired_series_are_not_queryable() { + let test_context = TestContext::new(Temporality::Cumulative); + let counter = test_context + .meter() + .u64_counter("subsystem_requests") + .build(); + let stale_attributes = [KeyValue::new("subsystem", "stale")]; + let live_attributes = [KeyValue::new("subsystem", "live")]; + counter.add(1, &stale_attributes); + counter.add(1, &live_attributes); - test_context.reset_metrics(); - } + test_context.flush_metrics(); + test_context + .meter_provider + .expire_series("subsystem_requests", &stale_attributes); + test_context.reset_metrics(); + test_context.flush_metrics(); + let resource_metrics = test_context + .exporter + .get_finished_metrics() + .expect("metrics expected to be exported"); + let metric = resource_metrics + .iter() + .flat_map(|rm| &rm.scope_metrics) + .flat_map(|sm| &sm.metrics) + .find(|metric| metric.name == "subsystem_requests") + .expect("live series should keep the metric collected"); + let MetricData::Sum(sum) = u64::extract_metrics_data_ref(&metric.data) + .expect("counter should use sum aggregation") + else { + unreachable!() + }; + + assert!( + find_sum_datapoint_with_key_value(&sum.data_points, "subsystem", "stale").is_none(), + "query results should not include expired series" + ); + assert!( + find_sum_datapoint_with_key_value(&sum.data_points, "subsystem", "live").is_some(), + "query results should include the unexpired series" + ); } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] From 6b093eda174c25192eaca9ea7470942de84425d9 Mon Sep 17 00:00:00 2001 From: QJ Yu Date: Mon, 30 Nov 2026 17:54:43 -0800 Subject: [PATCH 3/6] [issue-3874] update. --- opentelemetry-sdk/CHANGELOG.md | 3 +-- opentelemetry-sdk/src/metrics/meter_provider.rs | 7 ++----- opentelemetry/CHANGELOG.md | 2 ++ opentelemetry/src/metrics/meter.rs | 13 +++++++++++++ 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/opentelemetry-sdk/CHANGELOG.md b/opentelemetry-sdk/CHANGELOG.md index 4c29fdec5e..60404b1312 100644 --- a/opentelemetry-sdk/CHANGELOG.md +++ b/opentelemetry-sdk/CHANGELOG.md @@ -2,8 +2,7 @@ ## vNext -- Add a stub `SdkMeterProvider::expire_series` API for expiring a metric series - by instrument name and attributes. The method currently does nothing. +- Move the stub `expire_series` method to the API's `MeterProvider` trait. - Improved metrics measurement performance by speeding up attribute set lookups (faster `KeyValue` equality and boxed attribute keys). ([#3787](https://github.com/open-telemetry/opentelemetry-rust/pull/3787)) diff --git a/opentelemetry-sdk/src/metrics/meter_provider.rs b/opentelemetry-sdk/src/metrics/meter_provider.rs index 69ca2a9c0f..ee6233b63e 100644 --- a/opentelemetry-sdk/src/metrics/meter_provider.rs +++ b/opentelemetry-sdk/src/metrics/meter_provider.rs @@ -104,11 +104,6 @@ impl SdkMeterProvider { self.inner.force_flush() } - /// Expires a metric series identified by its instrument name and attributes. - /// - /// This method currently does nothing. - pub fn expire_series(&self, _instrument_name: &str, _attributes: &[KeyValue]) {} - /// Shuts down the meter provider flushing all pending telemetry and releasing /// any held computational resources. /// @@ -194,6 +189,8 @@ impl Drop for SdkMeterProviderInner { } impl MeterProvider for SdkMeterProvider { + fn remove_series(&self, _instrument_name: &str, _attributes: &[KeyValue]) {} + fn meter(&self, name: &'static str) -> Meter { let scope = InstrumentationScope::builder(name).build(); self.meter_with_scope(scope) diff --git a/opentelemetry/CHANGELOG.md b/opentelemetry/CHANGELOG.md index 9736a59703..12f3851c6f 100644 --- a/opentelemetry/CHANGELOG.md +++ b/opentelemetry/CHANGELOG.md @@ -2,6 +2,8 @@ ## vNext +- Add `MeterProvider::expire_series` for requesting expiration of a metric series. + The default implementation does nothing. - Added `TraceFlags::RANDOM`, `TraceFlags::is_random`, `TraceFlags::with_random`, and `SpanContext::is_random` for the W3C Trace Context Level 2 `random-trace-id` flag ([#3270](https://github.com/open-telemetry/opentelemetry-rust/issues/3270)). diff --git a/opentelemetry/src/metrics/meter.rs b/opentelemetry/src/metrics/meter.rs index 0c919fe1f3..2539a1b237 100644 --- a/opentelemetry/src/metrics/meter.rs +++ b/opentelemetry/src/metrics/meter.rs @@ -7,6 +7,7 @@ use crate::metrics::{ ObservableGauge, ObservableUpDownCounter, UpDownCounter, }; use crate::InstrumentationScope; +use crate::KeyValue; use super::{Counter, Histogram, HistogramBuilder}; @@ -60,6 +61,18 @@ pub trait MeterProvider { /// let meter = provider.meter_with_scope(scope); /// ``` fn meter_with_scope(&self, scope: InstrumentationScope) -> Meter; + + /// Requests that a metric series identified by its instrument name and + /// attributes no longer be exported from the collection. + /// + /// If the same attributes are recorded afterwards, it will start a new + /// series with a new start time. + /// + /// A non-existent instrument name or attribute set is a silent no-op. + /// Empty attribute set: `&[]` means "the series with no attributes". + /// + /// The default implementation does nothing. + fn remove_series(&self, _instrument_name: &str, _attributes: &[KeyValue]) {} } /// Provides the ability to create instruments for recording measurements or From 2ff042d03756275ff69b0c3f39e9959ad29f5442 Mon Sep 17 00:00:00 2001 From: QJ Yu Date: Tue, 1 Dec 2026 16:06:03 -0800 Subject: [PATCH 4/6] update --- .../src/metrics/meter_provider.rs | 4 +-- opentelemetry-sdk/src/metrics/mod.rs | 6 ++--- opentelemetry/src/metrics/meter.rs | 25 ++++++++++--------- 3 files changed, 17 insertions(+), 18 deletions(-) diff --git a/opentelemetry-sdk/src/metrics/meter_provider.rs b/opentelemetry-sdk/src/metrics/meter_provider.rs index ee6233b63e..e79477313f 100644 --- a/opentelemetry-sdk/src/metrics/meter_provider.rs +++ b/opentelemetry-sdk/src/metrics/meter_provider.rs @@ -1,7 +1,7 @@ use core::fmt; use opentelemetry::{ metrics::{Meter, MeterProvider}, - otel_debug, otel_error, otel_info, InstrumentationScope, KeyValue, + otel_debug, otel_error, otel_info, InstrumentationScope, }; use std::time::Duration; use std::{ @@ -189,8 +189,6 @@ impl Drop for SdkMeterProviderInner { } impl MeterProvider for SdkMeterProvider { - fn remove_series(&self, _instrument_name: &str, _attributes: &[KeyValue]) {} - fn meter(&self, name: &'static str) -> Meter { let scope = InstrumentationScope::builder(name).build(); self.meter_with_scope(scope) diff --git a/opentelemetry-sdk/src/metrics/mod.rs b/opentelemetry-sdk/src/metrics/mod.rs index 0e657a3b8e..9b3dcbc38d 100644 --- a/opentelemetry-sdk/src/metrics/mod.rs +++ b/opentelemetry-sdk/src/metrics/mod.rs @@ -348,7 +348,7 @@ mod tests { test_context.flush_metrics(); drop(stale_counter); - test_context.meter_provider.expire_series(stale_name, &[]); + test_context.meter().remove_series(stale_name, None, &[]); test_context.reset_metrics(); test_context.flush_metrics(); let resource_metrics = test_context @@ -385,8 +385,8 @@ mod tests { test_context.flush_metrics(); test_context - .meter_provider - .expire_series("subsystem_requests", &stale_attributes); + .meter() + .remove_series("subsystem_requests", None, &stale_attributes); test_context.reset_metrics(); test_context.flush_metrics(); let resource_metrics = test_context diff --git a/opentelemetry/src/metrics/meter.rs b/opentelemetry/src/metrics/meter.rs index 2539a1b237..d671662d10 100644 --- a/opentelemetry/src/metrics/meter.rs +++ b/opentelemetry/src/metrics/meter.rs @@ -61,18 +61,6 @@ pub trait MeterProvider { /// let meter = provider.meter_with_scope(scope); /// ``` fn meter_with_scope(&self, scope: InstrumentationScope) -> Meter; - - /// Requests that a metric series identified by its instrument name and - /// attributes no longer be exported from the collection. - /// - /// If the same attributes are recorded afterwards, it will start a new - /// series with a new start time. - /// - /// A non-existent instrument name or attribute set is a silent no-op. - /// Empty attribute set: `&[]` means "the series with no attributes". - /// - /// The default implementation does nothing. - fn remove_series(&self, _instrument_name: &str, _attributes: &[KeyValue]) {} } /// Provides the ability to create instruments for recording measurements or @@ -485,6 +473,19 @@ impl Meter { ) -> HistogramBuilder<'_, Histogram> { HistogramBuilder::new(self, name.into()) } + + + /// Requests that a metric series identified by its instrument name and + /// attributes no longer be exported from the collection. + /// + /// If the same attributes are recorded afterwards, it will start a new + /// series with a new start time. + /// + /// A non-existent instrument name or attribute set is a silent no-op. + /// Empty attribute set: `&[]` means "the series with no attributes". + /// + /// The default implementation does nothing. + pub fn remove_series(&self, _name: &str, _version: Option<&str>, _attributes: &[KeyValue]) {} } impl fmt::Debug for Meter { From 3b5be2307ca78b8b9b6e9da8db9e0ae40a532eb5 Mon Sep 17 00:00:00 2001 From: QJ Yu Date: Wed, 2 Dec 2026 15:13:35 -0800 Subject: [PATCH 5/6] [issue-3874] Wiring for remove series with instrument name and attribute set, and 2 tests for counter type. --- .../src/metrics/internal/aggregate.rs | 3 ++ .../metrics/internal/exponential_histogram.rs | 4 ++ .../src/metrics/internal/histogram.rs | 4 ++ .../src/metrics/internal/last_value.rs | 4 ++ opentelemetry-sdk/src/metrics/internal/mod.rs | 41 +++++++++++++++++++ .../src/metrics/internal/precomputed_sum.rs | 4 ++ opentelemetry-sdk/src/metrics/internal/sum.rs | 4 ++ opentelemetry-sdk/src/metrics/meter.rs | 7 +++- opentelemetry-sdk/src/metrics/mod.rs | 8 ++-- opentelemetry-sdk/src/metrics/pipeline.rs | 25 +++++++++++ opentelemetry/src/metrics/meter.rs | 19 ++++----- opentelemetry/src/metrics/mod.rs | 7 ++++ 12 files changed, 115 insertions(+), 15 deletions(-) diff --git a/opentelemetry-sdk/src/metrics/internal/aggregate.rs b/opentelemetry-sdk/src/metrics/internal/aggregate.rs index d4792f4e0a..714e85ac4d 100644 --- a/opentelemetry-sdk/src/metrics/internal/aggregate.rs +++ b/opentelemetry-sdk/src/metrics/internal/aggregate.rs @@ -63,6 +63,9 @@ pub(crate) trait ComputeAggregation: Send + Sync + 'static { /// returned option is expected to contain a new aggregation with the data from /// the current collection cycle. fn call(&self, dest: Option<&mut AggregatedMetrics>) -> (usize, Option); + + // Removes the series identified by `attributes`. The default does nothing. + fn remove(&self, _attributes: &[KeyValue]) {} } /// Separate `measure` and `collect` functions for an aggregate. diff --git a/opentelemetry-sdk/src/metrics/internal/exponential_histogram.rs b/opentelemetry-sdk/src/metrics/internal/exponential_histogram.rs index 7e825ff2d7..102328a3af 100644 --- a/opentelemetry-sdk/src/metrics/internal/exponential_histogram.rs +++ b/opentelemetry-sdk/src/metrics/internal/exponential_histogram.rs @@ -597,6 +597,10 @@ where }; (len, new.map(T::make_aggregated_metrics)) } + + fn remove(&self, attributes: &[KeyValue]) { + self.value_map.remove(attributes); + } } #[cfg(test)] diff --git a/opentelemetry-sdk/src/metrics/internal/histogram.rs b/opentelemetry-sdk/src/metrics/internal/histogram.rs index 02f49d46e8..2d80f6da2f 100644 --- a/opentelemetry-sdk/src/metrics/internal/histogram.rs +++ b/opentelemetry-sdk/src/metrics/internal/histogram.rs @@ -313,6 +313,10 @@ where }; (len, new.map(T::make_aggregated_metrics)) } + + fn remove(&self, attributes: &[KeyValue]) { + self.value_map.remove(attributes); + } } #[cfg(test)] diff --git a/opentelemetry-sdk/src/metrics/internal/last_value.rs b/opentelemetry-sdk/src/metrics/internal/last_value.rs index ff2b70cc75..1e1aaeecb0 100644 --- a/opentelemetry-sdk/src/metrics/internal/last_value.rs +++ b/opentelemetry-sdk/src/metrics/internal/last_value.rs @@ -214,6 +214,10 @@ where }; (len, new.map(T::make_aggregated_metrics)) } + + fn remove(&self, attributes: &[KeyValue]) { + self.value_map.remove(attributes); + } } #[cfg(test)] diff --git a/opentelemetry-sdk/src/metrics/internal/mod.rs b/opentelemetry-sdk/src/metrics/internal/mod.rs index c4cb7fab59..9b2def5fde 100644 --- a/opentelemetry-sdk/src/metrics/internal/mod.rs +++ b/opentelemetry-sdk/src/metrics/internal/mod.rs @@ -216,6 +216,47 @@ where } } + fn remove(&self, attributes: &[KeyValue]) -> bool { + if attributes.is_empty() { + let tracker = &self.no_attribute_tracker; + if tracker.bound_count.load(Ordering::Acquire) > 0 { + return false; // same policy as attributed series + } + let was_present = tracker.has_been_updated.swap(false, Ordering::AcqRel); + // clone_and_reset zeroes the live value and hands back the old one; we drop it. + let _old = tracker.aggregator.clone_and_reset(&self.config); + return was_present; + } + + let sorted = sort_and_dedup(attributes); + if sorted.as_slice() == stream_overflow_attributes() { + return false; // never remove the overflow series + } + + let Ok(mut trackers) = self.trackers.write() else { + return false; // poisoned lock; same policy as measure + }; + + // Same two lookups measure() does: as given, then sorted. + let Some(target) = trackers + .get(attributes) + .or_else(|| trackers.get(sorted.as_slice())) + .cloned() + else { + return false; // no such series: silent no-op + }; + + // A bound handle holds this tracker directly; deleting it would orphan the handle. + if target.bound_count.load(Ordering::Acquire) > 0 { + return false; + } + + // Remove EVERY key that points at this tracker (provided + sorted order). + trackers.retain(|_, t: &mut Arc>| !Arc::ptr_eq(t, &target)); + self.count.fetch_sub(1, Ordering::SeqCst); + true + } + /// Resolves attributes and returns a cached Arc for bound instruments. /// The caller can then call `tracker.aggregator.update()` directly, bypassing the /// full lookup path on subsequent measurements. diff --git a/opentelemetry-sdk/src/metrics/internal/precomputed_sum.rs b/opentelemetry-sdk/src/metrics/internal/precomputed_sum.rs index e1d6e1b865..d1632e2fa2 100644 --- a/opentelemetry-sdk/src/metrics/internal/precomputed_sum.rs +++ b/opentelemetry-sdk/src/metrics/internal/precomputed_sum.rs @@ -218,6 +218,10 @@ where }; (len, new.map(T::make_aggregated_metrics)) } + + fn remove(&self, attributes: &[KeyValue]) { + self.value_map.remove(attributes); + } } #[cfg(test)] diff --git a/opentelemetry-sdk/src/metrics/internal/sum.rs b/opentelemetry-sdk/src/metrics/internal/sum.rs index e13c502ed6..9c0dabc0e4 100644 --- a/opentelemetry-sdk/src/metrics/internal/sum.rs +++ b/opentelemetry-sdk/src/metrics/internal/sum.rs @@ -228,6 +228,10 @@ where }; (len, new.map(T::make_aggregated_metrics)) } + + fn remove(&self, attributes: &[KeyValue]) { + self.value_map.remove(attributes); + } } #[cfg(test)] diff --git a/opentelemetry-sdk/src/metrics/meter.rs b/opentelemetry-sdk/src/metrics/meter.rs index 34256faf7f..1bafb33bfa 100644 --- a/opentelemetry-sdk/src/metrics/meter.rs +++ b/opentelemetry-sdk/src/metrics/meter.rs @@ -8,7 +8,7 @@ use opentelemetry::{ InstrumentProvider, ObservableCounter, ObservableGauge, ObservableUpDownCounter, UpDownCounter, }, - otel_error, InstrumentationScope, + otel_error, InstrumentationScope, KeyValue, }; use crate::metrics::{ @@ -546,6 +546,11 @@ impl InstrumentProvider for SdkMeter { let resolver = InstrumentResolver::new(self, &self.u64_resolver); self.create_histogram(builder, &resolver) } + + fn remove_series(&self, name: &str, attributes: &[KeyValue]) { + // find the value map and remove things + self.pipes.remove_series(&self.scope, name, attributes); + } } fn validate_instrument_config(name: &str, unit: &Option>) -> MetricResult<()> { diff --git a/opentelemetry-sdk/src/metrics/mod.rs b/opentelemetry-sdk/src/metrics/mod.rs index 9b3dcbc38d..c9a805d3d2 100644 --- a/opentelemetry-sdk/src/metrics/mod.rs +++ b/opentelemetry-sdk/src/metrics/mod.rs @@ -336,7 +336,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] - async fn expired_series_are_not_collected() { + async fn removed_series_are_not_collected() { let test_context = TestContext::new(Temporality::Cumulative); let meter = test_context.meter(); let stale_name = "subsystem_stale_requests"; @@ -348,7 +348,7 @@ mod tests { test_context.flush_metrics(); drop(stale_counter); - test_context.meter().remove_series(stale_name, None, &[]); + test_context.meter().remove_series(stale_name, &[]); test_context.reset_metrics(); test_context.flush_metrics(); let resource_metrics = test_context @@ -372,7 +372,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] - async fn expired_series_are_not_queryable() { + async fn removed_series_are_not_queryable() { let test_context = TestContext::new(Temporality::Cumulative); let counter = test_context .meter() @@ -386,7 +386,7 @@ mod tests { test_context.flush_metrics(); test_context .meter() - .remove_series("subsystem_requests", None, &stale_attributes); + .remove_series("subsystem_requests", &stale_attributes); test_context.reset_metrics(); test_context.flush_metrics(); let resource_metrics = test_context diff --git a/opentelemetry-sdk/src/metrics/pipeline.rs b/opentelemetry-sdk/src/metrics/pipeline.rs index 0ed05f9e02..a942ed41a6 100644 --- a/opentelemetry-sdk/src/metrics/pipeline.rs +++ b/opentelemetry-sdk/src/metrics/pipeline.rs @@ -97,6 +97,19 @@ impl Pipeline { fn shutdown(&self) -> OTelSdkResult { self.reader.shutdown() } + + /// Removes the series for `attributes` from every instrument named `name` in `scope`. + fn remove_series(&self, scope: &InstrumentationScope, name: &str, attributes: &[KeyValue]) { + let Ok(inner) = self.inner.lock() else { + return; // poisoned lock: nothing sensible to do for a no-op-on-failure API + }; + let Some(syncs) = inner.aggregations.get(scope) else { + return; // no instruments for this scope: silent no-op, as documented + }; + for s in syncs.iter().filter(|s| s.name == name) { + s.comp_agg.remove(attributes); + } + } } impl SdkProducer for Pipeline { @@ -774,6 +787,18 @@ impl Pipelines { ))) } } + + /// Removes the series for `attributes` from every instrument named `name` in `scope`. + pub(crate) fn remove_series( + &self, + scope: &InstrumentationScope, + name: &str, + attributes: &[KeyValue], + ) { + for pipe in &self.0 { + pipe.remove_series(scope, name, attributes) + } + } } /// resolver facilitates resolving aggregate functions an instrument calls to diff --git a/opentelemetry/src/metrics/meter.rs b/opentelemetry/src/metrics/meter.rs index d671662d10..2434c5f285 100644 --- a/opentelemetry/src/metrics/meter.rs +++ b/opentelemetry/src/metrics/meter.rs @@ -474,18 +474,17 @@ impl Meter { HistogramBuilder::new(self, name.into()) } - - /// Requests that a metric series identified by its instrument name and - /// attributes no longer be exported from the collection. - /// - /// If the same attributes are recorded afterwards, it will start a new + /// Requests that a metric series identified by its instrument name, + /// and attributes no longer be exported from the collection. + /// + /// If the same attributes are recorded afterwards, it will start a new /// series with a new start time. - /// - /// A non-existent instrument name or attribute set is a silent no-op. - /// Empty attribute set: `&[]` means "the series with no attributes". /// - /// The default implementation does nothing. - pub fn remove_series(&self, _name: &str, _version: Option<&str>, _attributes: &[KeyValue]) {} + /// A non-existent instrument name or attribute set is a silent no-op. + /// Empty attribute set: `&[]` means "the series with no attributes". + pub fn remove_series(&self, name: &str, attributes: &[KeyValue]) { + self.instrument_provider.remove_series(name, attributes); + } } impl fmt::Debug for Meter { diff --git a/opentelemetry/src/metrics/mod.rs b/opentelemetry/src/metrics/mod.rs index 2c1ccefb01..6ed21adfe7 100644 --- a/opentelemetry/src/metrics/mod.rs +++ b/opentelemetry/src/metrics/mod.rs @@ -21,6 +21,8 @@ pub use instruments::{ pub use meter::{Meter, MeterProvider}; pub use noop::NoopMeterProvider; +use crate::KeyValue; + /// SDK implemented trait for creating instruments pub trait InstrumentProvider { /// creates an instrument for recording increasing values. @@ -129,4 +131,9 @@ pub trait InstrumentProvider { fn u64_histogram(&self, _builder: HistogramBuilder<'_, Histogram>) -> Histogram { Histogram::new(Arc::new(noop::NoopSyncInstrument::new())) } + + /// removes a metric series from being exported in the collection, + /// identified by its instrument name and attributes. + /// The default implementation does nothing. + fn remove_series(&self, _name: &str, _attributes: &[KeyValue]) {} } From 196c0e6509d59a4aee3bc16b0ed0eacd79cf089b Mon Sep 17 00:00:00 2001 From: QJ Yu Date: Thu, 3 Dec 2026 19:03:49 -0800 Subject: [PATCH 6/6] Parameterize tests. --- opentelemetry-sdk/CHANGELOG.md | 2 +- opentelemetry-sdk/src/metrics/mod.rs | 150 ++++++++++++++++----------- opentelemetry/CHANGELOG.md | 2 +- 3 files changed, 90 insertions(+), 64 deletions(-) diff --git a/opentelemetry-sdk/CHANGELOG.md b/opentelemetry-sdk/CHANGELOG.md index 60404b1312..94b2ae8c33 100644 --- a/opentelemetry-sdk/CHANGELOG.md +++ b/opentelemetry-sdk/CHANGELOG.md @@ -2,7 +2,7 @@ ## vNext -- Move the stub `expire_series` method to the API's `MeterProvider` trait. +- Move the stub `remove_series` method to the API's `MeterProvider` trait. - Improved metrics measurement performance by speeding up attribute set lookups (faster `KeyValue` equality and boxed attribute keys). ([#3787](https://github.com/open-telemetry/opentelemetry-rust/pull/3787)) diff --git a/opentelemetry-sdk/src/metrics/mod.rs b/opentelemetry-sdk/src/metrics/mod.rs index c9a805d3d2..5bb3c08795 100644 --- a/opentelemetry-sdk/src/metrics/mod.rs +++ b/opentelemetry-sdk/src/metrics/mod.rs @@ -127,6 +127,7 @@ mod tests { use self::data::{HistogramDataPoint, MetricData, ScopeMetrics, SumDataPoint}; use super::internal::Number; use super::*; + use crate::metrics::data::AggregatedMetrics; use crate::metrics::data::ResourceMetrics; use crate::metrics::internal::AggregatedMetricsAccess; use crate::metrics::InMemoryMetricExporter; @@ -335,84 +336,109 @@ mod tests { counter_aggregation_helper(Temporality::Cumulative); } - #[tokio::test(flavor = "multi_thread", worker_threads = 1)] - async fn removed_series_are_not_collected() { - let test_context = TestContext::new(Temporality::Cumulative); - let meter = test_context.meter(); - let stale_name = "subsystem_stale_requests"; - let live_name = "subsystem_live_requests"; - let stale_counter = meter.u64_counter(stale_name).build(); - let live_counter = meter.u64_counter(live_name).build(); - stale_counter.add(1, &[]); - live_counter.add(1, &[]); + type Recorder = Box; + + fn counter_recorder(meter: &Meter, name: &str) -> Recorder { + let c = meter.u64_counter(name.to_string()).build(); + Box::new(move |attrs| c.add(1, attrs)) + } + fn histogram_recorder(meter: &Meter, name: &str) -> Recorder { + let h = meter.f64_histogram(name.to_string()).build(); + Box::new(move |attrs| h.record(1.0, attrs)) + } + fn gauge_recorder(meter: &Meter, name: &str) -> Recorder { + let g = meter.i64_gauge(name.to_string()).build(); + Box::new(move |attrs| g.record(1, attrs)) + } + fn up_down_counter_recorder(meter: &Meter, name: &str) -> Recorder { + let c = meter.i64_up_down_counter(name.to_string()).build(); + Box::new(move |attrs| c.add(1, attrs)) + } + /// Attribute sets of every data point in `data`, whatever the data kind. + fn attribute_sets(data: &MetricData) -> Vec> { + match data { + MetricData::Gauge(g) => g + .data_points() + .map(|dp| dp.attributes().cloned().collect()) + .collect(), + MetricData::Sum(s) => s + .data_points() + .map(|dp| dp.attributes().cloned().collect()) + .collect(), + MetricData::Histogram(h) => h + .data_points() + .map(|dp| dp.attributes().cloned().collect()) + .collect(), + MetricData::ExponentialHistogram(e) => e + .data_points() + .map(|dp| dp.attributes().cloned().collect()) + .collect(), + } + } - test_context.flush_metrics(); - drop(stale_counter); - test_context.meter().remove_series(stale_name, &[]); - test_context.reset_metrics(); - test_context.flush_metrics(); - let resource_metrics = test_context + /// Same, for the type-erased `AggregatedMetrics`. + fn exported_attribute_sets(agg: &AggregatedMetrics) -> Vec> { + match agg { + AggregatedMetrics::F64(d) => attribute_sets(d), + AggregatedMetrics::U64(d) => attribute_sets(d), + AggregatedMetrics::I64(d) => attribute_sets(d), + } + } + + fn series_exported_for(test_context: &TestContext, name: &str) -> Vec> { + test_context .exporter .get_finished_metrics() - .expect("metrics expected to be exported"); - let metrics: Vec<_> = resource_metrics + .expect("metrics expected to be exported") .iter() .flat_map(|rm| &rm.scope_metrics) .flat_map(|sm| &sm.metrics) - .collect(); - - assert!( - !metrics.iter().any(|metric| metric.name == stale_name), - "expired series should no longer be collected" - ); - assert!( - metrics.iter().any(|metric| metric.name == live_name), - "expiration should not remove an unrelated live series" - ); + .filter(|m| m.name() == name) + .flat_map(|m| exported_attribute_sets(m.data())) + .collect() } - #[tokio::test(flavor = "multi_thread", worker_threads = 1)] - async fn removed_series_are_not_queryable() { + fn check_remove(make: fn(&Meter, &str) -> Recorder, to_remove: &[KeyValue]) { let test_context = TestContext::new(Temporality::Cumulative); - let counter = test_context - .meter() - .u64_counter("subsystem_requests") - .build(); - let stale_attributes = [KeyValue::new("subsystem", "stale")]; - let live_attributes = [KeyValue::new("subsystem", "live")]; - counter.add(1, &stale_attributes); - counter.add(1, &live_attributes); - + let record = make(&test_context.meter(), "subsystem_requests"); + let live = [KeyValue::new("subsystem", "live")]; + record(to_remove); + record(&live); test_context.flush_metrics(); + let before = series_exported_for(&test_context, "subsystem_requests"); + assert_eq!(before.len(), 2, "baseline: both series exported"); + assert!(before.contains(&to_remove.to_vec()), "baseline: target series exported"); test_context .meter() - .remove_series("subsystem_requests", &stale_attributes); + .remove_series("subsystem_requests", to_remove); test_context.reset_metrics(); test_context.flush_metrics(); - let resource_metrics = test_context - .exporter - .get_finished_metrics() - .expect("metrics expected to be exported"); - let metric = resource_metrics - .iter() - .flat_map(|rm| &rm.scope_metrics) - .flat_map(|sm| &sm.metrics) - .find(|metric| metric.name == "subsystem_requests") - .expect("live series should keep the metric collected"); - let MetricData::Sum(sum) = u64::extract_metrics_data_ref(&metric.data) - .expect("counter should use sum aggregation") - else { - unreachable!() - }; - + let after = series_exported_for(&test_context, "subsystem_requests"); assert!( - find_sum_datapoint_with_key_value(&sum.data_points, "subsystem", "stale").is_none(), - "query results should not include expired series" - ); - assert!( - find_sum_datapoint_with_key_value(&sum.data_points, "subsystem", "live").is_some(), - "query results should include the unexpired series" + !after.contains(&to_remove.to_vec()), + "removed series must not be exported" ); + assert!(after.contains(&live.to_vec()), "other series must survive"); + } + + #[rstest] + #[case::counter(counter_recorder)] + #[case::up_down_counter(up_down_counter_recorder)] + #[case::histogram(histogram_recorder)] + #[case::gauge(gauge_recorder)] + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn removed_attributed_series_is_not_collected(#[case] make: fn(&Meter, &str) -> Recorder) { + check_remove(make, &[KeyValue::new("subsystem", "stale")]); + } + + #[rstest] + #[case::counter(counter_recorder)] + #[case::up_down_counter(up_down_counter_recorder)] + #[case::histogram(histogram_recorder)] + #[case::gauge(gauge_recorder)] + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn removed_no_attribute_series_is_not_collected(#[case] make: fn(&Meter, &str) -> Recorder) { + check_remove(make, &[]); } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] diff --git a/opentelemetry/CHANGELOG.md b/opentelemetry/CHANGELOG.md index 12f3851c6f..64c9b2c363 100644 --- a/opentelemetry/CHANGELOG.md +++ b/opentelemetry/CHANGELOG.md @@ -2,7 +2,7 @@ ## vNext -- Add `MeterProvider::expire_series` for requesting expiration of a metric series. +- Add `MeterProvider::remove_series` for requesting expiration of a metric series. The default implementation does nothing. - Added `TraceFlags::RANDOM`, `TraceFlags::is_random`, `TraceFlags::with_random`, and `SpanContext::is_random` for the W3C Trace Context Level 2 `random-trace-id` flag