Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions opentelemetry-sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## vNext

- 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))
Expand Down
3 changes: 3 additions & 0 deletions opentelemetry-sdk/src/metrics/internal/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AggregatedMetrics>);

// Removes the series identified by `attributes`. The default does nothing.
fn remove(&self, _attributes: &[KeyValue]) {}
}

/// Separate `measure` and `collect` functions for an aggregate.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,10 @@ where
};
(len, new.map(T::make_aggregated_metrics))
}

fn remove(&self, attributes: &[KeyValue]) {
self.value_map.remove(attributes);
}
}

#[cfg(test)]
Expand Down
4 changes: 4 additions & 0 deletions opentelemetry-sdk/src/metrics/internal/histogram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,10 @@ where
};
(len, new.map(T::make_aggregated_metrics))
}

fn remove(&self, attributes: &[KeyValue]) {
self.value_map.remove(attributes);
}
}

#[cfg(test)]
Expand Down
4 changes: 4 additions & 0 deletions opentelemetry-sdk/src/metrics/internal/last_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ where
};
(len, new.map(T::make_aggregated_metrics))
}

fn remove(&self, attributes: &[KeyValue]) {
self.value_map.remove(attributes);
}
}

#[cfg(test)]
Expand Down
41 changes: 41 additions & 0 deletions opentelemetry-sdk/src/metrics/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TrackerEntry<A>>| !Arc::ptr_eq(t, &target));
self.count.fetch_sub(1, Ordering::SeqCst);
true
}

/// Resolves attributes and returns a cached Arc<TrackerEntry> for bound instruments.
/// The caller can then call `tracker.aggregator.update()` directly, bypassing the
/// full lookup path on subsequent measurements.
Expand Down
4 changes: 4 additions & 0 deletions opentelemetry-sdk/src/metrics/internal/precomputed_sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,10 @@ where
};
(len, new.map(T::make_aggregated_metrics))
}

fn remove(&self, attributes: &[KeyValue]) {
self.value_map.remove(attributes);
}
}

#[cfg(test)]
Expand Down
4 changes: 4 additions & 0 deletions opentelemetry-sdk/src/metrics/internal/sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,10 @@ where
};
(len, new.map(T::make_aggregated_metrics))
}

fn remove(&self, attributes: &[KeyValue]) {
self.value_map.remove(attributes);
}
}

#[cfg(test)]
Expand Down
7 changes: 6 additions & 1 deletion opentelemetry-sdk/src/metrics/meter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use opentelemetry::{
InstrumentProvider, ObservableCounter, ObservableGauge, ObservableUpDownCounter,
UpDownCounter,
},
otel_error, InstrumentationScope,
otel_error, InstrumentationScope, KeyValue,
};

use crate::metrics::{
Expand Down Expand Up @@ -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<Cow<'static, str>>) -> MetricResult<()> {
Expand Down
106 changes: 106 additions & 0 deletions opentelemetry-sdk/src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -335,6 +336,111 @@ mod tests {
counter_aggregation_helper(Temporality::Cumulative);
}

type Recorder = Box<dyn Fn(&[KeyValue])>;

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<T>(data: &MetricData<T>) -> Vec<Vec<KeyValue>> {
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(),
}
}

/// Same, for the type-erased `AggregatedMetrics`.
fn exported_attribute_sets(agg: &AggregatedMetrics) -> Vec<Vec<KeyValue>> {
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<Vec<KeyValue>> {
test_context
.exporter
.get_finished_metrics()
.expect("metrics expected to be exported")
.iter()
.flat_map(|rm| &rm.scope_metrics)
.flat_map(|sm| &sm.metrics)
.filter(|m| m.name() == name)
.flat_map(|m| exported_attribute_sets(m.data()))
.collect()
}

fn check_remove(make: fn(&Meter, &str) -> Recorder, to_remove: &[KeyValue]) {
let test_context = TestContext::new(Temporality::Cumulative);
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", to_remove);
test_context.reset_metrics();
test_context.flush_metrics();
let after = series_exported_for(&test_context, "subsystem_requests");
assert!(
!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)]
async fn counter_aggregation_no_attributes_cumulative() {
let mut test_context = TestContext::new(Temporality::Cumulative);
Expand Down
25 changes: 25 additions & 0 deletions opentelemetry-sdk/src/metrics/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions opentelemetry/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## vNext

- 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
([#3270](https://github.com/open-telemetry/opentelemetry-rust/issues/3270)).
Expand Down
13 changes: 13 additions & 0 deletions opentelemetry/src/metrics/meter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::metrics::{
ObservableGauge, ObservableUpDownCounter, UpDownCounter,
};
use crate::InstrumentationScope;
use crate::KeyValue;

use super::{Counter, Histogram, HistogramBuilder};

Expand Down Expand Up @@ -472,6 +473,18 @@ impl Meter {
) -> HistogramBuilder<'_, Histogram<u64>> {
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".
pub fn remove_series(&self, name: &str, attributes: &[KeyValue]) {
self.instrument_provider.remove_series(name, attributes);
}
}

impl fmt::Debug for Meter {
Expand Down
7 changes: 7 additions & 0 deletions opentelemetry/src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -129,4 +131,9 @@ pub trait InstrumentProvider {
fn u64_histogram(&self, _builder: HistogramBuilder<'_, Histogram<u64>>) -> Histogram<u64> {
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]) {}
}