diff --git a/CHANGELOG.md b/CHANGELOG.md index dcf4ea81..85574f8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,16 @@ Each release links to full notes on the ## [Unreleased] +### Changed + +- **`ProcessEvaluation.non_matches` is `None` instead of `[]` when there are + no records and a `compare_with()` result had no `non_matches` key**, as + from `aggregate_from_comparisons()` or `update_from_comparison_result()` + on default `compare_with()` results. This is a breaking change: code that + iterates `non_matches` from those results now raises `TypeError`, and + `save_metrics()` writes `null` for it. Records that were collected are + still returned ([#425](https://github.com/awslabs/stickler/issues/425)). + ### Fixed - A `field_comparisons` row that meets its threshold only through the `1e-10` @@ -23,6 +33,10 @@ Each release links to full notes on the the threshold (`0.7996 < 0.8`, not `0.800 < 0.8`). Every row with the same verdict gets its reason from `ThresholdHelper.match_reason` ([#462](https://github.com/awslabs/stickler/issues/462)). +- The HTML report and the terminal printer no longer print "No non-matches + found." for a bulk run that has no records to show it. When documents + raised, both say how many could not be compared + ([#425](https://github.com/awslabs/stickler/issues/425)). ## [1.1.0] - 2026-12-04 diff --git a/docs/docs/Guides/Evaluation/bulk-evaluation.md b/docs/docs/Guides/Evaluation/bulk-evaluation.md index ab2add95..a220be38 100644 --- a/docs/docs/Guides/Evaluation/bulk-evaluation.md +++ b/docs/docs/Guides/Evaluation/bulk-evaluation.md @@ -127,7 +127,7 @@ final = evaluator.compute() | `field_metrics` | `dict` | Per-field metrics with the same confusion-matrix structure as `metrics`, plus `mean_score` (arithmetic mean of the per-document `threshold_applied_score` at that path) when that path was actually scored. Keyed by dotted field path (e.g., `"customer.name"`). | | `errors` | `list` | Records for any documents that raised exceptions during processing. | | `total_time` | `float` | Wall-clock time in seconds since the evaluator was created or last reset. | -| `non_matches` | `list` | Detailed non-match records (when `document_non_matches=True`), each tagged with `doc_id`. | +| `non_matches` | `list` or `None` | Detailed non-match records (when `document_non_matches=True`), each tagged with `doc_id`. `None` when no records were collected: `document_non_matches=False`, or no records and a `compare_with()` result without `non_matches`. | --- diff --git a/src/stickler/reporting/html/section_generator.py b/src/stickler/reporting/html/section_generator.py index f4311807..ccc014a8 100644 --- a/src/stickler/reporting/html/section_generator.py +++ b/src/stickler/reporting/html/section_generator.py @@ -117,6 +117,22 @@ def generate_non_matches(self, config: ReportConfig) -> str: return html_string if not non_matches: + # A document that raised was never compared, so it has no records + # and is not clean (#425). A failed accumulator is not counted: its + # document was compared. + failed = sum( + 1 + for error in getattr(self.results, "errors", None) or [] + if "accumulator" not in error + ) + if failed: + html_string += ( + "

No non-matches in the documents that were compared. " + f"{failed} could not be compared; see errors on " + "the results.

" + ) + return html_string + html_string += "

No non-matches found.

