Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Metrics][POC] Use Weak instead of Arc in Counter to respect MeterProvider shutdown #2497

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
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
10 changes: 10 additions & 0 deletions opentelemetry-sdk/src/metrics/instrument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,20 @@ impl InstrumentId {
}
}

pub(crate) trait SyncInstrumentUpdate: Send + Sync {}

impl<T> SyncInstrumentUpdate for ResolvedMeasures<T> {}

pub(crate) struct ResolvedMeasures<T> {
pub(crate) measures: Vec<Arc<dyn Measure<T>>>,
}

impl<T: 'static> ResolvedMeasures<T> {
pub(crate) fn as_sync_instrument_update(self: Arc<Self>) -> Arc<dyn SyncInstrumentUpdate> {
self
}
}

impl<T: Copy + 'static> SyncInstrument<T> for ResolvedMeasures<T> {
fn measure(&self, val: T, attrs: &[KeyValue]) {
for measure in &self.measures {
Expand Down
21 changes: 17 additions & 4 deletions opentelemetry-sdk/src/metrics/meter.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use core::fmt;
use std::{borrow::Cow, sync::Arc};
use std::{
borrow::Cow,
sync::{Arc, Mutex},
};

use opentelemetry::{
metrics::{
Expand All @@ -11,7 +14,7 @@ use opentelemetry::{
};

use crate::metrics::{
instrument::{Instrument, InstrumentKind, Observable, ResolvedMeasures},
instrument::{Instrument, InstrumentKind, Observable, ResolvedMeasures, SyncInstrumentUpdate},
internal::{self, Number},
pipeline::{Pipelines, Resolver},
MetricError, MetricResult,
Expand Down Expand Up @@ -50,6 +53,7 @@ pub(crate) struct SdkMeter {
u64_resolver: Resolver<u64>,
i64_resolver: Resolver<i64>,
f64_resolver: Resolver<f64>,
pub(crate) sync_instruments: Mutex<Vec<Arc<dyn SyncInstrumentUpdate>>>,
}

impl SdkMeter {
Expand All @@ -62,6 +66,7 @@ impl SdkMeter {
u64_resolver: Resolver::new(Arc::clone(&pipes), Arc::clone(&view_cache)),
i64_resolver: Resolver::new(Arc::clone(&pipes), Arc::clone(&view_cache)),
f64_resolver: Resolver::new(pipes, view_cache),
sync_instruments: Mutex::new(Vec::new()),
}
}

Expand Down Expand Up @@ -93,8 +98,16 @@ impl SdkMeter {
builder.unit,
None,
)
.map(|i| Counter::new(Arc::new(i)))
{
.map(|i| {
let resolved_measures = Arc::new(i);
let sync_instrument_update = resolved_measures.clone().as_sync_instrument_update();

self.sync_instruments
.lock()
.unwrap()
.push(sync_instrument_update);
Counter::new(resolved_measures)
}) {
Ok(counter) => counter,
Err(err) => {
otel_error!(
Expand Down
4 changes: 4 additions & 0 deletions opentelemetry-sdk/src/metrics/meter_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ impl SdkMeterProviderInner {
"MeterProvider shutdown already invoked.".into(),
))
} else {
let mut meters = self.meters.lock().unwrap();
for (_, meter) in meters.drain() {
meter.sync_instruments.lock().unwrap().clear(); // Clear all `SyncInstrument` trait objects to avoid any further updates from instruments.
}
self.pipes.shutdown()
}
}
Expand Down
12 changes: 8 additions & 4 deletions opentelemetry/src/metrics/instruments/counter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::KeyValue;
use core::fmt;
use std::sync::Arc;
use std::sync::{Arc, Weak};

use super::SyncInstrument;

Expand All @@ -11,7 +11,7 @@ use super::SyncInstrument;
/// duplicate [`Counter`]s for the same metric could lower SDK performance.
#[derive(Clone)]
#[non_exhaustive]
pub struct Counter<T>(Arc<dyn SyncInstrument<T> + Send + Sync>);
pub struct Counter<T>(Weak<dyn SyncInstrument<T> + Send + Sync>);

impl<T> fmt::Debug for Counter<T>
where
Expand All @@ -25,12 +25,16 @@ where
impl<T> Counter<T> {
/// Create a new counter.
pub fn new(inner: Arc<dyn SyncInstrument<T> + Send + Sync>) -> Self {
Counter(inner)
Counter(Arc::downgrade(&inner))
}

/// Records an increment to the counter.
pub fn add(&self, value: T, attributes: &[KeyValue]) {
self.0.measure(value, attributes)
if let Some(inner) = self.0.upgrade() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how much is the perf cost for this upgrade as opposed to storing Arc itself?

Copy link
Contributor Author

@utpilla utpilla Jan 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a considerable perf cost. Check this #2442 (comment).

inner.measure(value, attributes);
} else {
// TODO: Log error
}
}
}

Expand Down
Loading