diff --git a/prometheus_client/openmetrics/parser.py b/prometheus_client/openmetrics/parser.py index ebd6da10..e2000286 100644 --- a/prometheus_client/openmetrics/parser.py +++ b/prometheus_client/openmetrics/parser.py @@ -105,6 +105,17 @@ def _parse_timestamp(timestamp): return ts +def _timestamp_is_after(a, b): + """Return whether timestamp a is later than timestamp b. + + _parse_timestamp returns a Timestamp for fixed-point values and a float + for exponent notation, so the two can be mixed within a group. + """ + if isinstance(a, Timestamp) and isinstance(b, Timestamp): + return a > b + return float(a) > float(b) + + def _is_character_escaped(s, charpos): num_bslashes = 0 while (charpos > num_bslashes @@ -617,7 +628,7 @@ def build_metric(name, documentation, typ, unit, samples): if group is not None and g == group: if (sample.timestamp is None) != (group_timestamp is None): raise ValueError("Mix of timestamp presence within a group: " + line) - if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info': + if group_timestamp is not None and _timestamp_is_after(group_timestamp, sample.timestamp) and typ != 'info': raise ValueError("Timestamps went backwards within a group: " + line) else: group_timestamp_samples = set() diff --git a/tests/openmetrics/test_parser.py b/tests/openmetrics/test_parser.py index 78b7af83..46bcb272 100644 --- a/tests/openmetrics/test_parser.py +++ b/tests/openmetrics/test_parser.py @@ -664,6 +664,20 @@ def test_timestamps(self): b.add_metric([], 2, timestamp=Timestamp(1234567890, 0)) self.assertEqual([a, b], list(families)) + def test_mixed_timestamp_formats(self): + families = text_string_to_metric_families("""# TYPE a gauge +# HELP a help +a 1 1 +a 2 1.5e0 +a 3 2.5 +# EOF +""") + a = GaugeMetricFamily("a", "help") + a.add_sample("a", {}, 1, Timestamp(1, 0)) + a.add_sample("a", {}, 2, 1.5) + a.add_sample("a", {}, 3, Timestamp(2, 500000000)) + self.assertEqual([a], list(families)) + def test_hash_in_label_value(self): families = text_string_to_metric_families("""# TYPE a counter # HELP a help @@ -958,6 +972,8 @@ def test_invalid_input(self): ('# TYPE a gauge\na 0 1\na 0 -1\n# EOF\n'), ('# TYPE a gauge\na 0 1.1\na 0 1\n# EOF\n'), ('# TYPE a gauge\na 0 1\na 0 0\n# EOF\n'), + ('# TYPE a gauge\na 0 2\na 0 1.5e0\n# EOF\n'), + ('# TYPE a gauge\na 0 2e0\na 0 1.5\n# EOF\n'), ('# TYPE a gauge\na 0\na 0 0\n# EOF\n'), ('# TYPE a gauge\na 0 0\na 0\n# EOF\n'), # Clashing names.