diff --git a/py/src/braintrust/score.py b/py/src/braintrust/score.py index c9395c49..3ad297b6 100644 --- a/py/src/braintrust/score.py +++ b/py/src/braintrust/score.py @@ -1,5 +1,6 @@ import dataclasses import inspect +import math import warnings from abc import ABC, abstractmethod from collections.abc import Mapping @@ -45,8 +46,14 @@ def as_dict(self): } def __post_init__(self): - if self.score is not None and (self.score < 0 or self.score > 1): - raise ValueError(f"score ({self.score}) must be between 0 and 1") + if self.score is not None: + # bool is a supported scorer return (OneOrMoreScores includes bool), so + # it intentionally passes through here; only reject non-finite floats, + # which silently poison downstream averages. + if isinstance(self.score, float) and not math.isfinite(self.score): + raise ValueError(f"score ({self.score}) must be a finite number between 0 and 1") + if self.score < 0 or self.score > 1: + raise ValueError(f"score ({self.score}) must be between 0 and 1") if self.error is not None: warnings.warn( "The error field is deprecated, as errors are now propagated to the caller." diff --git a/py/src/braintrust/test_score.py b/py/src/braintrust/test_score.py index 77cca41b..76ba4686 100644 --- a/py/src/braintrust/test_score.py +++ b/py/src/braintrust/test_score.py @@ -181,5 +181,21 @@ def test_validation_requires_non_empty_id(self): Classification(id="") +class TestScoreValidation(unittest.TestCase): + def test_rejects_non_finite_values(self): + for invalid in (float("nan"), float("inf"), -float("inf")): + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + Score(name="invalid", score=invalid) + + def test_accepts_and_round_trips_valid_values(self): + # bool is a supported scorer return (OneOrMoreScores includes bool) and + # must keep working; the old range-only check accepted it. + for valid in (0, 1, 0.5, True, False): + with self.subTest(valid=valid): + score = Score(name="valid", score=valid) + self.assertEqual(score.as_dict()["score"], valid) + self.assertEqual(Score.from_dict(score.as_dict()).score, valid) + + if __name__ == "__main__": unittest.main()