aboutsummaryrefslogtreecommitdiff
path: root/.venv/lib/python3.12/site-packages/opentelemetry/sdk/metrics/_internal/aggregation.py
blob: 8443d9516cf04c4ffb31efc6912deef5114a6ad4 (about) (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# pylint: disable=too-many-lines

from abc import ABC, abstractmethod
from bisect import bisect_left
from enum import IntEnum
from functools import partial
from logging import getLogger
from math import inf
from threading import Lock
from typing import (
    Callable,
    Generic,
    List,
    Optional,
    Sequence,
    Type,
    TypeVar,
)

from opentelemetry.metrics import (
    Asynchronous,
    Counter,
    Histogram,
    Instrument,
    ObservableCounter,
    ObservableGauge,
    ObservableUpDownCounter,
    Synchronous,
    UpDownCounter,
    _Gauge,
)
from opentelemetry.sdk.metrics._internal.exemplar import (
    Exemplar,
    ExemplarReservoirBuilder,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.buckets import (
    Buckets,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping import (
    Mapping,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping.exponent_mapping import (
    ExponentMapping,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping.logarithm_mapping import (
    LogarithmMapping,
)
from opentelemetry.sdk.metrics._internal.measurement import Measurement
from opentelemetry.sdk.metrics._internal.point import Buckets as BucketsPoint
from opentelemetry.sdk.metrics._internal.point import (
    ExponentialHistogramDataPoint,
    HistogramDataPoint,
    NumberDataPoint,
    Sum,
)
from opentelemetry.sdk.metrics._internal.point import Gauge as GaugePoint
from opentelemetry.sdk.metrics._internal.point import (
    Histogram as HistogramPoint,
)
from opentelemetry.util.types import Attributes

_DataPointVarT = TypeVar("_DataPointVarT", NumberDataPoint, HistogramDataPoint)

_logger = getLogger(__name__)


class AggregationTemporality(IntEnum):
    """
    The temporality to use when aggregating data.

    Can be one of the following values:
    """

    UNSPECIFIED = 0
    DELTA = 1
    CUMULATIVE = 2


class _Aggregation(ABC, Generic[_DataPointVarT]):
    def __init__(
        self,
        attributes: Attributes,
        reservoir_builder: ExemplarReservoirBuilder,
    ):
        self._lock = Lock()
        self._attributes = attributes
        self._reservoir = reservoir_builder()
        self._previous_point = None

    @abstractmethod
    def aggregate(
        self, measurement: Measurement, should_sample_exemplar: bool = True
    ) -> None:
        """Aggregate a measurement.

        Args:
            measurement: Measurement to aggregate
            should_sample_exemplar: Whether the measurement should be sampled by the exemplars reservoir or not.
        """

    @abstractmethod
    def collect(
        self,
        collection_aggregation_temporality: AggregationTemporality,
        collection_start_nano: int,
    ) -> Optional[_DataPointVarT]:
        pass

    def _collect_exemplars(self) -> Sequence[Exemplar]:
        """Returns the collected exemplars.

        Returns:
            The exemplars collected by the reservoir
        """
        return self._reservoir.collect(self._attributes)

    def _sample_exemplar(
        self, measurement: Measurement, should_sample_exemplar: bool
    ) -> None:
        """Offer the measurement to the exemplar reservoir for sampling.

        It should be called within the each :ref:`aggregate` call.

        Args:
            measurement: The new measurement
            should_sample_exemplar: Whether the measurement should be sampled by the exemplars reservoir or not.
        """
        if should_sample_exemplar:
            self._reservoir.offer(
                measurement.value,
                measurement.time_unix_nano,
                measurement.attributes,
                measurement.context,
            )


class _DropAggregation(_Aggregation):
    def aggregate(
        self, measurement: Measurement, should_sample_exemplar: bool = True
    ) -> None:
        pass

    def collect(
        self,
        collection_aggregation_temporality: AggregationTemporality,
        collection_start_nano: int,
    ) -> Optional[_DataPointVarT]:
        pass


class _SumAggregation(_Aggregation[Sum]):
    def __init__(
        self,
        attributes: Attributes,
        instrument_is_monotonic: bool,
        instrument_aggregation_temporality: AggregationTemporality,
        start_time_unix_nano: int,
        reservoir_builder: ExemplarReservoirBuilder,
    ):
        super().__init__(attributes, reservoir_builder)

        self._start_time_unix_nano = start_time_unix_nano
        self._instrument_aggregation_temporality = (
            instrument_aggregation_temporality
        )
        self._instrument_is_monotonic = instrument_is_monotonic

        self._value = None

        self._previous_collection_start_nano = self._start_time_unix_nano
        self._previous_value = 0

    def aggregate(
        self, measurement: Measurement, should_sample_exemplar: bool = True
    ) -> None:
        with self._lock:
            if self._value is None:
                self._value = 0

            self._value = self._value + measurement.value

        self._sample_exemplar(measurement, should_sample_exemplar)

    def collect(
        self,
        collection_aggregation_temporality: AggregationTemporality,
        collection_start_nano: int,
    ) -> Optional[NumberDataPoint]:
        """
        Atomically return a point for the current value of the metric and
        reset the aggregation value.

        Synchronous instruments have a method which is called directly with
        increments for a given quantity:

        For example, an instrument that counts the amount of passengers in
        every vehicle that crosses a certain point in a highway:

        synchronous_instrument.add(2)
        collect(...)  # 2 passengers are counted
        synchronous_instrument.add(3)
        collect(...)  # 3 passengers are counted
        synchronous_instrument.add(1)
        collect(...)  # 1 passenger is counted

        In this case the instrument aggregation temporality is DELTA because
        every value represents an increment to the count,

        Asynchronous instruments have a callback which returns the total value
        of a given quantity:

        For example, an instrument that measures the amount of bytes written to
        a certain hard drive:

        callback() -> 1352
        collect(...) # 1352 bytes have been written so far
        callback() -> 2324
        collect(...) # 2324 bytes have been written so far
        callback() -> 4542
        collect(...) # 4542 bytes have been written so far

        In this case the instrument aggregation temporality is CUMULATIVE
        because every value represents the total of the measurement.

        There is also the collection aggregation temporality, which is passed
        to this method. The collection aggregation temporality defines the
        nature of the returned value by this aggregation.

        When the collection aggregation temporality matches the
        instrument aggregation temporality, then this method returns the
        current value directly:

        synchronous_instrument.add(2)
        collect(DELTA) -> 2
        synchronous_instrument.add(3)
        collect(DELTA) -> 3
        synchronous_instrument.add(1)
        collect(DELTA) -> 1

        callback() -> 1352
        collect(CUMULATIVE) -> 1352
        callback() -> 2324
        collect(CUMULATIVE) -> 2324
        callback() -> 4542
        collect(CUMULATIVE) -> 4542

        When the collection aggregation temporality does not match the
        instrument aggregation temporality, then a conversion is made. For this
        purpose, this aggregation keeps a private attribute,
        self._previous_value.

        When the instrument is synchronous:

        self._previous_value is the sum of every previously
        collected (delta) value. In this case, the returned (cumulative) value
        will be:

        self._previous_value + value

        synchronous_instrument.add(2)
        collect(CUMULATIVE) -> 2
        synchronous_instrument.add(3)
        collect(CUMULATIVE) -> 5
        synchronous_instrument.add(1)
        collect(CUMULATIVE) -> 6

        Also, as a diagram:

        time ->

        self._previous_value
        |-------------|

        value (delta)
                      |----|

        returned value (cumulative)
        |------------------|

        When the instrument is asynchronous:

        self._previous_value is the value of the previously
        collected (cumulative) value. In this case, the returned (delta) value
        will be:

        value - self._previous_value

        callback() -> 1352
        collect(DELTA) -> 1352
        callback() -> 2324
        collect(DELTA) -> 972
        callback() -> 4542
        collect(DELTA) -> 2218

        Also, as a diagram:

        time ->

        self._previous_value
        |-------------|

        value (cumulative)
        |------------------|

        returned value (delta)
                      |----|
        """

        with self._lock:
            value = self._value
            self._value = None

            if (
                self._instrument_aggregation_temporality
                is AggregationTemporality.DELTA
            ):
                # This happens when the corresponding instrument for this
                # aggregation is synchronous.
                if (
                    collection_aggregation_temporality
                    is AggregationTemporality.DELTA
                ):
                    previous_collection_start_nano = (
                        self._previous_collection_start_nano
                    )
                    self._previous_collection_start_nano = (
                        collection_start_nano
                    )

                    if value is None:
                        return None

                    return NumberDataPoint(
                        attributes=self._attributes,
                        exemplars=self._collect_exemplars(),
                        start_time_unix_nano=previous_collection_start_nano,
                        time_unix_nano=collection_start_nano,
                        value=value,
                    )

                if value is None:
                    value = 0

                self._previous_value = value + self._previous_value

                return NumberDataPoint(
                    attributes=self._attributes,
                    exemplars=self._collect_exemplars(),
                    start_time_unix_nano=self._start_time_unix_nano,
                    time_unix_nano=collection_start_nano,
                    value=self._previous_value,
                )

            # This happens when the corresponding instrument for this
            # aggregation is asynchronous.

            if value is None:
                # This happens when the corresponding instrument callback
                # does not produce measurements.
                return None

            if (
                collection_aggregation_temporality
                is AggregationTemporality.DELTA
            ):
                result_value = value - self._previous_value

                self._previous_value = value

                previous_collection_start_nano = (
                    self._previous_collection_start_nano
                )
                self._previous_collection_start_nano = collection_start_nano

                return NumberDataPoint(
                    attributes=self._attributes,
                    exemplars=self._collect_exemplars(),
                    start_time_unix_nano=previous_collection_start_nano,
                    time_unix_nano=collection_start_nano,
                    value=result_value,
                )

            return NumberDataPoint(
                attributes=self._attributes,
                exemplars=self._collect_exemplars(),
                start_time_unix_nano=self._start_time_unix_nano,
                time_unix_nano=collection_start_nano,
                value=value,
            )


class _LastValueAggregation(_Aggregation[GaugePoint]):
    def __init__(
        self,
        attributes: Attributes,
        reservoir_builder: ExemplarReservoirBuilder,
    ):
        super().__init__(attributes, reservoir_builder)
        self._value = None

    def aggregate(
        self, measurement: Measurement, should_sample_exemplar: bool = True
    ):
        with self._lock:
            self._value = measurement.value

        self._sample_exemplar(measurement, should_sample_exemplar)

    def collect(
        self,
        collection_aggregation_temporality: AggregationTemporality,
        collection_start_nano: int,
    ) -> Optional[_DataPointVarT]:
        """
        Atomically return a point for the current value of the metric.
        """
        with self._lock:
            if self._value is None:
                return None
            value = self._value
            self._value = None

        exemplars = self._collect_exemplars()

        return NumberDataPoint(
            attributes=self._attributes,
            exemplars=exemplars,
            start_time_unix_nano=None,
            time_unix_nano=collection_start_nano,
            value=value,
        )


_DEFAULT_EXPLICIT_BUCKET_HISTOGRAM_AGGREGATION_BOUNDARIES: Sequence[float] = (
    0.0,
    5.0,
    10.0,
    25.0,
    50.0,
    75.0,
    100.0,
    250.0,
    500.0,
    750.0,
    1000.0,
    2500.0,
    5000.0,
    7500.0,
    10000.0,
)


class _ExplicitBucketHistogramAggregation(_Aggregation[HistogramPoint]):
    def __init__(
        self,
        attributes: Attributes,
        instrument_aggregation_temporality: AggregationTemporality,
        start_time_unix_nano: int,
        reservoir_builder: ExemplarReservoirBuilder,
        boundaries: Optional[Sequence[float]] = None,
        record_min_max: bool = True,
    ):
        if boundaries is None:
            boundaries = (
                _DEFAULT_EXPLICIT_BUCKET_HISTOGRAM_AGGREGATION_BOUNDARIES
            )
        super().__init__(
            attributes,
            reservoir_builder=partial(
                reservoir_builder, boundaries=boundaries
            ),
        )

        self._instrument_aggregation_temporality = (
            instrument_aggregation_temporality
        )
        self._start_time_unix_nano = start_time_unix_nano
        self._boundaries = tuple(boundaries)
        self._record_min_max = record_min_max

        self._value = None
        self._min = inf
        self._max = -inf
        self._sum = 0

        self._previous_value = None
        self._previous_min = inf
        self._previous_max = -inf
        self._previous_sum = 0

        self._previous_collection_start_nano = self._start_time_unix_nano

    def _get_empty_bucket_counts(self) -> List[int]:
        return [0] * (len(self._boundaries) + 1)

    def aggregate(
        self, measurement: Measurement, should_sample_exemplar: bool = True
    ) -> None:
        with self._lock:
            if self._value is None:
                self._value = self._get_empty_bucket_counts()

            measurement_value = measurement.value

            self._sum += measurement_value

            if self._record_min_max:
                self._min = min(self._min, measurement_value)
                self._max = max(self._max, measurement_value)

            self._value[bisect_left(self._boundaries, measurement_value)] += 1

        self._sample_exemplar(measurement, should_sample_exemplar)

    def collect(
        self,
        collection_aggregation_temporality: AggregationTemporality,
        collection_start_nano: int,
    ) -> Optional[_DataPointVarT]:
        """
        Atomically return a point for the current value of the metric.
        """

        with self._lock:
            value = self._value
            sum_ = self._sum
            min_ = self._min
            max_ = self._max

            self._value = None
            self._sum = 0
            self._min = inf
            self._max = -inf

            if (
                self._instrument_aggregation_temporality
                is AggregationTemporality.DELTA
            ):
                # This happens when the corresponding instrument for this
                # aggregation is synchronous.
                if (
                    collection_aggregation_temporality
                    is AggregationTemporality.DELTA
                ):
                    previous_collection_start_nano = (
                        self._previous_collection_start_nano
                    )
                    self._previous_collection_start_nano = (
                        collection_start_nano
                    )

                    if value is None:
                        return None

                    return HistogramDataPoint(
                        attributes=self._attributes,
                        exemplars=self._collect_exemplars(),
                        start_time_unix_nano=previous_collection_start_nano,
                        time_unix_nano=collection_start_nano,
                        count=sum(value),
                        sum=sum_,
                        bucket_counts=tuple(value),
                        explicit_bounds=self._boundaries,
                        min=min_,
                        max=max_,
                    )

                if value is None:
                    value = self._get_empty_bucket_counts()

                if self._previous_value is None:
                    self._previous_value = self._get_empty_bucket_counts()

                self._previous_value = [
                    value_element + previous_value_element
                    for (
                        value_element,
                        previous_value_element,
                    ) in zip(value, self._previous_value)
                ]
                self._previous_min = min(min_, self._previous_min)
                self._previous_max = max(max_, self._previous_max)
                self._previous_sum = sum_ + self._previous_sum

                return HistogramDataPoint(
                    attributes=self._attributes,
                    exemplars=self._collect_exemplars(),
                    start_time_unix_nano=self._start_time_unix_nano,
                    time_unix_nano=collection_start_nano,
                    count=sum(self._previous_value),
                    sum=self._previous_sum,
                    bucket_counts=tuple(self._previous_value),
                    explicit_bounds=self._boundaries,
                    min=self._previous_min,
                    max=self._previous_max,
                )

            return None


# pylint: disable=protected-access
class _ExponentialBucketHistogramAggregation(_Aggregation[HistogramPoint]):
    # _min_max_size and _max_max_size are the smallest and largest values
    # the max_size parameter may have, respectively.

    # _min_max_size is is the smallest reasonable value which is small enough
    # to contain the entire normal floating point range at the minimum scale.
    _min_max_size = 2

    # _max_max_size is an arbitrary limit meant to limit accidental creation of
    # giant exponential bucket histograms.
    _max_max_size = 16384

    def __init__(
        self,
        attributes: Attributes,
        reservoir_builder: ExemplarReservoirBuilder,
        instrument_aggregation_temporality: AggregationTemporality,
        start_time_unix_nano: int,
        # This is the default maximum number of buckets per positive or
        # negative number range.  The value 160 is specified by OpenTelemetry.
        # See the derivation here:
        # https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exponential-bucket-histogram-aggregation)
        max_size: int = 160,
        max_scale: int = 20,
    ):
        # max_size is the maximum capacity of the positive and negative
        # buckets.
        # _sum is the sum of all the values aggregated by this aggregator.
        # _count is the count of all calls to aggregate.
        # _zero_count is the count of all the calls to aggregate when the value
        # to be aggregated is exactly 0.
        # _min is the smallest value aggregated by this aggregator.
        # _max is the smallest value aggregated by this aggregator.
        # _positive holds the positive values.
        # _negative holds the negative values by their absolute value.
        if max_size < self._min_max_size:
            raise ValueError(
                f"Buckets max size {max_size} is smaller than "
                "minimum max size {self._min_max_size}"
            )

        if max_size > self._max_max_size:
            raise ValueError(
                f"Buckets max size {max_size} is larger than "
                "maximum max size {self._max_max_size}"
            )
        if max_scale > 20:
            _logger.warning(
                "max_scale is set to %s which is "
                "larger than the recommended value of 20",
                max_scale,
            )

        # This aggregation is analogous to _ExplicitBucketHistogramAggregation,
        # the only difference is that with every call to aggregate, the size
        # and amount of buckets can change (in
        # _ExplicitBucketHistogramAggregation both size and amount of buckets
        # remain constant once it is instantiated).

        super().__init__(
            attributes,
            reservoir_builder=partial(
                reservoir_builder, size=min(20, max_size)
            ),
        )

        self._instrument_aggregation_temporality = (
            instrument_aggregation_temporality
        )
        self._start_time_unix_nano = start_time_unix_nano
        self._max_size = max_size
        self._max_scale = max_scale

        self._value_positive = None
        self._value_negative = None
        self._min = inf
        self._max = -inf
        self._sum = 0
        self._count = 0
        self._zero_count = 0
        self._scale = None

        self._previous_value_positive = None
        self._previous_value_negative = None
        self._previous_min = inf
        self._previous_max = -inf
        self._previous_sum = 0
        self._previous_count = 0
        self._previous_zero_count = 0
        self._previous_scale = None

        self._previous_collection_start_nano = self._start_time_unix_nano

        self._mapping = self._new_mapping(self._max_scale)

    def aggregate(
        self, measurement: Measurement, should_sample_exemplar: bool = True
    ) -> None:
        # pylint: disable=too-many-branches,too-many-statements, too-many-locals

        with self._lock:
            if self._value_positive is None:
                self._value_positive = Buckets()
            if self._value_negative is None:
                self._value_negative = Buckets()

            measurement_value = measurement.value

            self._sum += measurement_value

            self._min = min(self._min, measurement_value)
            self._max = max(self._max, measurement_value)

            self._count += 1

            if measurement_value == 0:
                self._zero_count += 1

                if self._count == self._zero_count:
                    self._scale = 0

                return

            if measurement_value > 0:
                value = self._value_positive

            else:
                measurement_value = -measurement_value
                value = self._value_negative

            # The following code finds out if it is necessary to change the
            # buckets to hold the incoming measurement_value, changes them if
            # necessary. This process does not exist in
            # _ExplicitBucketHistogram aggregation because the buckets there
            # are constant in size and amount.
            index = self._mapping.map_to_index(measurement_value)

            is_rescaling_needed = False
            low, high = 0, 0

            if len(value) == 0:
                value.index_start = index
                value.index_end = index
                value.index_base = index

            elif (
                index < value.index_start
                and (value.index_end - index) >= self._max_size
            ):
                is_rescaling_needed = True
                low = index
                high = value.index_end

            elif (
                index > value.index_end
                and (index - value.index_start) >= self._max_size
            ):
                is_rescaling_needed = True
                low = value.index_start
                high = index

            if is_rescaling_needed:
                scale_change = self._get_scale_change(low, high)
                self._downscale(
                    scale_change,
                    self._value_positive,
                    self._value_negative,
                )
                self._mapping = self._new_mapping(
                    self._mapping.scale - scale_change
                )

                index = self._mapping.map_to_index(measurement_value)

            self._scale = self._mapping.scale

            if index < value.index_start:
                span = value.index_end - index

                if span >= len(value.counts):
                    value.grow(span + 1, self._max_size)

                value.index_start = index

            elif index > value.index_end:
                span = index - value.index_start

                if span >= len(value.counts):
                    value.grow(span + 1, self._max_size)

                value.index_end = index

            bucket_index = index - value.index_base

            if bucket_index < 0:
                bucket_index += len(value.counts)

            # Now the buckets have been changed if needed and bucket_index will
            # be used to increment the counter of the bucket that needs to be
            # incremented.

            # This is analogous to
            # self._value[bisect_left(self._boundaries, measurement_value)] += 1
            # in _ExplicitBucketHistogramAggregation.aggregate
            value.increment_bucket(bucket_index)

        self._sample_exemplar(measurement, should_sample_exemplar)

    def collect(
        self,
        collection_aggregation_temporality: AggregationTemporality,
        collection_start_nano: int,
    ) -> Optional[_DataPointVarT]:
        """
        Atomically return a point for the current value of the metric.
        """

        # pylint: disable=too-many-statements, too-many-locals
        with self._lock:
            value_positive = self._value_positive
            value_negative = self._value_negative
            sum_ = self._sum
            min_ = self._min
            max_ = self._max
            count = self._count
            zero_count = self._zero_count
            scale = self._scale

            self._value_positive = None
            self._value_negative = None
            self._sum = 0
            self._min = inf
            self._max = -inf
            self._count = 0
            self._zero_count = 0
            self._scale = None

            if (
                self._instrument_aggregation_temporality
                is AggregationTemporality.DELTA
            ):
                # This happens when the corresponding instrument for this
                # aggregation is synchronous.
                if (
                    collection_aggregation_temporality
                    is AggregationTemporality.DELTA
                ):
                    previous_collection_start_nano = (
                        self._previous_collection_start_nano
                    )
                    self._previous_collection_start_nano = (
                        collection_start_nano
                    )

                    if value_positive is None and value_negative is None:
                        return None

                    return ExponentialHistogramDataPoint(
                        attributes=self._attributes,
                        exemplars=self._collect_exemplars(),
                        start_time_unix_nano=previous_collection_start_nano,
                        time_unix_nano=collection_start_nano,
                        count=count,
                        sum=sum_,
                        scale=scale,
                        zero_count=zero_count,
                        positive=BucketsPoint(
                            offset=value_positive.offset,
                            bucket_counts=(value_positive.get_offset_counts()),
                        ),
                        negative=BucketsPoint(
                            offset=value_negative.offset,
                            bucket_counts=(value_negative.get_offset_counts()),
                        ),
                        # FIXME: Find the right value for flags
                        flags=0,
                        min=min_,
                        max=max_,
                    )

                # Here collection_temporality is CUMULATIVE.
                # instrument_temporality is always DELTA for the time being.
                # Here we need to handle the case where:
                # collect is called after at least one other call to collect
                # (there is data in previous buckets, a call to merge is needed
                # to handle possible differences in bucket sizes).
                # collect is called without another call previous call to
                # collect was made (there is no previous buckets, previous,
                # empty buckets that are the same scale of the current buckets
                # need to be made so that they can be cumulatively aggregated
                # to the current buckets).

                if (
                    value_positive is None
                    and self._previous_value_positive is None
                ):
                    # This happens if collect is called for the first time
                    # and aggregate has not yet been called.
                    value_positive = Buckets()
                    self._previous_value_positive = value_positive.copy_empty()
                if (
                    value_negative is None
                    and self._previous_value_negative is None
                ):
                    value_negative = Buckets()
                    self._previous_value_negative = value_negative.copy_empty()
                if scale is None and self._previous_scale is None:
                    scale = self._mapping.scale
                    self._previous_scale = scale

                if (
                    value_positive is not None
                    and self._previous_value_positive is None
                ):
                    # This happens when collect is called the very first time
                    # and aggregate has been called before.

                    # We need previous buckets to add them to the current ones.
                    # When collect is called for the first time, there are no
                    # previous buckets, so we need to create empty buckets to
                    # add them to the current ones. The addition of empty
                    # buckets to the current ones will result in the current
                    # ones unchanged.

                    # The way the previous buckets are generated here is
                    # different from the explicit bucket histogram where
                    # the size and amount of the buckets does not change once
                    # they are instantiated. Here, the size and amount of the
                    # buckets can change with every call to aggregate. In order
                    # to get empty buckets that can be added to the current
                    # ones resulting in the current ones unchanged we need to
                    # generate empty buckets that have the same size and amount
                    # as the current ones, this is what copy_empty does.
                    self._previous_value_positive = value_positive.copy_empty()
                if (
                    value_negative is not None
                    and self._previous_value_negative is None
                ):
                    self._previous_value_negative = value_negative.copy_empty()
                if scale is not None and self._previous_scale is None:
                    self._previous_scale = scale

                if (
                    value_positive is None
                    and self._previous_value_positive is not None
                ):
                    value_positive = self._previous_value_positive.copy_empty()
                if (
                    value_negative is None
                    and self._previous_value_negative is not None
                ):
                    value_negative = self._previous_value_negative.copy_empty()
                if scale is None and self._previous_scale is not None:
                    scale = self._previous_scale

                min_scale = min(self._previous_scale, scale)

                low_positive, high_positive = (
                    self._get_low_high_previous_current(
                        self._previous_value_positive,
                        value_positive,
                        scale,
                        min_scale,
                    )
                )
                low_negative, high_negative = (
                    self._get_low_high_previous_current(
                        self._previous_value_negative,
                        value_negative,
                        scale,
                        min_scale,
                    )
                )

                min_scale = min(
                    min_scale
                    - self._get_scale_change(low_positive, high_positive),
                    min_scale
                    - self._get_scale_change(low_negative, high_negative),
                )

                self._downscale(
                    self._previous_scale - min_scale,
                    self._previous_value_positive,
                    self._previous_value_negative,
                )

                # self._merge adds the values from value to
                # self._previous_value, this is analogous to
                # self._previous_value = [
                #     value_element + previous_value_element
                #     for (
                #         value_element,
                #         previous_value_element,
                #     ) in zip(value, self._previous_value)
                # ]
                # in _ExplicitBucketHistogramAggregation.collect.
                self._merge(
                    self._previous_value_positive,
                    value_positive,
                    scale,
                    min_scale,
                    collection_aggregation_temporality,
                )
                self._merge(
                    self._previous_value_negative,
                    value_negative,
                    scale,
                    min_scale,
                    collection_aggregation_temporality,
                )

                self._previous_min = min(min_, self._previous_min)
                self._previous_max = max(max_, self._previous_max)
                self._previous_sum = sum_ + self._previous_sum
                self._previous_count = count + self._previous_count
                self._previous_zero_count = (
                    zero_count + self._previous_zero_count
                )
                self._previous_scale = min_scale

                return ExponentialHistogramDataPoint(
                    attributes=self._attributes,
                    exemplars=self._collect_exemplars(),
                    start_time_unix_nano=self._start_time_unix_nano,
                    time_unix_nano=collection_start_nano,
                    count=self._previous_count,
                    sum=self._previous_sum,
                    scale=self._previous_scale,
                    zero_count=self._previous_zero_count,
                    positive=BucketsPoint(
                        offset=self._previous_value_positive.offset,
                        bucket_counts=(
                            self._previous_value_positive.get_offset_counts()
                        ),
                    ),
                    negative=BucketsPoint(
                        offset=self._previous_value_negative.offset,
                        bucket_counts=(
                            self._previous_value_negative.get_offset_counts()
                        ),
                    ),
                    # FIXME: Find the right value for flags
                    flags=0,
                    min=self._previous_min,
                    max=self._previous_max,
                )

            return None

    def _get_low_high_previous_current(
        self,
        previous_point_buckets,
        current_point_buckets,
        current_scale,
        min_scale,
    ):
        (previous_point_low, previous_point_high) = self._get_low_high(
            previous_point_buckets, self._previous_scale, min_scale
        )
        (current_point_low, current_point_high) = self._get_low_high(
            current_point_buckets, current_scale, min_scale
        )

        if current_point_low > current_point_high:
            low = previous_point_low
            high = previous_point_high

        elif previous_point_low > previous_point_high:
            low = current_point_low
            high = current_point_high

        else:
            low = min(previous_point_low, current_point_low)
            high = max(previous_point_high, current_point_high)

        return low, high

    @staticmethod
    def _get_low_high(buckets, scale, min_scale):
        if buckets.counts == [0]:
            return 0, -1

        shift = scale - min_scale

        return buckets.index_start >> shift, buckets.index_end >> shift

    @staticmethod
    def _new_mapping(scale: int) -> Mapping:
        if scale <= 0:
            return ExponentMapping(scale)
        return LogarithmMapping(scale)

    def _get_scale_change(self, low, high):
        change = 0

        while high - low >= self._max_size:
            high = high >> 1
            low = low >> 1

            change += 1

        return change

    @staticmethod
    def _downscale(change: int, positive, negative):
        if change == 0:
            return

        if change < 0:
            # pylint: disable=broad-exception-raised
            raise Exception("Invalid change of scale")

        positive.downscale(change)
        negative.downscale(change)

    def _merge(
        self,
        previous_buckets: Buckets,
        current_buckets: Buckets,
        current_scale,
        min_scale,
        aggregation_temporality,
    ):
        current_change = current_scale - min_scale

        for current_bucket_index, current_bucket in enumerate(
            current_buckets.counts
        ):
            if current_bucket == 0:
                continue

            # Not considering the case where len(previous_buckets) == 0. This
            # would not happen because self._previous_point is only assigned to
            # an ExponentialHistogramDataPoint object if self._count != 0.

            current_index = current_buckets.index_base + current_bucket_index
            if current_index > current_buckets.index_end:
                current_index -= len(current_buckets.counts)

            index = current_index >> current_change

            if index < previous_buckets.index_start:
                span = previous_buckets.index_end - index

                if span >= self._max_size:
                    # pylint: disable=broad-exception-raised
                    raise Exception("Incorrect merge scale")

                if span >= len(previous_buckets.counts):
                    previous_buckets.grow(span + 1, self._max_size)

                previous_buckets.index_start = index

            if index > previous_buckets.index_end:
                span = index - previous_buckets.index_start

                if span >= self._max_size:
                    # pylint: disable=broad-exception-raised
                    raise Exception("Incorrect merge scale")

                if span >= len(previous_buckets.counts):
                    previous_buckets.grow(span + 1, self._max_size)

                previous_buckets.index_end = index

            bucket_index = index - previous_buckets.index_base

            if bucket_index < 0:
                bucket_index += len(previous_buckets.counts)

            if aggregation_temporality is AggregationTemporality.DELTA:
                current_bucket = -current_bucket

            previous_buckets.increment_bucket(
                bucket_index, increment=current_bucket
            )


class Aggregation(ABC):
    """
    Base class for all aggregation types.
    """

    @abstractmethod
    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        """Creates an aggregation"""


class DefaultAggregation(Aggregation):
    """
    The default aggregation to be used in a `View`.

    This aggregation will create an actual aggregation depending on the
    instrument type, as specified next:

    ==================================================== ====================================
    Instrument                                           Aggregation
    ==================================================== ====================================
    `opentelemetry.sdk.metrics.Counter`                  `SumAggregation`
    `opentelemetry.sdk.metrics.UpDownCounter`            `SumAggregation`
    `opentelemetry.sdk.metrics.ObservableCounter`        `SumAggregation`
    `opentelemetry.sdk.metrics.ObservableUpDownCounter`  `SumAggregation`
    `opentelemetry.sdk.metrics.Histogram`                `ExplicitBucketHistogramAggregation`
    `opentelemetry.sdk.metrics.ObservableGauge`          `LastValueAggregation`
    ==================================================== ====================================
    """

    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        # pylint: disable=too-many-return-statements
        if isinstance(instrument, Counter):
            return _SumAggregation(
                attributes,
                reservoir_builder=reservoir_factory(_SumAggregation),
                instrument_is_monotonic=True,
                instrument_aggregation_temporality=(
                    AggregationTemporality.DELTA
                ),
                start_time_unix_nano=start_time_unix_nano,
            )
        if isinstance(instrument, UpDownCounter):
            return _SumAggregation(
                attributes,
                reservoir_builder=reservoir_factory(_SumAggregation),
                instrument_is_monotonic=False,
                instrument_aggregation_temporality=(
                    AggregationTemporality.DELTA
                ),
                start_time_unix_nano=start_time_unix_nano,
            )

        if isinstance(instrument, ObservableCounter):
            return _SumAggregation(
                attributes,
                reservoir_builder=reservoir_factory(_SumAggregation),
                instrument_is_monotonic=True,
                instrument_aggregation_temporality=(
                    AggregationTemporality.CUMULATIVE
                ),
                start_time_unix_nano=start_time_unix_nano,
            )

        if isinstance(instrument, ObservableUpDownCounter):
            return _SumAggregation(
                attributes,
                reservoir_builder=reservoir_factory(_SumAggregation),
                instrument_is_monotonic=False,
                instrument_aggregation_temporality=(
                    AggregationTemporality.CUMULATIVE
                ),
                start_time_unix_nano=start_time_unix_nano,
            )

        if isinstance(instrument, Histogram):
            boundaries = instrument._advisory.explicit_bucket_boundaries
            return _ExplicitBucketHistogramAggregation(
                attributes,
                reservoir_builder=reservoir_factory(
                    _ExplicitBucketHistogramAggregation
                ),
                instrument_aggregation_temporality=(
                    AggregationTemporality.DELTA
                ),
                boundaries=boundaries,
                start_time_unix_nano=start_time_unix_nano,
            )

        if isinstance(instrument, ObservableGauge):
            return _LastValueAggregation(
                attributes,
                reservoir_builder=reservoir_factory(_LastValueAggregation),
            )

        if isinstance(instrument, _Gauge):
            return _LastValueAggregation(
                attributes,
                reservoir_builder=reservoir_factory(_LastValueAggregation),
            )

        # pylint: disable=broad-exception-raised
        raise Exception(f"Invalid instrument type {type(instrument)} found")


class ExponentialBucketHistogramAggregation(Aggregation):
    def __init__(
        self,
        max_size: int = 160,
        max_scale: int = 20,
    ):
        self._max_size = max_size
        self._max_scale = max_scale

    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED
        if isinstance(instrument, Synchronous):
            instrument_aggregation_temporality = AggregationTemporality.DELTA
        elif isinstance(instrument, Asynchronous):
            instrument_aggregation_temporality = (
                AggregationTemporality.CUMULATIVE
            )

        return _ExponentialBucketHistogramAggregation(
            attributes,
            reservoir_factory(_ExponentialBucketHistogramAggregation),
            instrument_aggregation_temporality,
            start_time_unix_nano,
            max_size=self._max_size,
            max_scale=self._max_scale,
        )


class ExplicitBucketHistogramAggregation(Aggregation):
    """This aggregation informs the SDK to collect:

    - Count of Measurement values falling within explicit bucket boundaries.
    - Arithmetic sum of Measurement values in population. This SHOULD NOT be collected when used with instruments that record negative measurements, e.g. UpDownCounter or ObservableGauge.
    - Min (optional) Measurement value in population.
    - Max (optional) Measurement value in population.


    Args:
        boundaries: Array of increasing values representing explicit bucket boundary values.
        record_min_max: Whether to record min and max.
    """

    def __init__(
        self,
        boundaries: Optional[Sequence[float]] = None,
        record_min_max: bool = True,
    ) -> None:
        self._boundaries = boundaries
        self._record_min_max = record_min_max

    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED
        if isinstance(instrument, Synchronous):
            instrument_aggregation_temporality = AggregationTemporality.DELTA
        elif isinstance(instrument, Asynchronous):
            instrument_aggregation_temporality = (
                AggregationTemporality.CUMULATIVE
            )

        if self._boundaries is None:
            self._boundaries = (
                instrument._advisory.explicit_bucket_boundaries
                or _DEFAULT_EXPLICIT_BUCKET_HISTOGRAM_AGGREGATION_BOUNDARIES
            )

        return _ExplicitBucketHistogramAggregation(
            attributes,
            instrument_aggregation_temporality,
            start_time_unix_nano,
            reservoir_factory(_ExplicitBucketHistogramAggregation),
            self._boundaries,
            self._record_min_max,
        )


class SumAggregation(Aggregation):
    """This aggregation informs the SDK to collect:

    - The arithmetic sum of Measurement values.
    """

    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        instrument_aggregation_temporality = AggregationTemporality.UNSPECIFIED
        if isinstance(instrument, Synchronous):
            instrument_aggregation_temporality = AggregationTemporality.DELTA
        elif isinstance(instrument, Asynchronous):
            instrument_aggregation_temporality = (
                AggregationTemporality.CUMULATIVE
            )

        return _SumAggregation(
            attributes,
            isinstance(instrument, (Counter, ObservableCounter)),
            instrument_aggregation_temporality,
            start_time_unix_nano,
            reservoir_factory(_SumAggregation),
        )


class LastValueAggregation(Aggregation):
    """
    This aggregation informs the SDK to collect:

    - The last Measurement.
    - The timestamp of the last Measurement.
    """

    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        return _LastValueAggregation(
            attributes,
            reservoir_builder=reservoir_factory(_LastValueAggregation),
        )


class DropAggregation(Aggregation):
    """Using this aggregation will make all measurements be ignored."""

    def _create_aggregation(
        self,
        instrument: Instrument,
        attributes: Attributes,
        reservoir_factory: Callable[
            [Type[_Aggregation]], ExemplarReservoirBuilder
        ],
        start_time_unix_nano: int,
    ) -> _Aggregation:
        return _DropAggregation(
            attributes, reservoir_factory(_DropAggregation)
        )