diff --git a/pyrit/score/scorer_evaluation/scorer_metrics.py b/pyrit/score/scorer_evaluation/scorer_metrics.py index 9b41e722d5..f809c81e58 100644 --- a/pyrit/score/scorer_evaluation/scorer_metrics.py +++ b/pyrit/score/scorer_evaluation/scorer_metrics.py @@ -4,6 +4,7 @@ from __future__ import annotations import json +import math from dataclasses import asdict, dataclass, field from typing import TYPE_CHECKING, Any, Generic, TypeVar @@ -21,6 +22,37 @@ M = TypeVar("M", bound="ScorerMetrics") +def non_finite_to_none(value: Any) -> Any: + """ + Return a copy of ``value`` in which every non-finite float has become ``None``. + + JSON (RFC 8259) has no number for ``NaN`` or ``Infinity``, but ``json.dumps`` writes them as + the bare tokens ``NaN`` / ``Infinity`` by default. Python reads those back, so a metrics file + written this way looks round-trip safe here while strict parsers reject the whole document: + ``JSON.parse`` in JavaScript, and the .NET and Go standard JSON libraries both fail on it (jq + accepts the tokens only as a documented extension). An undefined statistic therefore has to be + serialized as ``null``, which is what this maps them to. + + Args: + value (Any): A metrics value: a scalar, or a dict / list / tuple / numpy array of them. + + Returns: + Any: The value with ``NaN`` and ``±inf`` replaced by ``None``. Numpy arrays become nested + lists, which is the shape ``to_json`` already writes for them. + """ + if isinstance(value, np.ndarray): + return [non_finite_to_none(item) for item in value.tolist()] + if isinstance(value, np.generic): + value = value.item() + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, dict): + return {key: non_finite_to_none(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [non_finite_to_none(item) for item in value] + return value + + def _json_default(value: Any) -> Any: """ Encode numpy arrays and scalars as plain JSON lists and numbers. @@ -78,13 +110,14 @@ def to_json(self) -> str: JSON lists. Returns: - str: The JSON string representation of the metrics. + str: The JSON string representation of the metrics. A statistic that is undefined + (``NaN``) is written as ``null``, because JSON has no literal for it. Raises: TypeError: If a field holds a value that is neither JSON-serializable nor a numpy array or scalar. """ - return json.dumps(asdict(self), default=_json_default) + return json.dumps(non_finite_to_none(asdict(self)), default=_json_default, allow_nan=False) @classmethod def from_json_file(cls: type[T], file_path: str | Path) -> T: @@ -143,10 +176,13 @@ class HarmScorerMetrics(ScorerMetrics): indicates that the model scores are typically higher than the human scores. When the model perfectly agrees with the gold labels (zero difference everywhere), this is reported as 0.0. When all differences are equal and non-zero (a systematic constant bias with no variance), the t-test is undefined and this - is reported as NaN; consult `mean_absolute_error` for the bias magnitude in that case. + is reported as NaN; consult `mean_absolute_error` for the bias magnitude in that case. NaN is the + in-memory signal only: it is not JSON-representable, so a round trip through `to_json`, + `from_json_file`, or the metrics registry gives ``None`` for this field instead. p_value (float): The p-value for the one-sample t-test above. It represents the probability of obtaining a difference in means as extreme as the observed difference, assuming the null hypothesis is true. - Reported as 1.0 on perfect agreement and NaN on the constant-non-zero-bias case (see `t_statistic`). + Reported as 1.0 on perfect agreement and NaN on the constant-non-zero-bias case (see `t_statistic`, + whose round-trip note applies here too). krippendorff_alpha_combined (float): Krippendorff's alpha for the reliability data, which includes both human and model scores. This measures the agreement between all the human raters and model scoring trials and ranges between -1.0 to 1.0 where 1.0 indicates perfect agreement, 0.0 indicates no agreement, and @@ -183,8 +219,8 @@ class HarmScorerMetrics(ScorerMetrics): mean_absolute_error: float mae_standard_error: float - t_statistic: float - p_value: float + t_statistic: float | None + p_value: float | None krippendorff_alpha_combined: float harm_category: str | None = field(default=None, kw_only=True) harm_definition: str | None = field(default=None, kw_only=True) diff --git a/pyrit/score/scorer_evaluation/scorer_metrics_io.py b/pyrit/score/scorer_evaluation/scorer_metrics_io.py index 021735dc22..0ec19239be 100644 --- a/pyrit/score/scorer_evaluation/scorer_metrics_io.py +++ b/pyrit/score/scorer_evaluation/scorer_metrics_io.py @@ -12,7 +12,7 @@ import secrets import stat import threading -from dataclasses import asdict +from dataclasses import MISSING, asdict, fields from pathlib import Path from typing import Any, TypeVar @@ -26,6 +26,7 @@ ObjectiveScorerMetrics, ScorerMetrics, ScorerMetricsWithIdentity, + non_finite_to_none, ) logger = logging.getLogger(__name__) @@ -49,6 +50,13 @@ def _metrics_to_registry_dict(metrics: ScorerMetrics) -> dict[str, Any]: Excludes: - trial_scores (too large for registry storage) - Internal fields starting with '_' + - None values for fields with defaults + + A statistic that is not a number (``NaN``) is kept, written as ``None`` so it serializes to + JSON ``null``: it carries the information that the value is undefined, which dropping the key + would lose, and the loading side declares those fields ``float | None``. + Required fields retain ``None`` when loaded metrics are saved again, so the entry can still + be loaded through the metrics constructor. Args: metrics (ScorerMetrics): The metrics object to convert. @@ -58,7 +66,17 @@ def _metrics_to_registry_dict(metrics: ScorerMetrics) -> dict[str, Any]: """ metrics_dict = asdict(metrics) excluded_keys = {"trial_scores"} - return {k: v for k, v in metrics_dict.items() if k not in excluded_keys and v is not None and not k.startswith("_")} + required_keys = { + metric_field.name + for metric_field in fields(metrics) + if metric_field.init and metric_field.default is MISSING and metric_field.default_factory is MISSING + } + kept = { + k: v + for k, v in metrics_dict.items() + if k not in excluded_keys and not k.startswith("_") and (v is not None or k in required_keys) + } + return non_finite_to_none(kept) def get_all_objective_metrics( @@ -327,7 +345,9 @@ def _append_jsonl_entry(file_path: Path, lock: threading.Lock, entry: dict[str, try: file_path.parent.mkdir(parents=True, exist_ok=True) with open(file_path, "a", encoding="utf-8") as f: - f.write(json.dumps(entry) + "\n") + # allow_nan=False: the registry is checked-in data that other tools read, and the + # bare NaN token json.dumps would emit for it is not JSON. + f.write(json.dumps(entry, allow_nan=False) + "\n") except Exception as e: logger.error(f"Failed to write to registry {file_path}: {e}") raise @@ -510,7 +530,7 @@ def replace_evaluation_results( output_lines = [*preserved] if output_lines and not output_lines[-1].endswith(("\n", "\r")): output_lines[-1] += line_ending - output_lines.append(json.dumps(new_entry) + line_ending) + output_lines.append(json.dumps(new_entry, allow_nan=False) + line_ending) # Rewrite the file with the surviving lines plus the new entry _rewrite_jsonl_atomically(file_path, output_lines) diff --git a/tests/unit/score/test_scorer_metrics.py b/tests/unit/score/test_scorer_metrics.py index e3fd298b42..4c2ddfb68f 100644 --- a/tests/unit/score/test_scorer_metrics.py +++ b/tests/unit/score/test_scorer_metrics.py @@ -668,3 +668,59 @@ def test_replace_preserves_other_entries(self, tmp_path): assert scorer2.hash in hashes assert hashes[scorer1.hash]["metrics"]["accuracy"] == 0.95 assert hashes[scorer2.hash]["metrics"]["accuracy"] == 0.85 + + +def _reject_constant(token: str): + """Refuse the ``NaN``/``Infinity`` tokens the way a strict JSON reader (``JSON.parse``) does.""" + raise ValueError(f"Not valid JSON (RFC 8259): bare {token} token") + + +def test_harm_metrics_to_json_writes_null_for_undefined_statistics(tmp_path): + """A statistic that is undefined (NaN) has no JSON number, so it must be written as null.""" + metrics = HarmScorerMetrics( + num_responses=2, + num_human_raters=2, + mean_absolute_error=0.05, + mae_standard_error=0.0, + t_statistic=float("nan"), + p_value=float("nan"), + krippendorff_alpha_combined=0.77, + trial_scores=np.array([[0.15, float("nan")]]), + ) + + json_str = metrics.to_json() + + assert "NaN" not in json_str + data = json.loads(json_str, parse_constant=_reject_constant) + assert data["t_statistic"] is None + assert data["p_value"] is None + assert data["trial_scores"] == [[0.15, None]] + + file_path = tmp_path / "metrics.json" + file_path.write_text(json_str, encoding="utf-8") + loaded = HarmScorerMetrics.from_json_file(str(file_path)) + assert loaded.t_statistic is None + assert loaded.p_value is None + + +def test_to_json_flattens_numpy_scalars_and_drops_infinite_ones(): + """ + ``ScorerEvaluator._compute_metrics`` hands over numpy scalars (``np.mean`` and friends), so the + serialization boundary has to flatten them and treat a non-finite one like any other NaN. + """ + metrics = HarmScorerMetrics( + num_responses=2, + num_human_raters=2, + mean_absolute_error=np.float64(0.05), + mae_standard_error=np.float64(0.0), + t_statistic=np.float64("inf"), + p_value=np.float64("nan"), + krippendorff_alpha_combined=np.float64(0.77), + ) + + data = json.loads(metrics.to_json(), parse_constant=_reject_constant) + + assert data["mean_absolute_error"] == 0.05 + assert data["krippendorff_alpha_combined"] == 0.77 + assert data["t_statistic"] is None + assert data["p_value"] is None diff --git a/tests/unit/score/test_scorer_metrics_io.py b/tests/unit/score/test_scorer_metrics_io.py index 4d68eeaac0..a73c484c39 100644 --- a/tests/unit/score/test_scorer_metrics_io.py +++ b/tests/unit/score/test_scorer_metrics_io.py @@ -5,6 +5,7 @@ import json import os import stat +from collections.abc import Callable from pathlib import Path from unittest.mock import patch @@ -799,5 +800,49 @@ def test_cleanup_failure_is_logged_without_masking_replace_error( assert len(staging_paths) == 1 staging_path = staging_paths[0] assert [call.args[0] for call in unlink.call_args_list] == [staging_path] * len(unlink_errors) + assert [call.args[0] for call in unlink.call_args_list] == [staging_path] * len(unlink_errors) assert caplog.messages == [f"Failed to clean up staging file {staging_path}: cleanup failed"] staging_path.unlink() + + +def _reject_constant(token: str): + """Refuse the ``NaN``/``Infinity`` tokens the way a strict JSON reader (``JSON.parse``) does.""" + raise ValueError(f"Not valid JSON (RFC 8259): bare {token} token") + + +@pytest.mark.parametrize("write", [add_evaluation_results, replace_evaluation_results], ids=["add", "replace"]) +def test_registry_entry_with_undefined_statistics_is_valid_json(*, tmp_path: Path, write: Callable[..., None]) -> None: + """ + A t-test that is undefined is reported as NaN by the evaluator (see ``ScorerMetrics`` docs). + Writing that through ``json.dumps`` emits the bare ``NaN`` token, which is not JSON, so the + checked-in registry stops being readable by strict parsers (``JSON.parse``, .NET, Go). + """ + path = tmp_path / "harm" / "probe_metrics.jsonl" + identifier = _make_identifier() + metrics = _make_harm_metrics(t_statistic=float("nan"), p_value=float("nan")) + + write(file_path=path, scorer_identifier=identifier, eval_hash="nan-hash", metrics=metrics) + + raw = path.read_text(encoding="utf-8").strip() + assert "NaN" not in raw + json.loads(raw, parse_constant=_reject_constant) + + # The row must still load back as a metrics object, not be dropped by the missing-key filter. + loaded = find_harm_metrics_by_eval_hash(eval_hash="nan-hash", file_path=path) + assert loaded is not None + assert loaded.t_statistic is None + assert loaded.p_value is None + assert loaded.mean_absolute_error == 0.08 + + saved_path = tmp_path / "harm" / "saved_metrics.jsonl" + write(file_path=saved_path, scorer_identifier=identifier, eval_hash="nan-hash", metrics=loaded) + + saved_data = json.loads(saved_path.read_text(encoding="utf-8").strip(), parse_constant=_reject_constant) + assert saved_data["metrics"]["t_statistic"] is None + assert saved_data["metrics"]["p_value"] is None + + reloaded = find_harm_metrics_by_eval_hash(eval_hash="nan-hash", file_path=saved_path) + assert reloaded is not None + assert reloaded.t_statistic is None + assert reloaded.p_value is None + assert reloaded.mean_absolute_error == 0.08