Skip to main content

confluent_kafka/common/metrics/stats/
sampled_stat.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A scalar value measured over one or more sampling windows
16//! (`org.apache.kafka.common.metrics.stats.SampledStat`).
17
18use std::sync::Mutex;
19
20use crate::common::config::config_def::java_double_to_string;
21use crate::common::metrics::{Measurable, MetricConfig, Stat};
22
23/// The per-subclass behaviour of a [`SampledStat`].
24///
25/// Java's `SampledStat` is abstract with `update`/`combine` provided by each
26/// subclass and an `initialValue` passed to the constructor. We model those
27/// abstract methods as this trait object held by the concrete `SampledStat`
28/// struct, plus the `initial_value` stored on the struct. `newSample` is NOT
29/// virtual in Java, so it stays on `SampledStat` itself.
30// selects the SampledStat subclass, which Rust models as one struct
31#[doc(alias = "rust-only")]
32pub trait SampledStatKind: Send + Sync {
33    /// Update the current sample with the recorded value (Java `update`).
34    ///
35    /// # Arguments
36    ///
37    /// - `sample` - the current sample
38    /// - `config` - the metric's configuration
39    /// - `value` - the recorded value
40    /// - `time_ms` - the POSIX time in milliseconds of the recording
41    fn update(&self, sample: &mut Sample, config: &MetricConfig, value: f64, time_ms: i64);
42
43    /// Combine all samples into a single measurement (Java `combine`).
44    ///
45    /// # Arguments
46    ///
47    /// - `samples` - the samples to combine
48    /// - `config` - the metric's configuration
49    /// - `now` - the current POSIX time in milliseconds
50    ///
51    /// # Returns
52    ///
53    /// The measurement.
54    fn combine(&self, samples: &[Sample], config: &MetricConfig, now: i64) -> f64;
55
56    /// Returns whether this is a `WindowedCount` (counts invocations rather than
57    /// summing values). Used by [`crate::common::metrics::stats::Meter`] to decide
58    /// whether the total records `1.0`, mirroring Java's
59    /// `rate.stat instanceof WindowedCount` check. Defaults to `false`; only
60    /// `WindowedCount` overrides it.
61    fn is_windowed_count(&self) -> bool {
62        false
63    }
64
65    /// Returns whether this is a `WindowedSum` (or a subclass of it). `Meter` only
66    /// supports a `WindowedSum`/`WindowedCount` rate stat, mirroring Java's
67    /// `instanceof WindowedSum` guard. Defaults to `false`.
68    fn is_windowed_sum(&self) -> bool {
69        false
70    }
71}
72
73/// A `SampledStat` records a single scalar value measured over one or more
74/// samples. Each sample is recorded over a configurable window. The window can
75/// be defined by number of events or elapsed time (or both, if both are given
76/// the window is complete when *either* the event count or elapsed time
77/// criterion is met).
78///
79/// All the samples are combined to produce the measurement. When a window is
80/// complete the oldest sample is cleared and recycled to begin recording the
81/// next sample.
82///
83#[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat")]
84// The mutable sample ring + cursor are guarded by a single `Mutex` mirroring
85// Java's sensor `synchronized`. This lock is taken per-fetch / per-partition,
86// never per-record on the hot path.
87pub struct SampledStat {
88    initial_value: f64,
89    kind: Box<dyn SampledStatKind>,
90    inner: Mutex<SampledStatInner>,
91}
92
93struct SampledStatInner {
94    current: usize,
95    time_window_ms: i64,
96    samples: Vec<Sample>,
97}
98
99impl SampledStat {
100    /// Create a `SampledStat` with the given initial value and per-subclass
101    /// behaviour.
102    ///
103    /// # Arguments
104    ///
105    /// - `initial_value` - the value a sample starts from
106    /// - `kind` - the subclass behaviour: `update` and `combine`
107    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat#SampledStat")]
108    pub fn new(initial_value: f64, kind: Box<dyn SampledStatKind>) -> Self {
109        Self {
110            initial_value,
111            kind,
112            inner: Mutex::new(SampledStatInner {
113                current: 0,
114                time_window_ms: -1,
115                // keep one extra placeholder for "overlapping sample" (see
116                // purge_obsolete_samples() logic)
117                samples: Vec::with_capacity((crate::common::metrics::MetricConfig::DEFAULT_NUM_SAMPLES + 1) as usize),
118            }),
119        }
120    }
121
122    /// Whether the underlying kind is a `WindowedCount` (see
123    /// [`SampledStatKind::is_windowed_count`]).
124    pub(crate) fn is_windowed_count(&self) -> bool {
125        self.kind.is_windowed_count()
126    }
127
128    /// Whether the underlying kind is a `WindowedSum` (see
129    /// [`SampledStatKind::is_windowed_sum`]).
130    pub(crate) fn is_windowed_sum(&self) -> bool {
131        self.kind.is_windowed_sum()
132    }
133
134    /// Allow configuring the time window for this sampled stat (Java
135    /// `withTimeWindow(long window, TimeUnit unit)`; the conversion to ms is done
136    /// by the caller, mirroring `Rate`'s use of `withTimeWindow`).
137    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat#SampledStat")]
138    pub(crate) fn with_time_window_ms(&self, window_ms: i64) {
139        self.inner.lock().expect("sampled stat mutex poisoned").time_window_ms = window_ms;
140    }
141
142    /// Purge any samples that lack observed events within the monitored window.
143    ///
144    /// Public so `Rate::window_size` can purge before computing the window size,
145    /// matching Java's `protected` visibility used by `Rate`.
146    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat#purgeObsoleteSamples")]
147    pub(crate) fn purge_obsolete_samples(&self, config: &MetricConfig, now: i64) {
148        let mut inner = self.inner.lock().expect("sampled stat mutex poisoned");
149        Self::purge_obsolete_samples_locked(&mut inner, self.initial_value, config, now);
150    }
151
152    /// The start time of the oldest non-purged sample (Java `oldest(now)`),
153    /// used by `Rate::window_size`.
154    pub(crate) fn oldest_start_time_ms(&self, now: i64) -> i64 {
155        let mut inner = self.inner.lock().expect("sampled stat mutex poisoned");
156        Self::oldest_locked(&mut inner, self.initial_value, now).start_time_ms
157    }
158
159    // ---- internal helpers operating on a locked inner ----
160
161    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat#newSample")]
162    fn new_sample(initial_value: f64, time_window_ms: i64, time_ms: i64) -> Sample {
163        if time_window_ms > 0 {
164            Sample::with_time_window_ms(initial_value, time_ms, time_window_ms)
165        } else {
166            Sample::new(initial_value, time_ms)
167        }
168    }
169
170    fn current_locked(inner: &mut SampledStatInner, initial_value: f64, time_ms: i64) -> &mut Sample {
171        if inner.samples.is_empty() {
172            let s = Self::new_sample(initial_value, inner.time_window_ms, time_ms);
173            inner.samples.push(s);
174        }
175        let idx = inner.current;
176        &mut inner.samples[idx]
177    }
178
179    fn oldest_locked(inner: &mut SampledStatInner, initial_value: f64, now: i64) -> &Sample {
180        if inner.samples.is_empty() {
181            let s = Self::new_sample(initial_value, inner.time_window_ms, now);
182            inner.samples.push(s);
183        }
184        let mut oldest = 0usize;
185        for i in 1..inner.samples.len() {
186            if inner.samples[i].start_time_ms < inner.samples[oldest].start_time_ms {
187                oldest = i;
188            }
189        }
190        &inner.samples[oldest]
191    }
192
193    fn advance_locked(inner: &mut SampledStatInner, initial_value: f64, config: &MetricConfig, time_ms: i64) -> usize {
194        // keep one extra placeholder for "overlapping sample" (see
195        // purge_obsolete_samples() logic). Java's `int` arithmetic wraps, so the
196        // time and count arithmetic here and below wraps too rather than
197        // panicking under overflow checks on extreme caller-given values.
198        let max_samples = config.samples().wrapping_add(1) as usize;
199        inner.current = (inner.current + 1) % max_samples;
200        if inner.current >= inner.samples.len() {
201            let s = Self::new_sample(initial_value, inner.time_window_ms, time_ms);
202            inner.samples.push(s);
203        } else {
204            let idx = inner.current;
205            inner.samples[idx].reset(time_ms);
206        }
207        inner.current
208    }
209
210    fn purge_obsolete_samples_locked(
211        inner: &mut SampledStatInner,
212        initial_value: f64,
213        config: &MetricConfig,
214        now: i64,
215    ) {
216        let window_ms = if inner.time_window_ms > 0 {
217            inner.time_window_ms
218        } else {
219            config.time_window_ms()
220        };
221        let expire_age = (config.samples() as i64).wrapping_mul(window_ms);
222        for sample in inner.samples.iter_mut() {
223            // samples overlapping the monitored window are kept, even if they
224            // started before it
225            if now.wrapping_sub(sample.last_event_ms) >= expire_age {
226                sample.reset_to(initial_value, now);
227            }
228        }
229    }
230}
231
232impl Stat for SampledStat {
233    fn record(&self, config: &MetricConfig, value: f64, time_ms: i64) {
234        let mut inner = self.inner.lock().expect("sampled stat mutex poisoned");
235        let initial_value = self.initial_value;
236        // Select the current sample, advancing to a fresh one if complete.
237        let is_complete = {
238            let sample = Self::current_locked(&mut inner, initial_value, time_ms);
239            sample.is_complete(time_ms, config)
240        };
241        let idx = if is_complete {
242            Self::advance_locked(&mut inner, initial_value, config, time_ms)
243        } else {
244            inner.current
245        };
246        let sample = &mut inner.samples[idx];
247        self.kind.update(sample, config, value, time_ms);
248        sample.event_count += 1;
249        sample.last_event_ms = time_ms;
250    }
251}
252
253impl Measurable for SampledStat {
254    fn measure(&self, config: &MetricConfig, now: i64) -> f64 {
255        let mut inner = self.inner.lock().expect("sampled stat mutex poisoned");
256        Self::purge_obsolete_samples_locked(&mut inner, self.initial_value, config, now);
257        self.kind.combine(&inner.samples, config, now)
258    }
259}
260
261/// A single sample within a [`SampledStat`].
262///
263/// Mirrors `SampledStat.Sample`. Java exposes the fields publicly to
264/// `SampledStat` subclasses; here a [`SampledStatKind`] implementation reads
265/// them through getters and writes the ones Java's stats write through setters.
266#[derive(Clone, Debug)]
267#[non_exhaustive]
268#[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample")]
269pub struct Sample {
270    /// The initial (reset) value of this sample.
271    pub(crate) initial_value: f64,
272    /// The number of events recorded into this sample.
273    pub(crate) event_count: i64,
274    /// The time the sample started.
275    pub(crate) start_time_ms: i64,
276    /// The time of the last event recorded into the sample.
277    pub(crate) last_event_ms: i64,
278    /// The accumulated value of the sample.
279    pub(crate) value: f64,
280    /// The per-sample time window (or `-1` to use the config's window).
281    pub(crate) time_window_ms: i64,
282}
283
284impl Sample {
285    /// Create a sample with no explicit time window.
286    ///
287    /// # Arguments
288    ///
289    /// - `initial_value` - the value the sample starts from
290    /// - `now` - the start time of the sample, in milliseconds
291    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#Sample")]
292    pub fn new(initial_value: f64, now: i64) -> Self {
293        Self {
294            initial_value,
295            event_count: 0,
296            start_time_ms: now,
297            last_event_ms: now,
298            value: initial_value,
299            time_window_ms: -1,
300        }
301    }
302
303    /// Create a sample with an explicit time window.
304    ///
305    /// # Arguments
306    ///
307    /// - `initial_value` - the value the sample starts from
308    /// - `now` - the start time of the sample, in milliseconds
309    /// - `time_window_ms` - the sample's time window, or `-1` for the config's
310    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#Sample")]
311    pub fn with_time_window_ms(initial_value: f64, now: i64, time_window_ms: i64) -> Self {
312        Self {
313            initial_value,
314            event_count: 0,
315            start_time_ms: now,
316            last_event_ms: now,
317            value: initial_value,
318            time_window_ms,
319        }
320    }
321
322    /// Reset the sample for reuse at `now`, keeping its configured initial value.
323    ///
324    /// # Arguments
325    ///
326    /// - `now` - the new start time of the sample, in milliseconds
327    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#reset")]
328    pub fn reset(&mut self, now: i64) {
329        self.event_count = 0;
330        self.start_time_ms = now;
331        self.last_event_ms = now;
332        self.value = self.initial_value;
333    }
334
335    /// Reset the sample to a given initial value at `now`.
336    ///
337    /// Java's `reset(now)` resets to the sample's stored `initialValue`; the
338    /// `SampledStat`'s own `initialValue` always equals it, so passing it
339    /// explicitly here keeps the two in lock-step.
340    fn reset_to(&mut self, initial_value: f64, now: i64) {
341        self.initial_value = initial_value;
342        self.reset(now);
343    }
344
345    /// Returns whether this sample's window is complete at `time_ms`.
346    ///
347    /// # Arguments
348    ///
349    /// - `time_ms` - the current POSIX time in milliseconds
350    /// - `config` - the metric's configuration, giving the event and time windows
351    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#isComplete")]
352    pub fn is_complete(&self, time_ms: i64, config: &MetricConfig) -> bool {
353        let window_ms = if self.time_window_ms > 0 {
354            self.time_window_ms
355        } else {
356            config.time_window_ms()
357        };
358        time_ms.wrapping_sub(self.start_time_ms) >= window_ms || self.event_count >= config.event_window()
359    }
360
361    /// Returns the initial (reset) value of this sample.
362    ///
363    /// Java's public `Sample.initialValue`.
364    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#initialValue")]
365    pub fn initial_value(&self) -> f64 {
366        self.initial_value
367    }
368
369    /// Returns the number of events recorded into this sample.
370    ///
371    /// Java's public `Sample.eventCount`.
372    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#eventCount")]
373    pub fn event_count(&self) -> i64 {
374        self.event_count
375    }
376
377    /// Returns the time the sample started.
378    ///
379    /// Java's public `Sample.startTimeMs`.
380    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#startTimeMs")]
381    pub fn start_time_ms(&self) -> i64 {
382        self.start_time_ms
383    }
384
385    /// Returns the time of the last event recorded into the sample.
386    ///
387    /// Java's public `Sample.lastEventMs`.
388    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#lastEventMs")]
389    pub fn last_event_ms(&self) -> i64 {
390        self.last_event_ms
391    }
392
393    /// Returns the accumulated value of the sample.
394    ///
395    /// Java's public `Sample.value`.
396    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#value")]
397    pub fn value(&self) -> f64 {
398        self.value
399    }
400
401    /// Returns the per-sample time window (or `-1` to use the config's window).
402    ///
403    /// Java's public `Sample.timeWindowMs`.
404    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#timeWindowMs")]
405    pub fn time_window_ms(&self) -> i64 {
406        self.time_window_ms
407    }
408
409    /// Sets the number of events recorded into this sample, as Java's
410    /// `SampledStat.record` does through the public `Sample.eventCount`.
411    ///
412    /// # Arguments
413    ///
414    /// - `event_count` - the number of events
415    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#eventCount")]
416    pub fn set_event_count(&mut self, event_count: i64) {
417        self.event_count = event_count;
418    }
419
420    /// Sets the time of the last event recorded into the sample, as Java's
421    /// `SampledStat.record` does through the public `Sample.lastEventMs`.
422    ///
423    /// # Arguments
424    ///
425    /// - `last_event_ms` - the time of the last event, in milliseconds
426    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#lastEventMs")]
427    pub fn set_last_event_ms(&mut self, last_event_ms: i64) {
428        self.last_event_ms = last_event_ms;
429    }
430
431    /// Sets the accumulated value of the sample, as Java's `Avg`, `Max`, `Min`
432    /// and `WindowedSum` do through the public `Sample.value`.
433    ///
434    /// # Arguments
435    ///
436    /// - `value` - the accumulated value
437    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStat$Sample#value")]
438    pub fn set_value(&mut self, value: f64) {
439        self.value = value;
440    }
441}
442
443impl std::fmt::Debug for SampledStat {
444    // The fields Java's `toString()` prints; the stat's kind is a trait object.
445    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446        let inner = self.inner.lock().expect("sampled stat mutex poisoned");
447        f.debug_struct("SampledStat")
448            .field("initial_value", &self.initial_value)
449            .field("current", &inner.current)
450            .field("samples", &inner.samples)
451            .finish_non_exhaustive()
452    }
453}
454
455impl std::fmt::Display for SampledStat {
456    /// Java's `SampledStat.toString()`, which `Avg`, `Max`, `Min`,
457    /// `WindowedCount` and `WindowedSum` inherit: the samples print as Java's
458    /// `List.toString()` and the doubles as Java's `Double.toString`.
459    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
460        let inner = self.inner.lock().expect("sampled stat mutex poisoned");
461        let samples = inner.samples.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
462        write!(
463            f,
464            "SampledStat(initialValue={}, current={}, samples=[{}])",
465            java_double_to_string(self.initial_value),
466            inner.current,
467            samples
468        )
469    }
470}
471
472impl std::fmt::Display for Sample {
473    /// Java's `Sample.toString()`, the doubles as Java's `Double.toString`.
474    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
475        write!(
476            f,
477            "Sample(value={}, eventCount={}, startTimeMs={}, lastEventMs={}, initialValue={}, timeWindowMs={})",
478            java_double_to_string(self.value),
479            self.event_count,
480            self.start_time_ms,
481            self.last_event_ms,
482            java_double_to_string(self.initial_value),
483            self.time_window_ms
484        )
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    #[test]
493    fn to_string_follows_java() {
494        assert_eq!(
495            Sample::with_time_window_ms(0.0, 5, 30).to_string(),
496            "Sample(value=0.0, eventCount=0, startTimeMs=5, lastEventMs=5, initialValue=0.0, timeWindowMs=30)"
497        );
498        let avg = Avg::new();
499        assert_eq!(avg.to_string(), "SampledStat(initialValue=0.0, current=0, samples=[])");
500        avg.record(&MetricConfig::new(), 2.5, 7);
501        assert_eq!(
502            avg.to_string(),
503            "SampledStat(initialValue=0.0, current=0, samples=[Sample(value=2.5, eventCount=1, startTimeMs=7, \
504             lastEventMs=7, initialValue=0.0, timeWindowMs=-1)])"
505        );
506    }
507    use crate::common::metrics::TimeUnit;
508    use crate::common::metrics::stats::{Avg, Max, Min, WindowedCount, WindowedSum};
509    use crate::common::metrics::{Measurable, Stat};
510    use crate::common::utils::MockTime;
511    use crate::common::utils::Time;
512    use std::sync::Arc;
513
514    // A SampledStat whose measure() returns the number of samples (sum of
515    // per-sample value where each sample's value is set to 1). Mirrors
516    // SampledStatTest.SampleCount.
517    struct SampleCountKind;
518    impl SampledStatKind for SampleCountKind {
519        fn update(&self, sample: &mut Sample, _config: &MetricConfig, _value: f64, _time_ms: i64) {
520            sample.value = 1.0;
521        }
522        fn combine(&self, samples: &[Sample], _config: &MetricConfig, _now: i64) -> f64 {
523            samples.iter().map(|s| s.value).sum()
524        }
525    }
526    fn sample_count() -> SampledStat {
527        SampledStat::new(0.0, Box::new(SampleCountKind))
528    }
529
530    // Creates a sample with events at the start and at the end. Positions clock
531    // at the end. Mirrors SampledStatTest.completeSample.
532    fn complete_sample(stat: &SampledStat, config: &MetricConfig, time: &MockTime) {
533        stat.record(config, 1.0, time.milliseconds());
534        time.sleep(config.time_window_ms() - 1);
535        stat.record(config, 1.0, time.milliseconds());
536        time.sleep(1);
537    }
538
539    /// Extreme caller-given times and sample counts wrap as Java's `long` and
540    /// `int` arithmetic does instead of panicking (they reach here from C
541    /// through `kafka_common_metrics_Sensor_record_with_value_time_ms`
542    /// and `kafka_common_metrics_MetricConfig_set_samples`). No Java
543    /// counterpart.
544    #[test]
545    fn extreme_times_and_sample_counts_wrap_instead_of_panicking() {
546        let config = MetricConfig::new().set_samples(i32::MAX);
547        let stat = sample_count();
548        for time_ms in [1, i64::MIN, i64::MAX, i64::MIN, 0] {
549            stat.record(&config, 1.0, time_ms);
550        }
551        let _ = stat.measure(&config, i64::MIN);
552        let _ = stat.measure(&config, i64::MAX);
553
554        let config = MetricConfig::new().set_time_window(i64::MAX, TimeUnit::Days).set_samples(3);
555        let stat = sample_count();
556        stat.record(&config, 1.0, i64::MAX);
557        let _ = stat.measure(&config, i64::MIN);
558    }
559
560    // SampledStatTest.testSampleIsPurgedIfDoesntOverlap
561    #[test]
562    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStatTest#testSampleIsPurgedIfDoesntOverlap")]
563    fn test_sample_is_purged_if_doesnt_overlap() {
564        let config = MetricConfig::new().set_time_window(1, TimeUnit::Seconds).set_samples(2);
565        let stat = sample_count();
566        let time = MockTime::new();
567
568        complete_sample(&stat, &config, &time);
569        time.sleep(2500);
570
571        let num_samples = stat.measure(&config, time.milliseconds());
572        assert_eq!(0.0, num_samples, "Sample should be purged if doesn't overlap the window");
573    }
574
575    // SampledStatTest.testSampleIsKeptIfOverlaps
576    #[test]
577    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStatTest#testSampleIsKeptIfOverlaps")]
578    fn test_sample_is_kept_if_overlaps() {
579        let config = MetricConfig::new().set_time_window(1, TimeUnit::Seconds).set_samples(2);
580        let stat = sample_count();
581        let time = MockTime::new();
582
583        complete_sample(&stat, &config, &time);
584        time.sleep(1500);
585
586        let num_samples = stat.measure(&config, time.milliseconds());
587        assert_eq!(1.0, num_samples, "Sample should be kept if overlaps the window");
588    }
589
590    // SampledStatTest.testSampleIsKeptIfOverlapsAndExtra
591    #[test]
592    #[doc(alias = "org.apache.kafka.common.metrics.stats.SampledStatTest#testSampleIsKeptIfOverlapsAndExtra")]
593    fn test_sample_is_kept_if_overlaps_and_extra() {
594        let config = MetricConfig::new().set_time_window(1, TimeUnit::Seconds).set_samples(2);
595        let stat = sample_count();
596        let time = MockTime::new();
597
598        complete_sample(&stat, &config, &time);
599        time.sleep(100);
600        complete_sample(&stat, &config, &time);
601        time.sleep(100);
602        stat.record(&config, 1.0, time.milliseconds());
603
604        let num_samples = stat.measure(&config, time.milliseconds());
605        assert_eq!(3.0, num_samples, "Sample should be kept if overlaps the window and is n+1");
606    }
607
608    // MetricsTest.testSampledStatReturnsNaNWhenNoValuesExist
609    #[test]
610    fn test_sampled_stat_returns_nan_when_no_values_exist() {
611        let max = Max::new();
612        let min = Min::new();
613        let avg = Avg::new();
614        let window_ms = 100i64;
615        let samples = 2;
616        let config = MetricConfig::new()
617            .set_time_window(window_ms, TimeUnit::Milliseconds)
618            .set_samples(samples);
619        let time = MockTime::new();
620
621        max.record(&config, 50.0, time.milliseconds());
622        min.record(&config, 50.0, time.milliseconds());
623        avg.record(&config, 50.0, time.milliseconds());
624
625        time.sleep(samples as i64 * window_ms);
626
627        assert!(max.measure(&config, time.milliseconds()).is_nan());
628        assert!(min.measure(&config, time.milliseconds()).is_nan());
629        assert!(avg.measure(&config, time.milliseconds()).is_nan());
630    }
631
632    // MetricsTest.testSampledStatReturnsInitialValueWhenNoValuesExist
633    #[test]
634    fn test_sampled_stat_returns_initial_value_when_no_values_exist() {
635        let count = WindowedCount::new();
636        let sampled_total = WindowedSum::new();
637        let window_ms = 100i64;
638        let samples = 2;
639        let config = MetricConfig::new()
640            .set_time_window(window_ms, TimeUnit::Milliseconds)
641            .set_samples(samples);
642        let time = MockTime::new();
643
644        count.record(&config, 50.0, time.milliseconds());
645        sampled_total.record(&config, 50.0, time.milliseconds());
646
647        time.sleep(samples as i64 * window_ms);
648
649        assert_eq!(0.0, count.measure(&config, time.milliseconds()));
650        assert_eq!(0.0, sampled_total.measure(&config, time.milliseconds()));
651    }
652
653    // Sanity: the Arc<dyn Measurable> view shares state with the recording stat.
654    #[test]
655    fn shared_arc_reflects_records() {
656        let config = MetricConfig::new();
657        let stat = Arc::new(WindowedSum::new());
658        let view: Arc<dyn Measurable> = Arc::clone(&stat) as Arc<dyn Measurable>;
659        stat.record(&config, 3.0, 0);
660        assert_eq!(view.measure(&config, 0), 3.0);
661    }
662}