" return html_string diff --git a/src/stickler/reporting/html/utils/data_extractors.py b/src/stickler/reporting/html/utils/data_extractors.py index 79bf49e9..c87a4407 100644 --- a/src/stickler/reporting/html/utils/data_extractors.py +++ b/src/stickler/reporting/html/utils/data_extractors.py @@ -76,9 +76,9 @@ def extract_non_matches( records at all. `compare_with()` only writes the `non_matches` key when called with `document_non_matches=True`, and `ProcessEvaluation.non_matches` is None when the bulk evaluator was - built with `document_non_matches=False`, so an empty list and no - list mean different things and only the first one means the - document was clean. + built with `document_non_matches=False` or aggregated results without + the key, so an empty list and no list mean different things and only + the first one means the evaluated documents were clean. """ if isinstance(results, ProcessEvaluation): return results.non_matches diff --git a/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py b/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py index 02290427..f4829321 100644 --- a/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py +++ b/src/stickler/structured_object_evaluator/bulk_structured_model_evaluator.py @@ -292,6 +292,9 @@ def reset(self) -> None: # Non-match tracking (when document_non_matches=True) self._non_matches = [] + # Set once a comparison result carries no `non_matches` key, so an empty + # list no longer means that every field matched (#425) + self._non_matches_uncollected = False # Error tracking self._errors = [] @@ -436,11 +439,14 @@ def _accumulate_result( try: # Collect non-matches if enabled and present - if self.document_non_matches and "non_matches" in comparison_result: - for non_match in comparison_result["non_matches"]: - non_match_with_doc = non_match.copy() - non_match_with_doc["doc_id"] = doc_id - self._non_matches.append(non_match_with_doc) + if self.document_non_matches: + if "non_matches" in comparison_result: + for non_match in comparison_result["non_matches"]: + non_match_with_doc = non_match.copy() + non_match_with_doc["doc_id"] = doc_id + self._non_matches.append(non_match_with_doc) + else: + self._non_matches_uncollected = True cm_result = comparison_result["confusion_matrix"] self._accumulate_confusion_matrix(cm_result) @@ -782,13 +788,22 @@ def _build_process_evaluation(self) -> ProcessEvaluation: dict(self._accumulator_errors) if self._accumulator_errors else None ) + # `[]` claims that records were collected and none were produced, so it + # is None when a result carried no records. Records that were collected + # are kept either way. + non_matches = None + if self.document_non_matches and ( + self._non_matches or not self._non_matches_uncollected + ): + non_matches = list(self._non_matches) + return ProcessEvaluation( document_count=self._processed_count, metrics=overall_metrics, field_metrics=field_metrics, errors=list(self._errors), total_time=total_time, - non_matches=list(self._non_matches) if self.document_non_matches else None, + non_matches=non_matches, confidence_metrics=confidence_metrics, decision_metrics=( accumulator_metrics.get(self._decision_accumulator.name) diff --git a/src/stickler/structured_object_evaluator/utils/pretty_print.py b/src/stickler/structured_object_evaluator/utils/pretty_print.py index c4a1b2fe..3aa69ecb 100644 --- a/src/stickler/structured_object_evaluator/utils/pretty_print.py +++ b/src/stickler/structured_object_evaluator/utils/pretty_print.py @@ -1009,6 +1009,22 @@ def _print_no_non_matches( if isinstance(results, dict) and "overall_score" in results: message += " For an EvalResult's .raw, pass the EvalResult itself." print(_colorize(message, Colors.YELLOW, use_color)) + return + + # A document that raised was never compared, so it has no records and is + # not clean (#425). A failed accumulator is not counted: its document was + # compared. + failed = sum( + 1 + for error in getattr(results, "errors", None) or [] + if "accumulator" not in error + ) + if failed: + message = ( + "No non-matches in the documents that were compared. " + f"{failed} could not be compared; see errors on the results." + ) + print(_colorize(message, Colors.YELLOW, use_color)) else: print(_colorize("✅ No non-matches found.", Colors.GREEN, use_color)) diff --git a/tests/reporting/html/README.md b/tests/reporting/html/README.md index a3b1e1f3..39bfdbdc 100644 --- a/tests/reporting/html/README.md +++ b/tests/reporting/html/README.md @@ -40,9 +40,13 @@ Three states, and they must stay distinguishable: - `None`: no records collected. `compare_with()` writes the `non_matches` key only under `document_non_matches=True`, with or without `evaluator_format=True`, and `ProcessEvaluation.non_matches` is `None` when the bulk - evaluator was built with `document_non_matches=False`. Says nothing about whether fields + evaluator was built with `document_non_matches=False`, or has no records and was given a + result without the key (#425). Says nothing about whether fields matched, so the section reports the records as missing. -- `[]`: collected, none produced. The only state that may claim success. +- `[]`: collected, none produced. The only state that may claim success, and only when no document + raised: a document that raised was never compared (#425). An `errors` record with an + `accumulator` key does not count, since its document was compared. Under `elide_errors=True` a + document that raised leaves no record, so the section still claims success. - a populated list: rendered as the table, capped by `ReportConfig.max_non_matches_displayed`. The terminal printers in `structured_object_evaluator/utils/pretty_print.py` carry the same diff --git a/tests/reporting/html/test_html_non_match_records.py b/tests/reporting/html/test_html_non_match_records.py index 6d036488..5c007e20 100644 --- a/tests/reporting/html/test_html_non_match_records.py +++ b/tests/reporting/html/test_html_non_match_records.py @@ -15,8 +15,10 @@ from stickler.structured_object_evaluator import StructuredModel from stickler.structured_object_evaluator.bulk_structured_model_evaluator import ( BulkStructuredModelEvaluator, + aggregate_from_comparisons, ) from stickler.structured_object_evaluator.models.comparable_field import ComparableField +from stickler.structured_object_evaluator.utils.pretty_print import print_non_matches class _Person(StructuredModel): @@ -107,6 +109,118 @@ def test_a_bulk_result_with_records_lists_them(): assert "document_non_matches=True" not in _section(results) +def test_aggregating_results_without_records_is_not_reported_as_clean(capsys): + """#425: a missing `non_matches` key was read as "no non-matches".""" + gt, pred = _wrong_pair() + results = aggregate_from_comparisons( + [gt.compare_with(pred, include_confusion_matrix=True)] + ) + + assert results.non_matches is None + assert "No non-matches found" not in _section(results) + print_non_matches(results) + assert "No non-match records in these results." in capsys.readouterr().out + + +def test_one_result_without_records_is_enough_to_withhold_success(): + """A clean result with records says nothing about the one without them.""" + same = _Person(name="Ada", city="London") + gt, pred = _wrong_pair() + clean = same.compare_with( + same, include_confusion_matrix=True, document_non_matches=True + ) + missing = gt.compare_with(pred, include_confusion_matrix=True) + + assert aggregate_from_comparisons([clean, missing]).non_matches is None + assert aggregate_from_comparisons([missing, clean]).non_matches is None + + +def test_collected_records_survive_a_result_without_them(): + gt, pred = _wrong_pair() + recorded = gt.compare_with( + pred, include_confusion_matrix=True, document_non_matches=True + ) + missing = gt.compare_with(pred, include_confusion_matrix=True) + + results = aggregate_from_comparisons([missing, recorded]) + + assert [nm["field_path"] for nm in results.non_matches] == ["name"] + + +def test_aggregating_clean_results_with_records_is_a_success(): + same = _Person(name="Ada", city="London") + clean = same.compare_with( + same, include_confusion_matrix=True, document_non_matches=True + ) + + results = aggregate_from_comparisons([clean]) + + assert results.non_matches == [] + assert "

