-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathopentelemetry_metric.rs
More file actions
1275 lines (1168 loc) · 51.6 KB
/
opentelemetry_metric.rs
File metadata and controls
1275 lines (1168 loc) · 51.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! OpenTelemetry OTLP metric payload.
//!
//! [Specification](https://opentelemetry.io/docs/reference/specification/protocol/otlp/),
//! [data model](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md)
//!
//! This format is valid for OTLP/gRPC and binary OTLP/HTTP messages. The
//! experimental JSON OTLP/HTTP format can also be supported but is not
//! currently implemented.
// Alright, to summarize this payload generator's understanding of the
// data-model described above:
//
// The central concern is a `Metric`. A `Metric` is:
//
// * name: String -- unique metric identifier
// * description: String -- optional human friendly description
// * unit: String -- unit of measurement, described by http://unitsofmeasure.org/ucum.html
// * data: enum { Gauge, Sum, Histogram, ExponentialHistogram, Summary }
//
// Each `Metric` is associated with a `Resource` -- called `ResourceMetrics` in
// the proto -- which defines the origination point of the `Metric`. Interior to
// the `Resource` is the `Scope` -- called `ScopeMetrics` in the proto -- which
// defines the library/smaller-than-resource scope that generated the
// `Metric`. We will not set `Scope` until we find out that it's important to do
// so for modeling purposes.
//
// The data types are as follows:
//
// * Gauge -- a collection of `NumberDataPoint`, values sampled at specific times
// * Sum -- `Gauge` with the addition of monotonic flag, aggregation metadata
//
// We omit Histogram / ExponentialHistogram / Summary in this current version
// but will introduce them in the near-term. The `NumberDataPoint` is a
//
// * attributes: Vec<KeyValue> -- tags
// * start_time_unix_nano: u64 -- represents the first possible moment a measurement could be recorded, optional
// * time_unix_nano: u64 -- a timestamp when the value was sampled
// * value: enum { u64, f64 } -- the value
// * flags: uu32 -- I'm not sure what to make of this yet
pub(crate) mod tags;
pub(crate) mod templates;
pub(crate) mod unit;
use std::rc::Rc;
use std::{cell::RefCell, io::Write};
use crate::SizedGenerator;
use crate::{Error, common::config::ConfRange, common::strings};
use bytes::BytesMut;
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
use opentelemetry_proto::tonic::metrics::v1::metric::Data;
use opentelemetry_proto::tonic::metrics::v1::{self, number_data_point};
use prost::Message;
use serde::{Deserialize, Serialize as SerdeSerialize};
use templates::{Pool, PoolError, ResourceTemplateGenerator};
use tracing::{debug, error};
use unit::UnitGenerator;
// smallest useful protobuf, determined by experimentation and enforced in
// smallest_protobuf test
const SMALLEST_PROTOBUF: usize = 31;
/// Increment timestamps by 100 milliseconds (in nanoseconds) per tick
const TIME_INCREMENT_NANOS: u64 = 1_000_000;
/// Configure the OpenTelemetry metric payload.
#[derive(Debug, Deserialize, SerdeSerialize, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[serde(deny_unknown_fields, default)]
/// OpenTelemetry metric contexts
pub struct Contexts {
/// The range of contexts -- see documentation for `context_id` function --
/// that will be generated.
pub total_contexts: ConfRange<u32>,
/// The range of attributes for resources.
pub attributes_per_resource: ConfRange<u8>,
/// The range of scopes that will be generated per resource.
pub scopes_per_resource: ConfRange<u8>,
/// The range of attributes for each scope.
pub attributes_per_scope: ConfRange<u8>,
/// The range of metrics that will be generated per scope.
pub metrics_per_scope: ConfRange<u8>,
/// The range of attributes for each metric.
pub attributes_per_metric: ConfRange<u8>,
}
impl Default for Contexts {
fn default() -> Self {
Self {
total_contexts: ConfRange::Constant(100),
attributes_per_resource: ConfRange::Inclusive { min: 1, max: 20 },
scopes_per_resource: ConfRange::Inclusive { min: 1, max: 20 },
attributes_per_scope: ConfRange::Constant(0),
metrics_per_scope: ConfRange::Inclusive { min: 1, max: 20 },
attributes_per_metric: ConfRange::Inclusive { min: 0, max: 10 },
}
}
}
/// Defines the relative probability of each kind of OpenTelemetry metric.
#[derive(Debug, Deserialize, SerdeSerialize, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[serde(deny_unknown_fields, default)]
pub struct MetricWeights {
/// The relative probability of generating a gauge metric.
pub gauge: u8,
/// The relative probability of generating a sum metric.
pub sum: u8,
}
impl Default for MetricWeights {
fn default() -> Self {
Self {
gauge: 50, // 50%
sum: 50, // 50%
}
}
}
/// Configure the OpenTelemetry metric payload.
#[derive(Debug, Default, Deserialize, SerdeSerialize, Clone, PartialEq, Copy)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[serde(deny_unknown_fields, default)]
pub struct Config {
/// Defines the relative probability of each kind of OpenTelemetry metric.
pub metric_weights: MetricWeights,
/// Define the contexts available when generating metrics
pub contexts: Contexts,
}
impl Config {
/// Determine whether the passed configuration obeys validation criteria.
///
/// # Errors
/// Function will error if the configuration is invalid
pub fn valid(&self) -> Result<(), String> {
// Validate metric weights - both types must have non-zero probability to ensure
// we can generate a diverse set of metrics
if self.metric_weights.gauge == 0 || self.metric_weights.sum == 0 {
return Err("Metric weights cannot be 0".to_string());
}
// Validate total_contexts - we need at least one context to generate metrics
match self.contexts.total_contexts {
ConfRange::Constant(0) => return Err("total_contexts cannot be zero".to_string()),
ConfRange::Constant(_) => (), // Non-zero constant is valid
ConfRange::Inclusive { min, max } => {
if min == 0 {
return Err("total_contexts minimum cannot be zero".to_string());
}
if min > max {
return Err("total_contexts minimum cannot be greater than maximum".to_string());
}
}
}
// Validate scopes_per_resource - each resource must have at least one scope
// to contain metrics
match self.contexts.scopes_per_resource {
ConfRange::Constant(0) => return Err("scopes_per_resource cannot be zero".to_string()),
ConfRange::Constant(_) => (), // Non-zero constant is valid
ConfRange::Inclusive { min, max } => {
if min == 0 {
return Err("scopes_per_resource minimum cannot be zero".to_string());
}
if min > max {
return Err(
"scopes_per_resource minimum cannot be greater than maximum".to_string()
);
}
}
}
// Validate metrics_per_scope - each scope must contain at least one metric
// to be meaningful
match self.contexts.metrics_per_scope {
ConfRange::Constant(0) => return Err("metrics_per_scope cannot be zero".to_string()),
ConfRange::Constant(_) => (), // Non-zero constant is valid
ConfRange::Inclusive { min, max } => {
if min == 0 {
return Err("metrics_per_scope minimum cannot be zero".to_string());
}
if min > max {
return Err(
"metrics_per_scope minimum cannot be greater than maximum".to_string()
);
}
}
}
let min_contexts = match self.contexts.total_contexts {
ConfRange::Constant(n) => n,
ConfRange::Inclusive { min, .. } => min,
};
let max_contexts = match self.contexts.total_contexts {
ConfRange::Constant(n) => n,
ConfRange::Inclusive { max, .. } => max,
};
// Calculate minimum and maximum possible contexts based on composition
let min_configured = match self.contexts.scopes_per_resource {
ConfRange::Constant(0) => 0u32,
ConfRange::Constant(n) => {
let metrics = match self.contexts.metrics_per_scope {
ConfRange::Constant(0) => 0u32,
ConfRange::Constant(m) => u32::from(m),
ConfRange::Inclusive { min, .. } => u32::from(min),
};
u32::from(n) * metrics
}
ConfRange::Inclusive { min, .. } => {
let metrics = match self.contexts.metrics_per_scope {
ConfRange::Constant(0) => 0u32,
ConfRange::Constant(m) => u32::from(m),
ConfRange::Inclusive { min, .. } => u32::from(min),
};
u32::from(min) * metrics
}
};
let max_configured = match self.contexts.scopes_per_resource {
ConfRange::Constant(0) => 0u32,
ConfRange::Constant(n) => {
let metrics = match self.contexts.metrics_per_scope {
ConfRange::Constant(0) => 0u32,
ConfRange::Constant(m) => u32::from(m),
ConfRange::Inclusive { max, .. } => u32::from(max),
};
u32::from(n) * metrics
}
ConfRange::Inclusive { max, .. } => {
let metrics = match self.contexts.metrics_per_scope {
ConfRange::Constant(0) => 0u32,
ConfRange::Constant(m) => u32::from(m),
ConfRange::Inclusive { max, .. } => u32::from(max),
};
u32::from(max) * metrics
}
};
// Validate that the requested contexts are achievable
if min_contexts > max_configured {
return Err(format!(
"Minimum requested contexts {min_contexts} cannot be achieved with current configuration (max possible: {max_configured})"
));
}
if max_contexts < min_configured {
return Err(format!(
"Maximum requested contexts {max_contexts} is less than minimum possible contexts {min_configured}"
));
}
Ok(())
}
}
#[derive(Debug, Clone)]
/// OTLP metric payload
pub struct OpentelemetryMetrics {
/// Template pool for metric generation
pool: Pool,
/// Scratch buffer for serialization
scratch: RefCell<BytesMut>,
/// Current tick count for monotonic timing (starts at 0)
tick: u64,
/// Accumulating sum increment, floating point
incr_f: f64,
/// Accumulating sum increment, integer
incr_i: i64,
}
impl OpentelemetryMetrics {
/// Construct a new instance of `OpentelemetryMetrics`
///
/// # Errors
/// Function will error if the configuration is invalid
pub fn new<R>(config: Config, rng: &mut R) -> Result<Self, Error>
where
R: rand::Rng + ?Sized,
{
let context_cap = config.contexts.total_contexts.sample(rng);
// Moby Dick is 1.2Mb. 128Kb should be more than enough for metric
// names, descriptions, etc.
let str_pool = Rc::new(strings::Pool::with_size(rng, 128_000));
let rt_gen = ResourceTemplateGenerator::new(&config, &str_pool, rng)?;
Ok(Self {
pool: Pool::new(context_cap, rt_gen),
scratch: RefCell::new(BytesMut::with_capacity(4096)),
tick: 0,
incr_f: 0.0,
incr_i: 0,
})
}
}
impl<'a> SizedGenerator<'a> for OpentelemetryMetrics {
type Output = v1::ResourceMetrics;
type Error = Error;
/// Generate OTLP metrics with the following enhancements:
///
/// * Monotonic sums are truly monotonic, incrementing by a random amount each tick
/// * Timestamps advance monotonically based on internal tick counter starting at epoch
/// * Each call advances the tick counter by a random amount (1-60)
fn generate<R>(&'a mut self, rng: &mut R, budget: &mut usize) -> Result<Self::Output, Error>
where
R: rand::Rng + ?Sized,
{
self.tick += rng.random_range(1..=60);
self.incr_f += rng.random_range(1.0..=100.0);
self.incr_i += rng.random_range(1_i64..=100_i64);
let mut tpl: v1::ResourceMetrics = match self.pool.fetch(rng, budget) {
Ok(t) => t.to_owned(),
Err(PoolError::EmptyChoice) => {
error!("Pool was unable to satify request for {budget} size");
Err(PoolError::EmptyChoice)?
}
Err(e) => Err(e)?,
};
// Update data points in each metric. For gauges we use random values,
// for accumulating sums we increment by a fixed amount per tick.
// All timestamps are updated based on the current tick.
for scope_metrics in &mut tpl.scope_metrics {
for metric in &mut scope_metrics.metrics {
if let Some(data) = &mut metric.data {
match data {
Data::Gauge(gauge) => {
for point in &mut gauge.data_points {
point.time_unix_nano = self.tick * TIME_INCREMENT_NANOS;
if let Some(value) = &mut point.value {
match value {
number_data_point::Value::AsDouble(v) => {
*v = rng.random();
}
number_data_point::Value::AsInt(v) => {
*v = rng.random();
}
}
}
}
}
Data::Sum(sum) => {
let is_accumulating = sum.is_monotonic;
for point in &mut sum.data_points {
point.time_unix_nano = self.tick * TIME_INCREMENT_NANOS;
if is_accumulating {
// For accumulating sums, monotonically
// increase by some factor of `tick_diff`
if let Some(value) = &mut point.value {
match value {
number_data_point::Value::AsDouble(v) => {
*v += self.incr_f;
}
#[allow(clippy::cast_possible_wrap)]
number_data_point::Value::AsInt(v) => {
*v += self.incr_i;
}
}
}
} else {
// For non-accumulating sums, use random
// values
if let Some(value) = &mut point.value {
match value {
number_data_point::Value::AsDouble(v) => {
*v = rng.random();
}
number_data_point::Value::AsInt(v) => {
*v = rng.random();
}
}
}
}
}
}
_ => unimplemented!(),
}
}
}
}
Ok(tpl)
}
}
impl crate::Serialize for OpentelemetryMetrics {
fn to_bytes<W, R>(&mut self, mut rng: R, max_bytes: usize, writer: &mut W) -> Result<(), Error>
where
R: rand::Rng + Sized,
W: Write,
{
// Our approach here is simple: pack v1::ResourceMetrics from the
// OpentelemetryMetrics generator into a ExportMetricsServiceRequest
// until we hit max_bytes worth of serialized bytes.
let mut bytes_remaining = max_bytes;
let mut request = ExportMetricsServiceRequest {
resource_metrics: Vec::with_capacity(8),
};
let loop_id: u32 = rng.random();
while bytes_remaining >= SMALLEST_PROTOBUF {
if let Ok(rm) = self.generate(&mut rng, &mut bytes_remaining) {
request.resource_metrics.push(rm);
let required_bytes = request.encoded_len();
debug!(
?loop_id,
?max_bytes,
?bytes_remaining,
?required_bytes,
?SMALLEST_PROTOBUF,
"to_bytes inner loop"
);
if required_bytes > max_bytes {
drop(request.resource_metrics.pop());
break;
}
bytes_remaining = max_bytes.saturating_sub(required_bytes);
} else {
debug!(
?bytes_remaining,
?SMALLEST_PROTOBUF,
"could not generate ResourceMetrics instance"
);
}
}
let needed = request.encoded_len();
{
let mut buf = self.scratch.borrow_mut();
buf.clear(); // keep the allocation, drop the contents
let capacity = buf.capacity();
let diff = capacity.saturating_sub(needed);
if buf.capacity() < needed {
buf.reserve(diff); // at most one malloc here
}
request.encode(&mut *buf)?;
writer.write_all(&buf)?;
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::{Config, Contexts, OpentelemetryMetrics, SMALLEST_PROTOBUF};
use crate::{
Serialize, SizedGenerator,
common::config::ConfRange,
opentelemetry_metric::v1::{ResourceMetrics, metric},
};
use opentelemetry_proto::tonic::common::v1::any_value;
use opentelemetry_proto::tonic::metrics::v1::{
Metric, NumberDataPoint, ScopeMetrics, number_data_point,
};
use opentelemetry_proto::tonic::{
collector::metrics::v1::ExportMetricsServiceRequest, metrics::v1::Gauge,
};
use proptest::prelude::*;
use prost::Message;
use rand::{SeedableRng, rngs::SmallRng};
use std::{
collections::{HashMap, HashSet},
hash::{DefaultHasher, Hash, Hasher},
};
// Budget always decreases equivalent to the size of the returned value.
proptest! {
#[test]
fn generate_decrease_budget(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 0..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 0..20_u8,
attributes_per_metric in 0..10_u8,
steps in 1..u8::MAX,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(total_contexts),
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
..Default::default()
};
let mut budget = 10_000_000;
let mut rng = SmallRng::seed_from_u64(seed);
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
for _ in 0..steps {
let prev = budget;
match otel_metrics.generate(&mut rng, &mut budget) {
Ok(rm) => prop_assert_eq!(prev-rm.encoded_len(), budget),
Err(crate::Error::Pool(_)) => break,
Err(e) => return Err(e.into())
}
}
}
}
// Generation of metrics must be deterministic. In order to assert this
// property we generate two instances of OpentelemetryMetrics from disinct
// rngs and drive them forward for a random amount of steps, asserting equal
// outcomes.
proptest! {
#[test]
fn is_deterministic(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 0..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 0..20_u8,
attributes_per_metric in 0..10_u8,
steps in 1..u8::MAX,
budget in 128..2048_usize,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(total_contexts),
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
..Default::default()
};
let mut b1 = budget;
let mut rng1 = SmallRng::seed_from_u64(seed);
let mut otel_metrics1 = OpentelemetryMetrics::new(config, &mut rng1)?;
let mut b2 = budget;
let mut rng2 = SmallRng::seed_from_u64(seed);
let mut otel_metrics2 = OpentelemetryMetrics::new(config, &mut rng2)?;
for _ in 0..steps {
if let Ok(gen_1) = otel_metrics1.generate(&mut rng1, &mut b1) {
let gen_2 = otel_metrics2.generate(&mut rng2, &mut b2).expect("gen_2 was not Ok");
prop_assert_eq!(gen_1, gen_2);
prop_assert_eq!(b1, b2);
} else {
break;
}
}
}
}
// Generation of metrics must be context bounded. If `generate` is called
// more than total_context times only total_context contexts should be
// produced.
proptest! {
#[test]
fn contexts_bound_metric_generation(
seed: u64,
total_contexts_min in 1..4_u32,
total_contexts_max in 5..100_u32,
attributes_per_resource in 0..25_u8,
scopes_per_resource in 1..10_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 1..10_u8,
attributes_per_metric in 0..100_u8,
budget in 128..2048_usize,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Inclusive { min: total_contexts_min, max: total_contexts_max },
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
..Default::default()
};
let mut ids = HashSet::new();
let mut rng = SmallRng::seed_from_u64(seed);
let mut b = budget;
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
let total_generations = total_contexts_max + (total_contexts_max / 2);
for _ in 0..total_generations {
if let Ok(res) = otel_metrics.generate(&mut rng, &mut b) {
let id = context_id(&res);
ids.insert(id);
}
}
let actual_contexts = ids.len();
let bounded_above = actual_contexts <= total_contexts_max as usize;
prop_assert!(bounded_above,
"expected {actual_contexts} ≤ {total_contexts_max}");
}
}
// We want to be sure that the serialized size of the payload does not
// exceed `max_bytes`.
#[test]
fn payload_not_exceed_max_bytes() {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(10),
attributes_per_resource: ConfRange::Constant(5),
scopes_per_resource: ConfRange::Constant(2),
attributes_per_scope: ConfRange::Constant(3),
metrics_per_scope: ConfRange::Constant(4),
attributes_per_metric: ConfRange::Constant(2),
},
..Default::default()
};
let max_bytes = 512;
let mut rng = SmallRng::seed_from_u64(42);
let mut metrics = OpentelemetryMetrics::new(config, &mut rng)
.expect("failed to create metrics generator");
let mut bytes = Vec::new();
metrics
.to_bytes(&mut rng, max_bytes, &mut bytes)
.expect("failed to convert to bytes");
assert!(
bytes.len() <= max_bytes,
"max len: {max_bytes}, actual: {}",
bytes.len()
);
}
// We want to know that every payload produced by this type actually
// deserializes as a collection of OTEL metrics.
#[test]
fn payload_deserializes() {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(5),
attributes_per_resource: ConfRange::Constant(3),
scopes_per_resource: ConfRange::Constant(2),
attributes_per_scope: ConfRange::Constant(1),
metrics_per_scope: ConfRange::Constant(3),
attributes_per_metric: ConfRange::Constant(2),
},
..Default::default()
};
let max_bytes = 256;
let mut rng = SmallRng::seed_from_u64(42);
let mut metrics = OpentelemetryMetrics::new(config, &mut rng)
.expect("failed to create metrics generator");
let mut bytes: Vec<u8> = Vec::new();
metrics
.to_bytes(&mut rng, max_bytes, &mut bytes)
.expect("failed to convert to bytes");
opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest::decode(
bytes.as_slice(),
)
.expect("failed to decode the message from the buffer");
}
// Confirm that configuration bounds are naively obeyed. For instance, this
// test will pass if every resource generated has identical attributes, etc
// etc. Confirmation of context bounds being obeyed -- implying examination
// of attributes et al -- is appropriate for another property test.
proptest! {
#[test]
fn counts_within_bounds(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 0..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 0..20_u8,
attributes_per_metric in 0..10_u8,
steps in 1..u8::MAX,
budget in SMALLEST_PROTOBUF..2048_usize,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(total_contexts),
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
..Default::default()
};
let mut b = budget;
let mut rng = SmallRng::seed_from_u64(seed);
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
for _ in 0..steps {
if let Ok(metric) = otel_metrics.generate(&mut rng, &mut b) {
if let Some(resource) = &metric.resource {
prop_assert!(
resource.attributes.len() <= attributes_per_resource as usize,
"Resource attributes count {len} exceeds configured maximum {attributes_per_resource}",
len = resource.attributes.len(),
);
}
prop_assert!(
metric.scope_metrics.len() <= scopes_per_resource as usize,
"Scopes per resource count {len} exceeds configured maximum {scopes_per_resource}",
len = metric.scope_metrics.len(),
);
for scope in &metric.scope_metrics {
if let Some(scope) = &scope.scope {
prop_assert!(
scope.attributes.len() <= attributes_per_scope as usize,
"Scope attributes count {len} exceeds configured maximum {attributes_per_scope}",
len = scope.attributes.len(),
);
}
prop_assert!(
scope.metrics.len() <= metrics_per_scope as usize,
"Metrics per scope count {len} exceeds configured maximum {metrics_per_scope}",
len = scope.metrics.len(),
);
for metric in &scope.metrics {
prop_assert!(
metric.metadata.len() <= attributes_per_metric as usize,
"Metric attributes count {len} exceeds configured maximum {attributes_per_metric}",
len = metric.metadata.len(),
);
}
}
}
}
}
}
/// Extracts and hashes the context from a `ResourceMetrics`.
///
/// A context is defined by the unique combination of:
/// - Resource attributes
/// - Scope attributes
/// - Metric name, attributes, data kind, and unit
fn context_id(metric: &ResourceMetrics) -> u64 {
let mut hasher = DefaultHasher::new();
// Hash resource attributes
if let Some(resource) = &metric.resource {
for attr in &resource.attributes {
attr.key.hash(&mut hasher);
if let Some(value) = &attr.value {
if let Some(any_value::Value::StringValue(s)) = &value.value {
s.hash(&mut hasher);
}
}
}
}
// Hash each scope's context
for scope_metrics in &metric.scope_metrics {
// Hash scope attributes
if let Some(scope) = &scope_metrics.scope {
for attr in &scope.attributes {
attr.key.hash(&mut hasher);
if let Some(value) = &attr.value {
if let Some(any_value::Value::StringValue(s)) = &value.value {
s.hash(&mut hasher);
}
}
}
}
// Hash each metric's context
for metric in &scope_metrics.metrics {
// Hash metric name
metric.name.hash(&mut hasher);
// Hash metric attributes
for attr in &metric.metadata {
attr.key.hash(&mut hasher);
if let Some(value) = &attr.value {
if let Some(any_value::Value::StringValue(s)) = &value.value {
s.hash(&mut hasher);
}
}
}
// Hash metric data kind and unit
metric.unit.hash(&mut hasher);
if let Some(data) = &metric.data {
match data {
metric::Data::Gauge(_) => "gauge".hash(&mut hasher),
metric::Data::Sum(sum) => {
"sum".hash(&mut hasher);
sum.aggregation_temporality.hash(&mut hasher);
sum.is_monotonic.hash(&mut hasher);
}
// Add other metric types as needed
_ => "unknown".hash(&mut hasher),
}
}
}
}
hasher.finish()
}
// Ensures that the context_id function serves as an equality test, ignoring
// value differences etc.
proptest! {
#[test]
fn context_is_equality(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 1..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 1..20_u8,
attributes_per_metric in 0..10_u8,
budget in SMALLEST_PROTOBUF..4098_usize,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(total_contexts),
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
..Default::default()
};
let mut b1 = budget;
let mut rng = SmallRng::seed_from_u64(seed);
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
let metric1 = otel_metrics.generate(&mut rng, &mut b1);
// Generate two identical metrics
let mut b2 = budget;
let mut rng = SmallRng::seed_from_u64(seed);
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
let metric2 = otel_metrics.generate(&mut rng, &mut b2);
// Ensure that the metrics are equal and that their contexts, when
// applicable, are also equal.
if let Ok(m1) = metric1 {
let m2 = metric2.unwrap();
prop_assert_eq!(context_id(&m1), context_id(&m2));
prop_assert_eq!(m1, m2);
}
}
}
// Property: timestamps are monotonic
proptest! {
#[test]
fn timestamps_increase_monotonically(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 0..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 0..20_u8,
attributes_per_metric in 0..10_u8,
steps in 1..u8::MAX,
budget in SMALLEST_PROTOBUF..2048_usize,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(total_contexts),
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
..Default::default()
};
let mut budget = budget;
let mut rng = SmallRng::seed_from_u64(seed);
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
let mut timestamps_by_metric: HashMap<u64, Vec<u64>> = HashMap::new();
for _ in 0..steps {
if let Ok(resource_metric) = otel_metrics.generate(&mut rng, &mut budget) {
for scope_metric in &resource_metric.scope_metrics {
for metric in &scope_metric.metrics {
let id = context_id(&resource_metric);
if let Some(data) = &metric.data {
match data {
metric::Data::Gauge(gauge) => {
for point in &gauge.data_points {
timestamps_by_metric
.entry(id)
.or_insert_with(Vec::new)
.push(point.time_unix_nano);
}
},
metric::Data::Sum(sum) => {
for point in &sum.data_points {
timestamps_by_metric
.entry(id)
.or_insert_with(Vec::new)
.push(point.time_unix_nano);
}
},
_ => {},
}
}
}
}
}
}
if !timestamps_by_metric.is_empty() {
// For each metric, verify its timestamps increase monotonically
for (metric_id, timestamps) in ×tamps_by_metric {
if timestamps.len() > 1 {
for i in 1..timestamps.len() {
let current = timestamps[i];
let previous = timestamps[i-1]; // safety: iterator begins at 1
prop_assert!(
current >= previous,
"Timestamp for metric {metric_id} did not increase monotonically: current={current}, previous={previous}",
);
}
}
}
}
}
}
// Property: tick tally in OpentelemetryMetrics increase with calls to
// `generate`.
proptest! {
#[test]
fn increasing_ticks(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 0..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 0..20_u8,
attributes_per_metric in 0..10_u8,
budget in SMALLEST_PROTOBUF..4098_usize,
) {
let config = Config {
contexts: Contexts {
total_contexts: ConfRange::Constant(total_contexts),
attributes_per_resource: ConfRange::Constant(attributes_per_resource),
scopes_per_resource: ConfRange::Constant(scopes_per_resource),
attributes_per_scope: ConfRange::Constant(attributes_per_scope),
metrics_per_scope: ConfRange::Constant(metrics_per_scope),
attributes_per_metric: ConfRange::Constant(attributes_per_metric),
},
metric_weights: super::MetricWeights {
gauge: 0, // Only generate sum metrics
sum: 100,
},
};
let mut budget = budget;
let mut rng = SmallRng::seed_from_u64(seed);
let mut otel_metrics = OpentelemetryMetrics::new(config, &mut rng)?;
let prev = otel_metrics.tick;
let _ = otel_metrics.generate(&mut rng, &mut budget);
let cur = otel_metrics.tick;
prop_assert!(cur > prev, "Ticks did not advance properly: current: {cur}, previous: {prev}");
}
}
// Property: accumulated sums are monotonic
proptest! {
#[test]
fn accumulating_sums_only_increase(
seed: u64,
total_contexts in 1..1_000_u32,
attributes_per_resource in 0..20_u8,
scopes_per_resource in 0..20_u8,
attributes_per_scope in 0..20_u8,
metrics_per_scope in 0..20_u8,
attributes_per_metric in 0..10_u8,
budget in SMALLEST_PROTOBUF..512_usize, // see note below about repetition