Skip to content

Commit b727e66

Browse files
committed
Parse the native histogram sum as a float
_parse_nh_struct parsed the sum field with int(), so a native histogram whose sum is not integral failed to parse with ValueError: invalid literal for int() with base 10: '100.5' NativeHistogram.sum_value is a float and the OpenMetrics writer emits the sum verbatim (e.g. sum:100.5), so the library could not parse its own output for the common case of a non-integer sum. Parse sum with float() to match; count, schema and zero_count remain int as they are genuinely integers. Add test_native_histogram_float_sum, which parses a native histogram with a fractional sum and checks it round-trips to sum_value 100.5. Signed-off-by: Sean Kim <skim8705@gmail.com>
1 parent a96f6f4 commit b727e66

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

prometheus_client/openmetrics/parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,7 @@ def _parse_nh_struct(text):
315315
deltas = dict(re_deltas.findall(text))
316316

317317
count_value = int(items['count'])
318-
sum_value = int(items['sum'])
318+
sum_value = float(items['sum'])
319319
schema = int(items['schema'])
320320
zero_threshold = float(items['zero_threshold'])
321321
zero_count = int(items['zero_count'])

tests/openmetrics/test_parser.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,18 @@ def test_native_histogram(self):
218218
hfm.add_sample("nativehistogram", None, None, None, None, NativeHistogram(24, 100, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
219219
self.assertEqual([hfm], families)
220220

221+
def test_native_histogram_float_sum(self):
222+
families = text_string_to_metric_families("""# TYPE nativehistogram histogram
223+
# HELP nativehistogram Is a basic example of a native histogram
224+
nativehistogram {count:24,sum:100.5,schema:0,zero_threshold:0.001,zero_count:4,positive_spans:[0:2,1:2],negative_spans:[0:2,1:2],positive_deltas:[2,1,-3,3],negative_deltas:[2,1,-2,3]}
225+
# EOF
226+
""")
227+
families = list(families)
228+
229+
hfm = HistogramMetricFamily("nativehistogram", "Is a basic example of a native histogram")
230+
hfm.add_sample("nativehistogram", None, None, None, None, NativeHistogram(24, 100.5, 0, 0.001, 4, (BucketSpan(0, 2), BucketSpan(1, 2)), (BucketSpan(0, 2), BucketSpan(1, 2)), (2, 1, -3, 3), (2, 1, -2, 3)))
231+
self.assertEqual([hfm], families)
232+
221233
def test_native_histogram_utf8(self):
222234
families = text_string_to_metric_families("""# TYPE "native{histogram" histogram
223235
# HELP "native{histogram" Is a basic example of a native histogram

0 commit comments

Comments
 (0)