No non-matches found.

" in _section(results) + + +def test_reset_forgets_a_result_without_records(): + same = _Person(name="Ada", city="London") + evaluator = BulkStructuredModelEvaluator(target_schema=_Person) + evaluator.update_from_comparison_result( + same.compare_with(same, include_confusion_matrix=True) + ) + assert evaluator.compute().non_matches is None + + evaluator.reset() + evaluator.update(same, same) + + assert evaluator.compute().non_matches == [] + + +def test_a_bulk_run_where_every_document_raised_is_not_reported_as_clean(capsys): + """#425: documents that raised have no records because they were not compared.""" + evaluator = BulkStructuredModelEvaluator(target_schema=_Person) + evaluator.update(None, None, "doc-1") + evaluator.update(None, None, "doc-2") + results = evaluator.compute() + + assert len(results.errors) == 2 + assert results.non_matches == [] + + html = _section(results) + assert "No non-matches found" not in html + assert "2 could not be compared" in html + + print_non_matches(results) + out = capsys.readouterr().out + assert "No non-matches found" not in out + assert "2 could not be compared" in out + + +class _FailingAccumulator: + name = "failing" + + def reset(self): + pass + + def accumulate(self, comparison_result, prediction_raw): + raise RuntimeError("accumulator failed") + + def compute(self): + return None + + +def test_a_failed_accumulator_does_not_withhold_success(capsys): + """Its document was compared, and the records say it was clean.""" + same = _Person(name="Ada", city="London") + evaluator = BulkStructuredModelEvaluator( + target_schema=_Person, accumulators=[_FailingAccumulator()] + ) + evaluator.update(same, same) + results = evaluator.compute() + + assert len(results.errors) == 1 + assert "

No non-matches found.

" in _section(results) + print_non_matches(results) + assert "No non-matches found." in capsys.readouterr().out + + def test_an_evaluator_format_dict_without_records_says_so(): """Its `non_matches` key is absent, so the report says "not collected" (#608).