From efb93771e5544807712769dfa96f9f5e07a2992e Mon Sep 17 00:00:00 2001 From: biefan Date: Sat, 5 Dec 2026 08:49:29 +0800 Subject: [PATCH] FIX: Keep valid scorer metrics accessible after malformed registry records --- .../scorer_evaluation/scorer_metrics_io.py | 11 ++++++++-- tests/unit/score/test_scorer_metrics_io.py | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/pyrit/score/scorer_evaluation/scorer_metrics_io.py b/pyrit/score/scorer_evaluation/scorer_metrics_io.py index a7d532ba6e..0059f4e862 100644 --- a/pyrit/score/scorer_evaluation/scorer_metrics_io.py +++ b/pyrit/score/scorer_evaluation/scorer_metrics_io.py @@ -267,7 +267,6 @@ def _find_metrics_by_eval_hash( return metrics_class(**metrics_dict) except Exception as e: logger.warning(f"Failed to parse metrics for eval_hash {eval_hash}: {e}") - return None return None @@ -332,9 +331,17 @@ def _load_jsonl(file_path: Path) -> list[dict[str, Any]]: line = line.strip() if line: try: - entries.append(json.loads(line)) + entry = json.loads(line) except json.JSONDecodeError as e: logger.warning(f"Invalid JSON at line {line_num} in {file_path}: {e}") + continue + if not isinstance(entry, dict) or not isinstance(entry.get("metrics", {}), dict): + logger.warning( + f"Invalid registry entry at line {line_num} in {file_path}: expected a JSON object " + "with object-valued metrics" + ) + continue + entries.append(entry) except Exception as e: logger.error(f"Failed to load registry from {file_path}: {e}") diff --git a/tests/unit/score/test_scorer_metrics_io.py b/tests/unit/score/test_scorer_metrics_io.py index fd90a45445..067dda79e8 100644 --- a/tests/unit/score/test_scorer_metrics_io.py +++ b/tests/unit/score/test_scorer_metrics_io.py @@ -198,6 +198,26 @@ def test_find_objective_metrics_by_eval_hash_found(tmp_path): assert result.accuracy == 0.88 +@pytest.mark.parametrize( + "invalid_record", + [None, [], {"eval_hash": "wanted", "metrics": None}, {"eval_hash": "wanted", "metrics": {}}], + ids=["null-record", "array-record", "null-metrics", "missing-required-metrics"], +) +def test_registry_reads_skip_unusable_records(tmp_path: Path, invalid_record) -> None: + path = tmp_path / "metrics.jsonl" + path.write_text(json.dumps(invalid_record) + "\n", encoding="utf-8") + metrics = _make_objective_metrics(accuracy=0.88) + add_evaluation_results(file_path=path, scorer_identifier=_make_identifier(), eval_hash="wanted", metrics=metrics) + original = path.read_bytes() + + entries = get_all_objective_metrics(file_path=path) + assert [entry.metrics.accuracy for entry in entries] == [0.88] + match = find_objective_metrics_by_eval_hash(file_path=path, eval_hash="wanted") + assert match is not None + assert match.accuracy == 0.88 + assert path.read_bytes() == original + + def test_find_objective_metrics_reads_entries_recorded_before_the_baseline_fields(tmp_path): identifier = _make_identifier() entry = identifier.model_dump()