From 992aa5d6d4be2e70f5b740300d72d5437286c464 Mon Sep 17 00:00:00 2001 From: fei <204683769+feiiiiii5@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:01:36 +0800 Subject: [PATCH] fix: reject non-finite Score values --- py/src/braintrust/score.py | 11 +++++++++-- py/src/braintrust/test_score.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/py/src/braintrust/score.py b/py/src/braintrust/score.py index c9395c494..3ad297b6c 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 77cca41b3..76ba46869 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()