From 348dc59bfcf1c3bc3e17bb2007513db390f49e26 Mon Sep 17 00:00:00 2001 From: hugosmoreira Date: Sat, 19 Sep 2026 21:58:58 -0700 Subject: [PATCH 1/5] fix: report refused list elements with field comparison rules Signed-off-by: hugosmoreira --- CHANGELOG.md | 43 +--- docs/docs/Guides/Comparators/README.md | 17 +- .../models/comparison_helper_base.py | 50 +++- .../models/field_comparison_collector.py | 5 +- .../models/non_match_collector.py | 5 +- .../models/non_matches_helper.py | 34 ++- tests/structured_object_evaluator/README.md | 9 + .../test_nested_plain_basemodel.py | 49 +--- tests/test_list_reporting.py | 238 ++++++++++++++++++ 9 files changed, 348 insertions(+), 102 deletions(-) create mode 100644 tests/structured_object_evaluator/README.md create mode 100644 tests/test_list_reporting.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e4e8ad36..ccc00f3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ Each release links to full notes on the ## [Unreleased] +### Fixed + +- List reporting ([#332](https://github.com/awslabs/stickler/issues/332)): + `non_matches` and `field_comparisons` now use the configured comparator, + class gate, and field threshold for primitive and plain-model lists. Rejected + pairs produce an indexed false-discovery record instead of disappearing; + reordered pair indices and reported similarities also follow that comparator. + Scores and confusion-matrix counts are unchanged. Structured-model lists + retain recursive matching and their element-model threshold. + ## [1.0.0] - 2026-09-11 ### Added @@ -829,36 +839,9 @@ Each release links to full notes on the gate takes a `warn` flag, probing is silent, and the warnings are replayed on the pairs the matcher selected. - **Known gap: a refused list element is counted but not reported.** There is a - sixth reader of the pair question and it is the one that cannot consult the - gate. The confusion-matrix counts come through the wrapped comparator; the - item-level report comes through `ComparisonHelperBase.get_optimal_assignments`, - which runs its own `HungarianHelper.get_complete_matching_info(gt_list, - pred_list)` with no comparator argument at all. It therefore scores a refused - pair as a match and emits nothing, so the counts and the report disagree: - - ``` - f: Optional[List[Any]] = ComparableField(comparator=ANLSStarComparator()) - [Plain(sku='a')] vs [Cat(sku='a')] - - dev here - field_scores {'f': 1.0} {'f': 0.0} - f counts tp=1 fd=0 tp=0 fd=1 - non_matches [] [] <- an fd with no record - ``` - - An ordinary below-threshold element IS documented, so the omission is specific - to a refusal, and a user has no way to find out why the field lost a point. - Widening the `isinstance(gt_list[0], StructuredModel)` guard that skips - item-level collection for plain-model lists is not sufficient -- verified -- and - the actual fix is to thread the field's comparator into - `get_optimal_assignments`, a shared template-method base with two subclasses and - two collectors whose `non_matches` output would change for every list of plain - models. That is a reporting change with its own blast radius, so it is declared - and tracked in [#332](https://github.com/awslabs/stickler/issues/332) rather - than smuggled in here. Tests pin the disagreement so it cannot widen unnoticed, - including one asserting an ordinary below-threshold element IS still reported, - so the gap cannot read as larger than it is. + This release left a reporting gap: a refused list element contributed a false + discovery but no item-level record. The reporting fix for + [#332](https://github.com/awslabs/stickler/issues/332) is listed under Unreleased. Refusing is deliberate rather than conservative. The scalar default is edit distance over the rendered form, and because the field names are identical on diff --git a/docs/docs/Guides/Comparators/README.md b/docs/docs/Guides/Comparators/README.md index 43b5b444..f09d345e 100644 --- a/docs/docs/Guides/Comparators/README.md +++ b/docs/docs/Guides/Comparators/README.md @@ -611,20 +611,19 @@ accepts. Stickler warns once per field rather than raising, because which class arrives is a property of the prediction, and raising would end a bulk run partway through. -!!! warning "A refused list element is counted but not reported" +!!! note "Rejected list elements are included in reports" - A refused element is one `fd` in the confusion matrix, but it produces no - entry in `non_matches`, so the counts and the item-level report disagree: + A rejected pair contributes one `fd` in the confusion matrix and an indexed + entry in `non_matches`. With `document_field_comparisons=True`, its row has + `match=False` and `score=0.0`: ``` - [Plain(sku='a')] vs [Cat(sku='a')] -> fd=1, non_matches: [] + [Plain(sku='a')] vs [Cat(sku='a')] -> fd=1, non_matches: f[0] ``` - An ordinary below-threshold element *is* reported, so this is specific to a - refusal. The item-level report re-derives its own pairing without the field's - comparator, which is why it cannot see the refusal. Read the counts, not - `non_matches`, when you need to know whether a list element was refused. - Tracked in [#332](https://github.com/awslabs/stickler/issues/332). + Both reports use the field's comparator and threshold for plain-model and + primitive lists. Structured-model lists retain recursive matching and the + element model's `match_threshold`. ### The annotation has to name the model diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index 479b5581..74004f39 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -4,6 +4,10 @@ from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional +from stickler.algorithms.hungarian import HungarianMatcher +from stickler.comparators.base import BaseComparator + +from .comparison_helper import _ClassGatedComparator, _holds_a_plain_model from .hungarian_helper import HungarianHelper DEFAULT_MATCH_THRESHOLD = 0.7 @@ -36,12 +40,16 @@ def get_match_threshold(self, obj_list: List[Any]) -> float: return obj_list[0].__class__.match_threshold return DEFAULT_MATCH_THRESHOLD - def get_optimal_assignments(self, gt_list: List[Any], pred_list: List[Any]) -> tuple: + def get_optimal_assignments( + self, gt_list: List[Any], pred_list: List[Any], + comparator: Optional[BaseComparator] = None, + ) -> tuple: """Get optimal assignments and matched pairs with scores. Args: gt_list: Ground truth list pred_list: Prediction list + comparator: Field comparator for non-structured list elements. Returns: Tuple of (assignments, matched_pairs_with_scores) @@ -50,9 +58,20 @@ def get_optimal_assignments(self, gt_list: List[Any], pred_list: List[Any]) -> t matched_pairs_with_scores = [] if gt_list and pred_list: - hungarian_info = self.hungarian_helper.get_complete_matching_info( - gt_list, pred_list - ) + if comparator is None: + hungarian_info = self.hungarian_helper.get_complete_matching_info( + gt_list, pred_list + ) + else: + # Mirror scoring: comparators receive raw values, and plain + # models pass through the same class gate. Probing stays silent; + # the scoring run already warned about selected refused pairs. + if _holds_a_plain_model(gt_list) or _holds_a_plain_model(pred_list): + comparator = _ClassGatedComparator(comparator) + matcher = HungarianMatcher( + comparator, match_threshold=0.0, normalize_values=False + ) + hungarian_info = matcher.calculate_metrics(gt_list, pred_list) matched_pairs_with_scores = hungarian_info["matched_pairs"] assignments = [(i, j) for i, j, _ in matched_pairs_with_scores] @@ -292,7 +311,9 @@ def _extract_entries_from_objects( pass def collect_list_entries( - self, field_name: str, gt_list: List[Any], pred_list: List[Any] + self, field_name: str, gt_list: List[Any], pred_list: List[Any], + comparator: Optional[BaseComparator] = None, + match_threshold: Optional[float] = None, ) -> List[Dict[str, Any]]: """Collect entries from a list field using the template method pattern. @@ -300,6 +321,8 @@ def collect_list_entries( field_name: Name of the list field gt_list: Ground truth list pred_list: Prediction list + comparator: Field comparator for non-structured list elements. + match_threshold: Field threshold for non-structured list elements. Returns: List of entries with individual information @@ -309,10 +332,19 @@ def collect_list_entries( if not gt_list and not pred_list: return entries - # Get optimal assignments with scores - assignments, matched_pairs_with_scores = self.get_optimal_assignments(gt_list, pred_list) - - match_threshold = self.get_match_threshold(gt_list or pred_list) + from .structured_model import StructuredModel + + # The dispatcher routes by the first GT element. Structured lists use + # recursive model comparison and the element model's threshold, not the + # parent field's comparator/threshold. + if gt_list and isinstance(gt_list[0], StructuredModel): + comparator = None + match_threshold = None + assignments, matched_pairs_with_scores = self.get_optimal_assignments( + gt_list, pred_list, comparator + ) + if match_threshold is None: + match_threshold = self.get_match_threshold(gt_list or pred_list) entries.extend(self.process_matched_pairs( field_name, gt_list, pred_list, matched_pairs_with_scores, match_threshold diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index b17c45d3..0432c667 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -93,8 +93,11 @@ def collect_field_comparisons( and isinstance(pred_val, list) ): # Use FieldComparisonHelper for primitive list collection + info = self.model._get_comparison_info(field_name) list_comparisons = self.helper.collect_list_entries( - field_name, gt_val, pred_val + field_name, gt_val, pred_val, + comparator=info.comparator, + match_threshold=info.threshold, ) all_field_comparisons.extend(list_comparisons) diff --git a/src/stickler/structured_object_evaluator/models/non_match_collector.py b/src/stickler/structured_object_evaluator/models/non_match_collector.py index 79a79c77..c09d9064 100644 --- a/src/stickler/structured_object_evaluator/models/non_match_collector.py +++ b/src/stickler/structured_object_evaluator/models/non_match_collector.py @@ -103,8 +103,11 @@ def collect_enhanced_non_matches( and isinstance(pred_val, list) ): # Use NonMatchesHelper for object-level collection + info = self.model._get_comparison_info(field_name) object_non_matches = self.helper.collect_list_non_matches( - field_name, gt_val, pred_val + field_name, gt_val, pred_val, + comparator=info.comparator, + match_threshold=info.threshold, ) all_non_matches.extend(object_non_matches) diff --git a/src/stickler/structured_object_evaluator/models/non_matches_helper.py b/src/stickler/structured_object_evaluator/models/non_matches_helper.py index 8ec1ccd1..8c9f5503 100644 --- a/src/stickler/structured_object_evaluator/models/non_matches_helper.py +++ b/src/stickler/structured_object_evaluator/models/non_matches_helper.py @@ -2,6 +2,8 @@ from typing import Any, Dict, List, Optional +from stickler.comparators.base import BaseComparator + from .comparison_helper_base import ComparisonHelperBase from .non_match_field import NonMatchType @@ -101,7 +103,9 @@ def create_non_match_entry( return entry def collect_list_non_matches( - self, field_name: str, gt_list: List[Any], pred_list: List[Any] + self, field_name: str, gt_list: List[Any], pred_list: List[Any], + comparator: Optional[BaseComparator] = None, + match_threshold: Optional[float] = None, ) -> List[Dict[str, Any]]: """Collect individual object-level non-matches from a list field. @@ -109,12 +113,16 @@ def collect_list_non_matches( field_name: Name of the list field gt_list: Ground truth list pred_list: Prediction list + comparator: Field comparator for non-structured list elements. + match_threshold: Field threshold for non-structured list elements. Returns: List of non-match dictionaries with individual object information """ # Use base class method but filter for non-matches only - all_entries = self.collect_list_entries(field_name, gt_list, pred_list) + all_entries = self.collect_list_entries( + field_name, gt_list, pred_list, comparator, match_threshold + ) # Filter for non-matches only (entries where match is False or non_match_type exists) non_matches = [] @@ -174,16 +182,18 @@ def _extract_entries_from_objects( non_match_type = "FD" object_index = gt_index - return [ - self.create_non_match_entry( - field_name, - gt_object, - pred_object, - non_match_type, - object_index, - similarity_score, - ) - ] + entry = self.create_non_match_entry( + field_name, + gt_object, + pred_object, + non_match_type, + object_index, + similarity_score, + ) + if non_match_type == "FD": + # The caller knows the field threshold used to classify this pair. + entry["reason"] = reason + return [entry] def _extract_field_level_non_matches( self, diff --git a/tests/structured_object_evaluator/README.md b/tests/structured_object_evaluator/README.md new file mode 100644 index 00000000..7b6d88f5 --- /dev/null +++ b/tests/structured_object_evaluator/README.md @@ -0,0 +1,9 @@ +# Structured evaluation tests + +These tests exercise model configuration, recursive scoring, list matching, +confusion matrices, and reporting through `StructuredModel.compare_with()`. +Run this directory with `python -m pytest tests/structured_object_evaluator/`. + +`test_nested_plain_basemodel.py` covers plain Pydantic model dispatch and class +gating. The cross-collector list-reporting regression matrix for issue #332 is +in `../test_list_reporting.py`. See `../README.md` for general test conventions. diff --git a/tests/structured_object_evaluator/test_nested_plain_basemodel.py b/tests/structured_object_evaluator/test_nested_plain_basemodel.py index 519e2d76..37d5e5e7 100644 --- a/tests/structured_object_evaluator/test_nested_plain_basemodel.py +++ b/tests/structured_object_evaluator/test_nested_plain_basemodel.py @@ -1894,26 +1894,8 @@ def test_the_probe_does_not_spend_the_one_warning_the_field_gets(self): assert self._mismatch_warnings(caught) -class TestARefusedElementIsCountedButNotReported: - """The declared gap, pinned so it cannot widen unnoticed. - - There is a sixth reader of the pair question and it cannot consult the gate. - The confusion-matrix counts come through the wrapped element comparator; the - item-level report comes through `ComparisonHelperBase.get_optimal_assignments`, - which runs its own `HungarianHelper.get_complete_matching_info(gt_list, - pred_list)` with no comparator argument at all. It scores the refused pair as a - match and emits nothing. - - So the counts say one false discovery and the report says there is nothing to - report. An ordinary below-threshold element IS documented, which is what makes - the omission specific to a refusal. - - This asserts the CURRENT behaviour. Fixing it means threading the field's - comparator into `get_optimal_assignments`, which changes `non_matches` for - every list of plain models, so it is its own change. When that lands this test - fails, which is the reminder to update the CHANGELOG's "Known gap" paragraph in - the same commit. - """ +class TestARefusedElementIsCountedAndReported: + """Regression for #332: rejected list pairs need an explanation and a count.""" class Plain(BaseModel): sku: Optional[str] = None @@ -1942,31 +1924,18 @@ def test_the_refusal_is_counted(self): assert result["field_scores"]["f"] == pytest.approx(0.0) assert (node["tp"], node["fd"]) == (0, 1) - def test_the_refusal_is_not_reported(self): - """The gap itself.""" + def test_the_refusal_is_reported(self): + """The item-level explanation must agree with the false-discovery count.""" result = self._result([self.Plain(sku="a")], [self.Other(sku="a")]) - assert not (result.get("non_matches") or []) + entry, = result["non_matches"] + assert entry["field_path"] == "f[0]" + assert entry["non_match_type"] == "false_discovery" + assert entry["similarity_score"] == 0.0 def test_an_ordinary_below_threshold_element_still_is_reported(self): - """The contrast that makes the gap specific rather than general. - - Without this, the test above would also pass if non-match reporting were - broken outright, and the gap would look larger than it is. - """ + """Ordinary below-threshold explanations remain available.""" result = self._result(["aaa"], ["zzz"]) assert result["non_matches"] assert any( "below threshold" in str(nm.get("reason", "")) for nm in result["non_matches"] ) - - def test_the_changelog_still_declares_it(self): - """A gap the CHANGELOG stops mentioning is a gap that reads as fixed.""" - from pathlib import Path - - changelog = Path(__file__).resolve().parents[2] / "CHANGELOG.md" - text = " ".join(changelog.read_text().split()) - assert "a refused list element is counted but not reported" in text.lower(), ( - "CHANGELOG no longer declares that a refused element produces no " - "non-match record, which the tests above measure as still true. " - "Remove both together or neither." - ) diff --git a/tests/test_list_reporting.py b/tests/test_list_reporting.py new file mode 100644 index 00000000..7c62e1ac --- /dev/null +++ b/tests/test_list_reporting.py @@ -0,0 +1,238 @@ +"""Regression coverage for reporting the list comparisons scored by #332.""" + +from typing import Any, Optional + +import pytest +from pydantic import BaseModel + +from stickler import ( + ANLSStarComparator, + ComparableField, + ExactComparator, + StructuredModel, +) +from stickler.comparators.base import BaseComparator + + +class Plain(BaseModel): + sku: str + + +class Other(BaseModel): + sku: str + + +class Document(StructuredModel): + items: Optional[list[Any]] = ComparableField( + default=None, comparator=ANLSStarComparator() + ) + + +def report(gt, pred, model=Document, **options): + return model(items=gt).compare_with( + model(items=pred), + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + **options, + ) + + +def test_refused_pair_is_reported_in_both_formats(): + result = report([Plain(sku="a")], [Other(sku="a")]) + assert result["field_scores"]["items"] == 0.0 + assert result["confusion_matrix"]["fields"]["items"]["overall"]["fd"] == 1 + assert len(result["non_matches"]) == 1 + entry = result["non_matches"][0] + assert entry["field_path"] == "items[0]" + assert entry["non_match_type"] == "false_discovery" + assert entry["ground_truth_value"] == {"sku": "a"} + assert entry["prediction_value"] == {"sku": "a"} + assert entry["similarity_score"] == 0.0 + (row,) = result["field_comparisons"] + assert (row["expected_key"], row["actual_key"]) == ("items[0]", "items[0]") + assert row["match"] is False + assert row["score"] == 0.0 + + +def test_reordered_mixed_classes_do_not_report_discarded_cross_pairs(): + result = report( + [Plain(sku="same"), Other(sku="same")], + [Other(sku="same"), Plain(sku="same")], + ) + assert result["field_scores"]["items"] == 1.0 + assert result["non_matches"] == [] + rows = result["field_comparisons"] + assert {(row["expected_key"], row["actual_key"]) for row in rows} == { + ("items[0]", "items[1]"), + ("items[1]", "items[0]"), + } + assert all(row["match"] for row in rows) + + +def test_duplicate_refusals_keep_distinct_indices(): + result = report([Plain(sku="a"), Plain(sku="a")], [Other(sku="a")]) + counts = result["confusion_matrix"]["fields"]["items"]["overall"] + assert (counts["fd"], counts["fn"]) == (1, 1) + assert {entry["field_path"] for entry in result["non_matches"]} == { + "items[0]", + "items[1]", + } + assert {entry["non_match_type"] for entry in result["non_matches"]} == { + "false_discovery", + "false_negative", + } + + +class ConstantComparator(BaseComparator): + def _compare(self, left, right): + return 0.6 + + +@pytest.mark.parametrize("threshold, matches", [(0.5, True), (0.6, True), (0.8, False)]) +@pytest.mark.parametrize("clip", [True, False]) +def test_custom_comparator_and_threshold_are_used_by_both_reports( + threshold, matches, clip +): + class CustomDocument(StructuredModel): + items: list[str] = ComparableField( + comparator=ConstantComparator(), + threshold=threshold, + clip_under_threshold=clip, + ) + + result = report(["a"], ["a"], model=CustomDocument) + assert result["field_scores"]["items"] == pytest.approx( + 0.6 if matches or not clip else 0.0 + ) + (row,) = result["field_comparisons"] + assert row["score"] == pytest.approx(0.6) + assert row["match"] is matches + if matches: + assert result["non_matches"] == [] + else: + (entry,) = result["non_matches"] + assert entry["similarity_score"] == pytest.approx(0.6) + assert entry["reason"] == "below threshold (0.600 < 0.8)" + + +def test_exact_comparator_is_not_overridden_by_report_normalization(): + class ExactDocument(StructuredModel): + items: list[str] = ComparableField( + comparator=ExactComparator(case_sensitive=True) + ) + + result = report(["A"], ["a"], model=ExactDocument) + assert result["field_scores"]["items"] == 0.0 + assert len(result["non_matches"]) == 1 + assert result["field_comparisons"][0]["match"] is False + + +@pytest.mark.parametrize("gt,pred,count", [([], [], 0), ([], ["a"], 1), (["a"], [], 1)]) +def test_empty_lists_preserve_report_counts(gt, pred, count): + result = report(gt, pred) + assert len(result["non_matches"]) == count + assert len(result["field_comparisons"]) == count + + +@pytest.mark.parametrize( + "gt,pred", [(["aaa"], ["zzz"]), ([Plain(sku="a")], [Plain(sku="a")])] +) +def test_controls_and_reporting_flags_do_not_change_scores(gt, pred): + result = report(gt, pred) + without_reports = Document(items=gt).compare_with( + Document(items=pred), include_confusion_matrix=True + ) + assert "non_matches" not in without_reports + assert "field_comparisons" not in without_reports + assert { + key: value + for key, value in result.items() + if key not in {"non_matches", "field_comparisons"} + } == without_reports + assert len(result["non_matches"]) == (1 if gt == ["aaa"] else 0) + + +@pytest.mark.parametrize( + "non_matches,comparisons", + [(False, False), (True, False), (False, True), (True, True)], +) +def test_refusal_reporting_flags_preserve_metrics(non_matches, comparisons): + gt = Document(items=[Plain(sku="a")]) + pred = Document(items=[Other(sku="a")]) + baseline = gt.compare_with(pred, include_confusion_matrix=True) + result = gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=non_matches, + document_field_comparisons=comparisons, + ) + assert ("non_matches" in result) is non_matches + assert ("field_comparisons" in result) is comparisons + assert {key: result[key] for key in baseline} == baseline + if non_matches: + assert len(result["non_matches"]) == 1 + if comparisons: + assert result["field_comparisons"][0]["match"] is False + + +def test_nested_report_paths_reach_the_same_class_gate(): + class Envelope(StructuredModel): + document: Document + + result = Envelope(document=Document(items=[Plain(sku="a")])).compare_with( + Envelope(document=Document(items=[Other(sku="a")])), + document_non_matches=True, + document_field_comparisons=True, + ) + (entry,) = result["non_matches"] + assert entry["field_path"] == "document.items[0]" + (row,) = result["field_comparisons"] + assert row["expected_key"] == "document.items[0]" + assert row["match"] is False + + +def test_unrelated_dict_pair_in_mixed_list_is_not_refused(): + result = report( + [{"code": "a"}, Plain(sku="b")], + [{"code": "a"}, Other(sku="b")], + ) + assert result["field_scores"]["items"] == pytest.approx(0.5) + (entry,) = result["non_matches"] + assert entry["field_path"] == "items[1]" + assert result["field_comparisons"][0]["match"] is True + + +def test_structured_list_keeps_element_threshold_not_parent_comparator(): + class Item(StructuredModel): + match_threshold = 0.9 + code: str = ComparableField(comparator=ExactComparator()) + + class Parent(StructuredModel): + # Runtime StructuredModel elements use recursive matching even when + # the annotation also permits primitives with a field comparator. + items: list[Any] = ComparableField(comparator=ConstantComparator(), threshold=0.9) + + result = report([Item(code="a")], [Item(code="a")], model=Parent) + assert result["field_scores"]["items"] == 1.0 + assert result["non_matches"] == [] + (row,) = result["field_comparisons"] + assert row["expected_key"] == "items[0].code" + assert row["score"] == 1.0 + + +def test_report_matching_does_not_emit_warnings_for_discarded_pairs(): + import warnings + + class Note(BaseModel): + sku: str + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + result = report( + [Plain(sku="a"), Note(sku="a")], [Note(sku="a"), Plain(sku="a")] + ) + assert result["non_matches"] == [] + assert not [ + warning for warning in caught if "Different classes" in str(warning.message) + ] From 7fefbbba191704a7b80576084aab22e2fc77a654 Mon Sep 17 00:00:00 2001 From: hugosmoreira Date: Thu, 24 Sep 2026 11:16:39 -0700 Subject: [PATCH 2/5] fix: reuse scored list pairings in comparison reports --- CHANGELOG.md | 43 ++++++-- src/stickler/algorithms/README.md | 5 +- .../models/comparison_engine.py | 22 ++++- .../models/comparison_helper.py | 59 ++++++----- .../models/comparison_helper_base.py | 72 ++++++++------ .../models/field_comparator.py | 4 +- .../models/field_comparison_collector.py | 14 ++- .../models/non_match_collector.py | 17 +++- .../models/non_matches_helper.py | 31 ++++-- .../models/primitive_list_comparator.py | 12 +++ .../models/structured_list_comparator.py | 7 ++ .../models/structured_model.py | 10 +- tests/test_list_reporting.py | 97 +++++++++++++++++++ 13 files changed, 308 insertions(+), 85 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccc00f3e..ef1d69bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,12 +12,10 @@ Each release links to full notes on the ### Fixed - List reporting ([#332](https://github.com/awslabs/stickler/issues/332)): - `non_matches` and `field_comparisons` now use the configured comparator, - class gate, and field threshold for primitive and plain-model lists. Rejected - pairs produce an indexed false-discovery record instead of disappearing; - reordered pair indices and reported similarities also follow that comparator. - Scores and confusion-matrix counts are unchanged. Structured-model lists - retain recursive matching and their element-model threshold. + `non_matches` and `field_comparisons` reuse the pairings, scores, and + threshold decisions made during list scoring. Rejected pairs produce indexed + false-discovery records, and reports no longer re-run comparators or disagree + with confusion-matrix counts when a score is near the threshold. ## [1.0.0] - 2026-09-11 @@ -839,9 +837,36 @@ Each release links to full notes on the gate takes a `warn` flag, probing is silent, and the warnings are replayed on the pairs the matcher selected. - This release left a reporting gap: a refused list element contributed a false - discovery but no item-level record. The reporting fix for - [#332](https://github.com/awslabs/stickler/issues/332) is listed under Unreleased. + **Known gap: a refused list element is counted but not reported.** There is a + sixth reader of the pair question and it is the one that cannot consult the + gate. The confusion-matrix counts come through the wrapped comparator; the + item-level report comes through `ComparisonHelperBase.get_optimal_assignments`, + which runs its own `HungarianHelper.get_complete_matching_info(gt_list, + pred_list)` with no comparator argument at all. It therefore scores a refused + pair as a match and emits nothing, so the counts and the report disagree: + + ``` + f: Optional[List[Any]] = ComparableField(comparator=ANLSStarComparator()) + [Plain(sku='a')] vs [Cat(sku='a')] + + dev here + field_scores {'f': 1.0} {'f': 0.0} + f counts tp=1 fd=0 tp=0 fd=1 + non_matches [] [] <- an fd with no record + ``` + + An ordinary below-threshold element IS documented, so the omission is specific + to a refusal, and a user has no way to find out why the field lost a point. + Widening the `isinstance(gt_list[0], StructuredModel)` guard that skips + item-level collection for plain-model lists is not sufficient -- verified -- and + the actual fix is to thread the field's comparator into + `get_optimal_assignments`, a shared template-method base with two subclasses and + two collectors whose `non_matches` output would change for every list of plain + models. That is a reporting change with its own blast radius, so it is declared + and tracked in [#332](https://github.com/awslabs/stickler/issues/332) rather + than smuggled in here. Tests pin the disagreement so it cannot widen unnoticed, + including one asserting an ordinary below-threshold element IS still reported, + so the gap cannot read as larger than it is. Refusing is deliberate rather than conservative. The scalar default is edit distance over the rendered form, and because the field names are identical on diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index c4e13e4d..fe4ce9da 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -77,19 +77,20 @@ a score inside that window is a TP there and an FD here. ## How the evaluator uses it -Both internal callers read **only** `matched_pairs` and classify the scores +All internal callers read **only** `matched_pairs` and classify the scores themselves: | Caller | What it does with the pairs | |---|---| | `HungarianHelper.get_complete_matching_info` | derives the matched and unmatched index sets for object matching over `List[StructuredModel]` | | `ComparisonHelper.compare_unordered_lists` | hands them to `unordered_list_metrics`, which counts against its own `classification_threshold` | +| `ComparisonHelperBase.get_optimal_assignments` | provides pairings for direct report-helper calls; `compare_with` reports instead reuse the scoring pass's pairings | `unordered_list_metrics` uses the same derivation as `calculate_metrics`, so the two agree on what a count means. The remaining difference is the tolerant threshold test noted above. -Because neither caller reads the counts, a change to how `calculate_metrics` +Because these callers do not read the counts, a change to how `calculate_metrics` classifies cannot move an evaluator score. It is a public API in its own right though, so a change there is still breaking for a direct caller. diff --git a/src/stickler/structured_object_evaluator/models/comparison_engine.py b/src/stickler/structured_object_evaluator/models/comparison_engine.py index 820b73db..be795fc9 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_engine.py +++ b/src/stickler/structured_object_evaluator/models/comparison_engine.py @@ -81,7 +81,17 @@ def confusion_matrix_builder(self): self._confusion_matrix_builder = ConfusionMatrixBuilder(self.model) return self._confusion_matrix_builder - def compare_recursive(self, other: "StructuredModel") -> Dict[str, Any]: + @staticmethod + def _drop_list_matching(result: Dict[str, Any]) -> None: + """Remove scoring-only pairing details from a public result tree.""" + for field_result in result.get("fields", {}).values(): + if isinstance(field_result, dict): + field_result.pop("_list_matching", None) + ComparisonEngine._drop_list_matching(field_result) + + def compare_recursive( + self, other: "StructuredModel", *, _include_list_matching: bool = False + ) -> Dict[str, Any]: """The core recursive comparison function. This method performs a single-traversal comparison of two StructuredModel @@ -177,6 +187,8 @@ def compare_recursive(self, other: "StructuredModel") -> Dict[str, Any]: if total_weight > 0: result["overall"]["similarity_score"] = total_score / total_weight + if not _include_list_matching: + self._drop_list_matching(result) return result def compare_with( @@ -249,7 +261,7 @@ def compare_with( >>> print(result["confusion_matrix"]["overall"]["tp"]) """ # SINGLE TRAVERSAL: Get everything in one pass - recursive_result = self.compare_recursive(other) + recursive_result = self.compare_recursive(other, _include_list_matching=True) # Extract scoring information from recursive result field_scores = {} @@ -441,6 +453,12 @@ def compare_with( if pred_bboxes: result["prediction_bboxes"] = pred_bboxes + # The collectors have consumed the scoring-only pairings. Keep the + # public recursive/confusion-matrix result shape unchanged. + self._drop_list_matching(recursive_result) + if "confusion_matrix" in result: + self._drop_list_matching(result["confusion_matrix"]) + # If evaluator_format is requested, transform the result if evaluator_format: return self.model._format_for_evaluator(result, other, recall_with_fd) diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper.py b/src/stickler/structured_object_evaluator/models/comparison_helper.py index a447041c..f030a0c3 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper.py @@ -150,6 +150,32 @@ def _holds_a_plain_model(items: List[Any]) -> bool: return any(_is_plain_model(item) for item in items) +def _match_non_structured_lists( + gt_list: List[Any], + pred_list: List[Any], + comparator: BaseComparator, + *, + model_cls=None, + field_name: str = "", + warn_selected: bool = False, +) -> List[tuple]: + """Use the same raw-value matcher and class gate for scoring and direct reports.""" + from stickler.algorithms.hungarian import HungarianMatcher + + element_comparator = comparator + if _holds_a_plain_model(gt_list) or _holds_a_plain_model(pred_list): + element_comparator = _ClassGatedComparator( + comparator, model_cls=model_cls, field_name=field_name + ) + matcher = HungarianMatcher( + element_comparator, match_threshold=0.0, normalize_values=False + ) + pairs = matcher.calculate_metrics(gt_list, pred_list)["matched_pairs"] + if warn_selected and isinstance(element_comparator, _ClassGatedComparator): + element_comparator.warn_for_selected(gt_list, pred_list, pairs) + return pairs + + def _maybe_absent(val: Any) -> bool: """Whether ``val`` could be absent under *either* of ``NullHelper``'s rules. @@ -180,6 +206,7 @@ def compare_unordered_lists( clip_under_threshold: bool = True, model_cls=None, field_name: str = "", + pair_sink: List[tuple] | None = None, ) -> Dict[str, Any]: """Compare two lists as unordered collections using Hungarian matching. @@ -196,6 +223,8 @@ def compare_unordered_lists( default to a falsy value so a caller with no field in hand still gets the gate -- it refuses the same pairs either way, and only the warning is less specific. + pair_sink: Optional list populated with the selected (ground-truth + index, prediction index, score) tuples from this scoring pass. Returns: Dictionary with confusion matrix metrics including: @@ -264,8 +293,6 @@ def compare_unordered_lists( ) else: # Use the provided comparator for other types - from stickler.algorithms.hungarian import HungarianMatcher - # CRITICAL FIX: Use match_threshold=0.0 to capture ALL matches, not just those above threshold # This allows us to keep track of partial matches for scoring. # @@ -289,29 +316,15 @@ def compare_unordered_lists( # Gate the element comparator on class identity. See # _ClassGatedComparator; skipped entirely for ordinary primitive # lists so the cost matrix stays unwrapped. - element_comparator = comparator - if _holds_a_plain_model(gt_list) or _holds_a_plain_model(pred_list): - element_comparator = _ClassGatedComparator( - comparator, model_cls=model_cls, field_name=field_name - ) - - hungarian = HungarianMatcher( - element_comparator, match_threshold=0.0, normalize_values=False - ) classification_threshold = threshold - # Get detailed metrics from HungarianMatcher - metrics = hungarian.calculate_metrics(gt_list, pred_list) - matched_pairs = metrics["matched_pairs"] - - # Only now is it known which pairs were chosen. The gate ran silently - # over the whole cost matrix; warning from inside it described - # discarded cells and spent `warn_once`'s single message per field on - # them. See `_ClassGatedComparator.warn_for_selected`. - if isinstance(element_comparator, _ClassGatedComparator): - element_comparator.warn_for_selected( - gt_list, pred_list, matched_pairs - ) + matched_pairs = _match_non_structured_lists( + gt_list, pred_list, comparator, + model_cls=model_cls, field_name=field_name, warn_selected=True, + ) + + if pair_sink is not None: + pair_sink.extend(matched_pairs) return ComparisonHelper.unordered_list_metrics( matched_pairs=matched_pairs, diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index 74004f39..e6cec238 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -4,10 +4,9 @@ from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional -from stickler.algorithms.hungarian import HungarianMatcher from stickler.comparators.base import BaseComparator -from .comparison_helper import _ClassGatedComparator, _holds_a_plain_model +from .comparison_helper import _match_non_structured_lists from .hungarian_helper import HungarianHelper DEFAULT_MATCH_THRESHOLD = 0.7 @@ -62,17 +61,13 @@ def get_optimal_assignments( hungarian_info = self.hungarian_helper.get_complete_matching_info( gt_list, pred_list ) + matched_pairs_with_scores = hungarian_info["matched_pairs"] else: - # Mirror scoring: comparators receive raw values, and plain - # models pass through the same class gate. Probing stays silent; - # the scoring run already warned about selected refused pairs. - if _holds_a_plain_model(gt_list) or _holds_a_plain_model(pred_list): - comparator = _ClassGatedComparator(comparator) - matcher = HungarianMatcher( - comparator, match_threshold=0.0, normalize_values=False + # Direct helper calls use the scoring matcher, but do not emit + # selected-pair warnings a second time. + matched_pairs_with_scores = _match_non_structured_lists( + gt_list, pred_list, comparator ) - hungarian_info = matcher.calculate_metrics(gt_list, pred_list) - matched_pairs_with_scores = hungarian_info["matched_pairs"] assignments = [(i, j) for i, j, _ in matched_pairs_with_scores] return assignments, matched_pairs_with_scores @@ -89,7 +84,9 @@ def generate_comparison_reason(self, is_match: bool, score: float, threshold: fl Descriptive reason string """ if is_match: - if math.isclose(score,1.0): + if score < threshold: + return f"within threshold tolerance ({score:.12g} vs {threshold})" + elif math.isclose(score,1.0): return "exact match" else: return f"above threshold ({score:.3f} >= {threshold})" @@ -115,7 +112,8 @@ def process_matched_pairs( gt_list: List[Any], pred_list: List[Any], matched_pairs_with_scores: List[tuple], - match_threshold: float + match_threshold: float, + verdicts: Optional[List[bool]] = None, ) -> List[Dict[str, Any]]: """Process matched pairs and create entries. @@ -125,19 +123,26 @@ def process_matched_pairs( pred_list: Prediction list matched_pairs_with_scores: List of (gt_idx, pred_idx, score) tuples match_threshold: Threshold for determining matches + verdicts: Optional decisions from scoring, including its tolerance Returns: List of entries for matched pairs """ entries = [] - for gt_idx, pred_idx, similarity_score in matched_pairs_with_scores: + for pair_index, (gt_idx, pred_idx, similarity_score) in enumerate( + matched_pairs_with_scores + ): if gt_idx < len(gt_list) and pred_idx < len(pred_list): gt_item = gt_list[gt_idx] pred_item = pred_list[pred_idx] # Determine if this is a match - is_match = bool(similarity_score >= match_threshold) + is_match = ( + bool(verdicts[pair_index]) + if verdicts is not None + else bool(similarity_score >= match_threshold) + ) # Create reason reason = self.generate_comparison_reason(is_match, similarity_score, match_threshold) @@ -314,6 +319,7 @@ def collect_list_entries( self, field_name: str, gt_list: List[Any], pred_list: List[Any], comparator: Optional[BaseComparator] = None, match_threshold: Optional[float] = None, + matching: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Collect entries from a list field using the template method pattern. @@ -323,6 +329,8 @@ def collect_list_entries( pred_list: Prediction list comparator: Field comparator for non-structured list elements. match_threshold: Field threshold for non-structured list elements. + matching: Pairings and decisions already produced by scoring. When + supplied, no comparator call or second assignment is made. Returns: List of entries with individual information @@ -334,20 +342,30 @@ def collect_list_entries( from .structured_model import StructuredModel - # The dispatcher routes by the first GT element. Structured lists use - # recursive model comparison and the element model's threshold, not the - # parent field's comparator/threshold. - if gt_list and isinstance(gt_list[0], StructuredModel): - comparator = None - match_threshold = None - assignments, matched_pairs_with_scores = self.get_optimal_assignments( - gt_list, pred_list, comparator - ) - if match_threshold is None: - match_threshold = self.get_match_threshold(gt_list or pred_list) + if matching is not None: + matched_pairs_with_scores = matching["pairs"] + assignments = [(i, j) for i, j, _ in matched_pairs_with_scores] + match_threshold = matching["threshold"] + verdicts = matching["verdicts"] + else: + # Direct helper callers still compute their own assignments. + if gt_list and isinstance(gt_list[0], StructuredModel): + if comparator is not None or match_threshold is not None: + raise ValueError( + "A StructuredModel list uses its element-model matcher and " + "threshold; field comparator/threshold overrides are not supported" + ) + match_threshold = None + assignments, matched_pairs_with_scores = self.get_optimal_assignments( + gt_list, pred_list, comparator + ) + if match_threshold is None: + match_threshold = self.get_match_threshold(gt_list or pred_list) + verdicts = None entries.extend(self.process_matched_pairs( - field_name, gt_list, pred_list, matched_pairs_with_scores, match_threshold + field_name, gt_list, pred_list, matched_pairs_with_scores, + match_threshold, verdicts, )) # Process unmatched ground truth items (FN) diff --git a/src/stickler/structured_object_evaluator/models/field_comparator.py b/src/stickler/structured_object_evaluator/models/field_comparator.py index 25502f52..3596433b 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparator.py +++ b/src/stickler/structured_object_evaluator/models/field_comparator.py @@ -163,7 +163,9 @@ def compare_structured_field( # # Impact: Moderate - primarily affects deeply nested structures (3+ levels) # Estimated overhead: 2-3x for structures with 3 levels of nesting - nested_details = gt_val.compare_recursive(pred_val)["fields"] + nested_details = gt_val.compare_recursive( + pred_val, _include_list_matching=True + )["fields"] # Return structure with object-level metrics and nested field details kept separate return { diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index 0432c667..c7cafb1a 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -93,11 +93,17 @@ def collect_field_comparisons( and isinstance(pred_val, list) ): # Use FieldComparisonHelper for primitive list collection - info = self.model._get_comparison_info(field_name) + matching = field_result.get("_list_matching") + if matching is None: + info = self.model._get_comparison_info(field_name) + matching_kwargs = { + "comparator": info.comparator, + "match_threshold": info.threshold, + } + else: + matching_kwargs = {"matching": matching} list_comparisons = self.helper.collect_list_entries( - field_name, gt_val, pred_val, - comparator=info.comparator, - match_threshold=info.threshold, + field_name, gt_val, pred_val, **matching_kwargs ) all_field_comparisons.extend(list_comparisons) diff --git a/src/stickler/structured_object_evaluator/models/non_match_collector.py b/src/stickler/structured_object_evaluator/models/non_match_collector.py index c09d9064..9d85808f 100644 --- a/src/stickler/structured_object_evaluator/models/non_match_collector.py +++ b/src/stickler/structured_object_evaluator/models/non_match_collector.py @@ -94,7 +94,8 @@ def collect_enhanced_non_matches( ): # Use NonMatchesHelper for object-level collection object_non_matches = self.helper.collect_list_non_matches( - field_name, gt_val, pred_val + field_name, gt_val, pred_val, + matching=field_result.get("_list_matching"), ) all_non_matches.extend(object_non_matches) @@ -103,11 +104,17 @@ def collect_enhanced_non_matches( and isinstance(pred_val, list) ): # Use NonMatchesHelper for object-level collection - info = self.model._get_comparison_info(field_name) + matching = field_result.get("_list_matching") + if matching is None: + info = self.model._get_comparison_info(field_name) + matching_kwargs = { + "comparator": info.comparator, + "match_threshold": info.threshold, + } + else: + matching_kwargs = {"matching": matching} object_non_matches = self.helper.collect_list_non_matches( - field_name, gt_val, pred_val, - comparator=info.comparator, - match_threshold=info.threshold, + field_name, gt_val, pred_val, **matching_kwargs ) all_non_matches.extend(object_non_matches) diff --git a/src/stickler/structured_object_evaluator/models/non_matches_helper.py b/src/stickler/structured_object_evaluator/models/non_matches_helper.py index 8c9f5503..549ed6a3 100644 --- a/src/stickler/structured_object_evaluator/models/non_matches_helper.py +++ b/src/stickler/structured_object_evaluator/models/non_matches_helper.py @@ -19,6 +19,7 @@ def create_entry( non_match_type: str, object_index: int = None, similarity_score: float = None, + match_threshold: Optional[float] = None, ) -> Dict[str, Any]: """Create a non-match entry for detailed analysis. @@ -29,12 +30,14 @@ def create_entry( non_match_type: Type of non-match ("FD", "FN", "FA") object_index: Optional index of the object in the list for indexed field paths similarity_score: Similarity score for FD entries + match_threshold: Threshold used to explain an FD when supplied Returns: Dictionary with non-match information """ return self.create_non_match_entry( - field_name, gt_object, pred_object, non_match_type, object_index, similarity_score + field_name, gt_object, pred_object, non_match_type, object_index, + similarity_score, match_threshold=match_threshold, ) def create_non_match_entry( @@ -45,6 +48,8 @@ def create_non_match_entry( non_match_type: str, object_index: int = None, similarity_score: float = None, + match_threshold: Optional[float] = None, + reason: Optional[str] = None, ) -> Dict[str, Any]: """Create a non-match entry for detailed analysis. @@ -55,6 +60,8 @@ def create_non_match_entry( non_match_type: Type of non-match ("FD", "FN", "FA") object_index: Optional index of the object in the list for indexed field paths similarity_score: Similarity score for FD entries + match_threshold: Threshold used to explain an FD when supplied + reason: Already-classified FD explanation from the scoring pass Returns: Dictionary with non-match information @@ -82,11 +89,16 @@ def create_non_match_entry( if non_match_type == "FD": # False Discovery: matched but below threshold if similarity_score is not None: - # Get the match threshold from the object - threshold = self.get_match_threshold([gt_object] if gt_object else [pred_object]) - entry["reason"] = ( - f"below threshold ({similarity_score:.3f} < {threshold})" - ) + if reason is None: + threshold = ( + match_threshold + if match_threshold is not None + else self.get_match_threshold( + [gt_object] if gt_object else [pred_object] + ) + ) + reason = f"below threshold ({similarity_score:.3f} < {threshold})" + entry["reason"] = reason entry["similarity"] = similarity_score entry["similarity_score"] = similarity_score else: @@ -106,6 +118,7 @@ def collect_list_non_matches( self, field_name: str, gt_list: List[Any], pred_list: List[Any], comparator: Optional[BaseComparator] = None, match_threshold: Optional[float] = None, + matching: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Collect individual object-level non-matches from a list field. @@ -121,7 +134,7 @@ def collect_list_non_matches( """ # Use base class method but filter for non-matches only all_entries = self.collect_list_entries( - field_name, gt_list, pred_list, comparator, match_threshold + field_name, gt_list, pred_list, comparator, match_threshold, matching ) # Filter for non-matches only (entries where match is False or non_match_type exists) @@ -189,10 +202,8 @@ def _extract_entries_from_objects( non_match_type, object_index, similarity_score, + reason=reason if non_match_type == "FD" else None, ) - if non_match_type == "FD": - # The caller knows the field threshold used to classify this pair. - entry["reason"] = reason return [entry] def _extract_field_level_non_matches( diff --git a/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py b/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py index 37808adb..48fa752c 100644 --- a/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py @@ -26,6 +26,8 @@ if TYPE_CHECKING: from .structured_model import StructuredModel +from .threshold_helper import ThresholdHelper + class PrimitiveListComparator: """Handles comparison of List[primitive] fields using Hungarian matching.""" @@ -103,6 +105,7 @@ def compare_primitive_list_with_scores( # the zeroing happens inside `unordered_list_metrics`, upstream of the # `threshold_applied_score = raw_similarity` line below, so that line # preserved a score that had already been thrown away. + matched_pairs = [] match_result = self.parent_model._compare_unordered_lists( gt_list, pred_list, @@ -110,6 +113,7 @@ def compare_primitive_list_with_scores( threshold, info.clip_under_threshold, field_name=field_name, + pair_sink=matched_pairs, ) # Extract the counts from the match result @@ -132,4 +136,12 @@ def compare_primitive_list_with_scores( "similarity_score": raw_similarity, "threshold_applied_score": threshold_applied_score, "weight": weight, + "_list_matching": { + "pairs": matched_pairs, + "threshold": threshold, + "verdicts": [ + ThresholdHelper.is_above_threshold(score, threshold) + for _, _, score in matched_pairs + ], + }, } diff --git a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py index 4ed9c5e5..99cd82f4 100644 --- a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py @@ -95,6 +95,13 @@ def compare_struct_list_with_scores( "similarity_score": raw_similarity, "threshold_applied_score": threshold_applied_score, "weight": weight, + "_list_matching": { + "pairs": matched_pairs, + "threshold": match_threshold, + "verdicts": [ + score >= match_threshold for _, _, score in matched_pairs + ], + }, } return final_result diff --git a/src/stickler/structured_object_evaluator/models/structured_model.py b/src/stickler/structured_object_evaluator/models/structured_model.py index b4a14410..9f9f90fb 100644 --- a/src/stickler/structured_object_evaluator/models/structured_model.py +++ b/src/stickler/structured_object_evaluator/models/structured_model.py @@ -1341,6 +1341,7 @@ def _compare_unordered_lists( threshold: float, clip_under_threshold: bool = True, field_name: str = "", + pair_sink: List[tuple] | None = None, ) -> Dict[str, Any]: """Compare two lists as unordered collections using Hungarian matching. @@ -1367,6 +1368,7 @@ def _compare_unordered_lists( clip_under_threshold, model_cls=self.__class__, field_name=field_name, + pair_sink=pair_sink, ) def compare_field_raw(self, field_name: str, other_value: Any) -> float: @@ -1412,7 +1414,9 @@ def compare_field_raw(self, field_name: str, other_value: Any) -> float: # For non-StructuredModel fields, use existing logic return ComparisonHelper.compare_field_raw(self, field_name, other_value) - def compare_recursive(self, other: "StructuredModel") -> dict: + def compare_recursive( + self, other: "StructuredModel", *, _include_list_matching: bool = False + ) -> dict: """The ONE clean recursive function that handles everything. Enhanced to capture BOTH confusion matrix metrics AND similarity scores @@ -1432,7 +1436,9 @@ def compare_recursive(self, other: "StructuredModel") -> dict: from .comparison_engine import ComparisonEngine engine = ComparisonEngine(self) - return engine.compare_recursive(other) + return engine.compare_recursive( + other, _include_list_matching=_include_list_matching + ) def _dispatch_field_comparison( self, field_name: str, gt_val: Any, pred_val: Any diff --git a/tests/test_list_reporting.py b/tests/test_list_reporting.py index 7c62e1ac..45081ef2 100644 --- a/tests/test_list_reporting.py +++ b/tests/test_list_reporting.py @@ -12,6 +12,9 @@ StructuredModel, ) from stickler.comparators.base import BaseComparator +from stickler.structured_object_evaluator.models.non_matches_helper import ( + NonMatchesHelper, +) class Plain(BaseModel): @@ -236,3 +239,97 @@ class Note(BaseModel): assert not [ warning for warning in caught if "Different classes" in str(warning.message) ] + + +def test_reports_reuse_the_scoring_cost_matrix(): + class CountingComparator(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return 1.0 if left == right else 0.0 + + class Tags(StructuredModel): + items: list[str] = ComparableField(comparator=CountingComparator()) + + values = ["a", "b", "c", "d"] + result = report(values, values, model=Tags) + + assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 4 + assert result["non_matches"] == [] + assert len(result["field_comparisons"]) == 4 + assert CountingComparator.calls == 16 + + +def test_reports_share_scoring_threshold_tolerance(): + class NearThresholdComparator(BaseComparator): + def _compare(self, left, right): + return 0.7 - 1e-12 + + class Tags(StructuredModel): + items: list[str] = ComparableField( + comparator=NearThresholdComparator(), threshold=0.7 + ) + + result = report(["a"], ["b"], model=Tags) + + assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 1 + assert result["non_matches"] == [] + assert result["field_comparisons"][0]["match"] is True + assert "within threshold tolerance" in result["field_comparisons"][0]["reason"] + + +def test_reports_use_the_score_from_a_stateful_comparator_once(): + class ChangingComparator(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return 1.0 if type(self).calls == 1 else 0.0 + + class Tags(StructuredModel): + items: list[str] = ComparableField(comparator=ChangingComparator()) + + result = report(["a"], ["a"], model=Tags) + + assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 1 + assert result["non_matches"] == [] + assert result["field_comparisons"][0]["match"] is True + assert result["field_comparisons"][0]["score"] == 1.0 + assert ChangingComparator.calls == 1 + + +def test_direct_non_match_reason_uses_the_supplied_threshold(): + entry = NonMatchesHelper().create_non_match_entry( + "items", "a", "b", "FD", 0, 0.6, match_threshold=0.8 + ) + assert entry["reason"] == "below threshold (0.600 < 0.8)" + + +def test_private_pairing_details_do_not_appear_in_public_results(): + ground_truth = Document(items=["a"]) + prediction = Document(items=["a"]) + recursive_result = ground_truth.compare_recursive(prediction) + reported_result = report(["a"], ["a"]) + + assert set(recursive_result["fields"]["items"]) == { + "overall", "fields", "raw_similarity_score", "similarity_score", + "threshold_applied_score", "weight", + } + assert set(reported_result["confusion_matrix"]["fields"]["items"]) >= { + "overall", "fields", "raw_similarity_score", "similarity_score", + "threshold_applied_score", "weight", + } + assert "_list_matching" not in reported_result["confusion_matrix"]["fields"]["items"] + + +@pytest.mark.parametrize("override", ["comparator", "match_threshold"]) +def test_direct_structured_list_helper_rejects_ignored_field_overrides(override): + class Item(StructuredModel): + code: str = ComparableField(comparator=ExactComparator()) + + kwargs = {override: ExactComparator() if override == "comparator" else 0.9} + with pytest.raises(ValueError, match="StructuredModel list"): + NonMatchesHelper().collect_list_non_matches( + "items", [Item(code="a")], [Item(code="a")], **kwargs + ) From 7664719fe02eebab87628ec682ed31e746c0fb73 Mon Sep 17 00:00:00 2001 From: hugosmoreira Date: Thu, 24 Sep 2026 15:44:24 -0700 Subject: [PATCH 3/5] fix: reuse nested list results in reports --- CHANGELOG.md | 5 +- src/stickler/algorithms/README.md | 2 +- .../models/README.md | 6 +- .../models/comparison_engine.py | 8 +- .../models/comparison_helper_base.py | 9 +- .../models/field_comparator.py | 14 +- .../models/field_comparison_collector.py | 17 +- .../models/field_comparison_helper.py | 28 +- .../models/non_matches_helper.py | 28 +- .../models/structured_list_comparator.py | 22 +- .../models/structured_model.py | 8 +- tests/test_list_reporting.py | 321 +++++++++++++++++- 12 files changed, 422 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ded90c9f..fbeb4c1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,8 +34,9 @@ Each release links to full notes on the - List reporting ([#332](https://github.com/awslabs/stickler/issues/332)): `non_matches` and `field_comparisons` reuse the pairings, scores, and threshold decisions made during list scoring. Rejected pairs produce indexed - false-discovery records, and reports no longer re-run comparators or disagree - with confusion-matrix counts when a score is near the threshold. + false-discovery records. Primitive-list reports avoid extra comparator calls + and preserve scoring's threshold tolerance. Standard structured-child reports + reuse scored child results; custom comparison overrides retain their fallback. - **An unrecognized key in a model config is now reported instead of dropped.** `model_from_json` read a closed set of keys and ignored everything else, so diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index fe4ce9da..836ad89f 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -2,7 +2,7 @@ One module, one public class. `HungarianMatcher` pairs the items of two lists so that the total similarity is as high as it can be, which is what lets a list -field be scored without caring about order. Both of its internal callers are on +field be scored without caring about order. Its internal callers are on the traditional evaluation path. **ANLS Star does not go through this class.** `trees/list_tree.py` calls diff --git a/src/stickler/structured_object_evaluator/models/README.md b/src/stickler/structured_object_evaluator/models/README.md index 09093dc8..a64cf55a 100644 --- a/src/stickler/structured_object_evaluator/models/README.md +++ b/src/stickler/structured_object_evaluator/models/README.md @@ -31,7 +31,11 @@ its `from_json()` ingestion and `compare_with()` comparison pipeline. **Comparison pipeline** - `comparison_engine.py` — `ComparisonEngine`, the orchestrator behind `compare_with()`. Runs a single recursive traversal, then layers on confusion - matrix, non-matches, field comparisons, and optional metrics. + matrix, non-matches, field comparisons, and optional metrics. Structured-list + reporting reuses child traversals from scoring for the standard `compare_with` + implementation; that cache is removed from public results. Custom overrides + of `compare_with`/`compare_recursive` and direct report-helper calls retain + their comparison fallback. - `comparison_dispatcher.py`, `field_comparator.py`, `primitive_list_comparator.py`, `structured_list_comparator.py`, `hungarian_helper.py` — dispatch and per-type comparison, including Hungarian diff --git a/src/stickler/structured_object_evaluator/models/comparison_engine.py b/src/stickler/structured_object_evaluator/models/comparison_engine.py index be795fc9..09597a85 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_engine.py +++ b/src/stickler/structured_object_evaluator/models/comparison_engine.py @@ -204,6 +204,7 @@ def compare_with( confidence_metrics: Optional[List["ConfidenceMetric"]] = None, add_bbox_metrics: bool = False, bbox_iou_thresholds: Optional[Union[float, Iterable[float]]] = None, + _retain_recursive_result: bool = False, ) -> Dict[str, Any]: """Compare with another instance using single traversal. @@ -455,7 +456,12 @@ def compare_with( # The collectors have consumed the scoring-only pairings. Keep the # public recursive/confusion-matrix result shape unchanged. - self._drop_list_matching(recursive_result) + if _retain_recursive_result: + # Internal structured-list scoring passes this same traversal to + # the report collectors instead of comparing a child again. + result["_recursive_result"] = recursive_result + else: + self._drop_list_matching(recursive_result) if "confusion_matrix" in result: self._drop_list_matching(result["confusion_matrix"]) diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index e6cec238..95474aa2 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -114,6 +114,7 @@ def process_matched_pairs( matched_pairs_with_scores: List[tuple], match_threshold: float, verdicts: Optional[List[bool]] = None, + pair_results: Optional[Dict[tuple, Dict[str, Any]]] = None, ) -> List[Dict[str, Any]]: """Process matched pairs and create entries. @@ -124,6 +125,7 @@ def process_matched_pairs( matched_pairs_with_scores: List of (gt_idx, pred_idx, score) tuples match_threshold: Threshold for determining matches verdicts: Optional decisions from scoring, including its tolerance + pair_results: Optional already-scored child results for structured lists Returns: List of entries for matched pairs @@ -148,6 +150,9 @@ def process_matched_pairs( reason = self.generate_comparison_reason(is_match, similarity_score, match_threshold) # Extract entries from structured model objects + pair_result = ( + pair_results.get((gt_idx, pred_idx)) if pair_results else None + ) extracted_entries = self._extract_entries_from_objects( field_name, gt_item, @@ -157,6 +162,7 @@ def process_matched_pairs( is_match, similarity_score, reason, + **({"pair_result": pair_result} if pair_result is not None else {}), ) entries.extend(extracted_entries) @@ -330,7 +336,7 @@ def collect_list_entries( comparator: Field comparator for non-structured list elements. match_threshold: Field threshold for non-structured list elements. matching: Pairings and decisions already produced by scoring. When - supplied, no comparator call or second assignment is made. + supplied, its list assignments and verdicts are reused. Returns: List of entries with individual information @@ -366,6 +372,7 @@ def collect_list_entries( entries.extend(self.process_matched_pairs( field_name, gt_list, pred_list, matched_pairs_with_scores, match_threshold, verdicts, + matching.get("pair_results") if matching is not None else None, )) # Process unmatched ground truth items (FN) diff --git a/src/stickler/structured_object_evaluator/models/field_comparator.py b/src/stickler/structured_object_evaluator/models/field_comparator.py index 3596433b..62e18df6 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparator.py +++ b/src/stickler/structured_object_evaluator/models/field_comparator.py @@ -163,9 +163,17 @@ def compare_structured_field( # # Impact: Moderate - primarily affects deeply nested structures (3+ levels) # Estimated overhead: 2-3x for structures with 3 levels of nesting - nested_details = gt_val.compare_recursive( - pred_val, _include_list_matching=True - )["fields"] + from .comparison_engine import ComparisonEngine + from .structured_model import StructuredModel + + if type(gt_val).compare_recursive is StructuredModel.compare_recursive: + nested_result = ComparisonEngine(gt_val).compare_recursive( + pred_val, _include_list_matching=True + ) + else: + # Existing overrides need not accept internal metadata options. + nested_result = gt_val.compare_recursive(pred_val) + nested_details = nested_result["fields"] # Return structure with object-level metrics and nested field details kept separate return { diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index c7cafb1a..f3253ff0 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -95,11 +95,18 @@ def collect_field_comparisons( # Use FieldComparisonHelper for primitive list collection matching = field_result.get("_list_matching") if matching is None: - info = self.model._get_comparison_info(field_name) - matching_kwargs = { - "comparator": info.comparator, - "match_threshold": info.threshold, - } + from .structured_model import StructuredModel + + if gt_val and isinstance(gt_val[0], StructuredModel): + # A custom recursive result may lack cached pairings. + # Structured lists use their element model's settings. + matching_kwargs = {} + else: + info = self.model._get_comparison_info(field_name) + matching_kwargs = { + "comparator": info.comparator, + "match_threshold": info.threshold, + } else: matching_kwargs = {"matching": matching} list_comparisons = self.helper.collect_list_entries( diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py index d0e5844a..9d572757 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py @@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional from .comparison_helper_base import ComparisonHelperBase +from .threshold_helper import ThresholdHelper class FieldComparisonHelper(ComparisonHelperBase): @@ -91,7 +92,8 @@ def _extract_entries_from_objects( pred_index: Optional[int], is_match: bool, similarity_score: float, - reason: str + reason: str, + pair_result: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Extract field-level comparisons from structured model objects. @@ -117,11 +119,15 @@ def _extract_entries_from_objects( and isinstance(gt_object, StructuredModel) and isinstance(pred_object, StructuredModel) ): - # Perform field-by-field comparison to get detailed field comparisons - comparison_result = gt_object.compare_with( - pred_object, - document_non_matches=False, - include_confusion_matrix=False + # Reuse the child scores already computed during list scoring. + comparison_result = ( + pair_result + if pair_result is not None + else gt_object.compare_with( + pred_object, + document_non_matches=False, + include_confusion_matrix=False, + ) ) field_comparisons = [] @@ -134,6 +140,16 @@ def _extract_entries_from_objects( # Get field configuration for threshold info = gt_object._get_comparison_info(nested_field_name) field_is_match = field_score >= info.threshold + if ( + isinstance(gt_nested_val, list) + and gt_nested_val + and not isinstance(gt_nested_val[0], StructuredModel) + ): + # Primitive-list scoring accepts values within tolerance; + # scalar and structured-object thresholds remain exact. + field_is_match = ThresholdHelper.is_above_threshold( + field_score, info.threshold + ) # Create field paths with indices expected_key = f"{field_name}[{gt_index}].{nested_field_name}" if gt_index is not None else f"{field_name}[].{nested_field_name}" diff --git a/src/stickler/structured_object_evaluator/models/non_matches_helper.py b/src/stickler/structured_object_evaluator/models/non_matches_helper.py index 549ed6a3..bc365e0c 100644 --- a/src/stickler/structured_object_evaluator/models/non_matches_helper.py +++ b/src/stickler/structured_object_evaluator/models/non_matches_helper.py @@ -155,7 +155,8 @@ def _extract_entries_from_objects( pred_index: Optional[int], is_match: bool, similarity_score: float, - reason: str + reason: str, + pair_result: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Extract non-match entries from structured model objects. @@ -179,7 +180,7 @@ def _extract_entries_from_objects( pred_object, StructuredModel ): return self._extract_field_level_non_matches( - field_name, gt_object, pred_object, gt_index + field_name, gt_object, pred_object, gt_index, pair_result ) return [] @@ -212,6 +213,7 @@ def _extract_field_level_non_matches( gt_object: Any, pred_object: Any, object_index: int, + pair_result: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Extract field-level non-matches from a threshold-passing object pair. @@ -224,15 +226,25 @@ def _extract_field_level_non_matches( Returns: List of field-level non-match entries """ - comparison_result = gt_object.compare_with( - pred_object, - document_non_matches=True, - include_confusion_matrix=False, - ) + if pair_result is None: + comparison_result = gt_object.compare_with( + pred_object, + document_non_matches=True, + include_confusion_matrix=False, + ) + nested_non_matches = comparison_result.get("non_matches", []) + else: + from .non_match_collector import NonMatchCollector + + nested_non_matches = NonMatchCollector( + gt_object + ).collect_enhanced_non_matches( + pair_result["recursive_result"], pred_object + ) field_non_matches = [] - for non_match in comparison_result.get("non_matches", []): + for non_match in nested_non_matches: indexed_field_path = ( f"{field_name}[{object_index}].{non_match['field_path']}" ) diff --git a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py index 99cd82f4..aa3b3a36 100644 --- a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py @@ -70,8 +70,9 @@ def compare_struct_list_with_scores( ) = self._calculate_object_level_metrics(gt_list, pred_list, match_threshold) # Calculate raw similarity score using extracted method + pair_results = {} raw_similarity = self._calculate_struct_list_similarity( - matched_pairs, gt_list, pred_list, info + matched_pairs, gt_list, pred_list, info, pair_results ) # CRITICAL FIX: For structured lists, we NEVER clip under threshold - partial matches are important @@ -101,6 +102,7 @@ def compare_struct_list_with_scores( "verdicts": [ score >= match_threshold for _, _, score in matched_pairs ], + "pair_results": pair_results, }, } @@ -167,6 +169,7 @@ def _calculate_struct_list_similarity( gt_list: List["StructuredModel"], pred_list: List["StructuredModel"], info: "ComparableField", + pair_results: Dict[tuple, Dict[str, Any]], ) -> float: """Calculate raw similarity score for structured list. @@ -174,10 +177,14 @@ def _calculate_struct_list_similarity( gt_list: Ground truth list pred_list: Predicted list info: Field comparison info + pair_results: Receives child traversals for report-time reuse Returns: Raw similarity score between 0.0 and 1.0 """ + from .comparison_engine import ComparisonEngine + from .structured_model import StructuredModel + # Updated code to not use helper that was calling Hungarian match again, and instead use already generated matched pairs threshold_corrected_pairs = [] for gt_idx, pred_idx, raw_score in matched_pairs: @@ -194,7 +201,18 @@ def _calculate_struct_list_similarity( ) else: # Use individual comparison with threshold application (same as .compare_with()) - individual_result = gt_item.compare_with(pred_item) + if type(gt_item).compare_with is StructuredModel.compare_with: + individual_result = ComparisonEngine(gt_item).compare_with( + pred_item, _retain_recursive_result=True + ) + pair_results[(gt_idx, pred_idx)] = { + "field_scores": individual_result["field_scores"], + "recursive_result": individual_result.pop("_recursive_result"), + } + else: + # Preserve custom compare_with overrides, which may not + # expose an internal traversal for report reuse. + individual_result = gt_item.compare_with(pred_item) threshold_applied_score = individual_result["overall_score"] threshold_corrected_pairs.append( diff --git a/src/stickler/structured_object_evaluator/models/structured_model.py b/src/stickler/structured_object_evaluator/models/structured_model.py index 9f9f90fb..4a40d10d 100644 --- a/src/stickler/structured_object_evaluator/models/structured_model.py +++ b/src/stickler/structured_object_evaluator/models/structured_model.py @@ -1414,9 +1414,7 @@ def compare_field_raw(self, field_name: str, other_value: Any) -> float: # For non-StructuredModel fields, use existing logic return ComparisonHelper.compare_field_raw(self, field_name, other_value) - def compare_recursive( - self, other: "StructuredModel", *, _include_list_matching: bool = False - ) -> dict: + def compare_recursive(self, other: "StructuredModel") -> dict: """The ONE clean recursive function that handles everything. Enhanced to capture BOTH confusion matrix metrics AND similarity scores @@ -1436,9 +1434,7 @@ def compare_recursive( from .comparison_engine import ComparisonEngine engine = ComparisonEngine(self) - return engine.compare_recursive( - other, _include_list_matching=_include_list_matching - ) + return engine.compare_recursive(other) def _dispatch_field_comparison( self, field_name: str, gt_val: Any, pred_val: Any diff --git a/tests/test_list_reporting.py b/tests/test_list_reporting.py index 45081ef2..a56f0086 100644 --- a/tests/test_list_reporting.py +++ b/tests/test_list_reporting.py @@ -1,5 +1,6 @@ """Regression coverage for reporting the list comparisons scored by #332.""" +import json from typing import Any, Optional import pytest @@ -214,7 +215,9 @@ class Item(StructuredModel): class Parent(StructuredModel): # Runtime StructuredModel elements use recursive matching even when # the annotation also permits primitives with a field comparator. - items: list[Any] = ComparableField(comparator=ConstantComparator(), threshold=0.9) + items: list[Any] = ComparableField( + comparator=ConstantComparator(), threshold=0.9 + ) result = report([Item(code="a")], [Item(code="a")], model=Parent) assert result["field_scores"]["items"] == 1.0 @@ -241,7 +244,8 @@ class Note(BaseModel): ] -def test_reports_reuse_the_scoring_cost_matrix(): +@pytest.mark.parametrize("bulk", [False, True]) +def test_reports_reuse_the_scoring_cost_matrix(bulk, tmp_path): class CountingComparator(BaseComparator): calls = 0 @@ -253,7 +257,20 @@ class Tags(StructuredModel): items: list[str] = ComparableField(comparator=CountingComparator()) values = ["a", "b", "c", "d"] - result = report(values, values, model=Tags) + if bulk: + from stickler.structured_object_evaluator.bulk_structured_model_evaluator import ( + BulkStructuredModelEvaluator, + ) + + output = tmp_path / "results.jsonl" + evaluator = BulkStructuredModelEvaluator( + target_schema=Tags, individual_results_jsonl=str(output) + ) + evaluator.update(Tags(items=values), Tags(items=values)) + evaluator.compute() + result = json.loads(output.read_text(encoding="utf-8"))["comparison_result"] + else: + result = report(values, values, model=Tags) assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 4 assert result["non_matches"] == [] @@ -299,13 +316,287 @@ class Tags(StructuredModel): assert ChangingComparator.calls == 1 -def test_direct_non_match_reason_uses_the_supplied_threshold(): - entry = NonMatchesHelper().create_non_match_entry( +@pytest.mark.parametrize( + "non_matches,comparisons", + [(False, False), (True, False), (False, True), (True, True)], +) +def test_structured_list_reports_do_not_recompare_accepted_children( + non_matches, comparisons +): + class ChangingComparator(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return 1.0 if type(self).calls <= 3 else 0.0 + + class Item(StructuredModel): + code: str = ComparableField(comparator=ChangingComparator()) + + class Parent(StructuredModel): + items: list[Item] + + result = Parent(items=[Item(code="a")]).compare_with( + Parent(items=[Item(code="a")]), + include_confusion_matrix=True, + document_non_matches=non_matches, + document_field_comparisons=comparisons, + ) + + counts = result["confusion_matrix"]["fields"]["items"]["overall"] + assert (counts["tp"], counts["fd"]) == (1, 0) + assert ChangingComparator.calls == 3 + if non_matches: + assert result["non_matches"] == [] + else: + assert "non_matches" not in result + if comparisons: + assert result["field_comparisons"] == [ + { + "expected_key": "items[0].code", + "expected_value": "a", + "actual_key": "items[0].code", + "actual_value": "a", + "match": True, + "score": 1.0, + "weighted_score": 1.0, + "reason": "exact match", + } + ] + else: + assert "field_comparisons" not in result + + +def test_structured_list_reports_keep_scored_reordered_pair_indices(): + class CountingComparator(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return 1.0 if left == right else 0.0 + + class Item(StructuredModel): + code: str = ComparableField(comparator=CountingComparator()) + + class Parent(StructuredModel): + items: list[Item] + + ground_truth = Parent(items=[Item(code="a"), Item(code="b")]) + prediction = Parent(items=[Item(code="b"), Item(code="a")]) + ground_truth.compare_with(prediction) + scoring_calls = CountingComparator.calls + CountingComparator.calls = 0 + + result = ground_truth.compare_with( + prediction, + document_non_matches=True, + document_field_comparisons=True, + ) + + assert CountingComparator.calls == scoring_calls + assert result["non_matches"] == [] + assert { + (row["expected_key"], row["actual_key"], row["match"]) + for row in result["field_comparisons"] + } == { + ("items[0].code", "items[1].code", True), + ("items[1].code", "items[0].code", True), + } + + +def test_structured_list_rejected_pair_remains_atomic(): + class Item(StructuredModel): + match_threshold = 0.9 + code: str = ComparableField(comparator=ConstantComparator()) + + class Parent(StructuredModel): + items: list[Item] + + result = Parent(items=[Item(code="a")]).compare_with( + Parent(items=[Item(code="b")]), + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + + counts = result["confusion_matrix"]["fields"]["items"]["overall"] + assert (counts["tp"], counts["fd"]) == (0, 1) + assert [entry["field_path"] for entry in result["non_matches"]] == ["items[0]"] + assert [row["expected_key"] for row in result["field_comparisons"]] == ["items[0]"] + + +def test_deep_structured_list_reports_reuse_child_results_without_leaking_cache(): + class CountingComparator(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return 1.0 if left == right else 0.0 + + class Leaf(StructuredModel): + code: str = ComparableField(comparator=CountingComparator()) + + class Group(StructuredModel): + leaves: list[Leaf] + + class Parent(StructuredModel): + groups: list[Group] + + ground_truth = Parent(groups=[Group(leaves=[Leaf(code="a")])]) + prediction = Parent(groups=[Group(leaves=[Leaf(code="a")])]) + ground_truth.compare_with(prediction) + scoring_calls = CountingComparator.calls + CountingComparator.calls = 0 + + result = ground_truth.compare_with( + prediction, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + + assert CountingComparator.calls == scoring_calls + assert result["non_matches"] == [] + + def assert_no_private_metadata(value): + if isinstance(value, dict): + assert ( + not {"_list_matching", "_recursive_result", "pair_results"} + & value.keys() + ) + for child in value.values(): + assert_no_private_metadata(child) + elif isinstance(value, list): + for child in value: + assert_no_private_metadata(child) + + assert_no_private_metadata(result) + assert_no_private_metadata(ground_truth.compare_recursive(prediction)) + + +@pytest.mark.parametrize("method", ["create_non_match_entry", "create_entry"]) +def test_direct_non_match_reason_uses_the_supplied_threshold(method): + entry = getattr(NonMatchesHelper(), method)( "items", "a", "b", "FD", 0, 0.6, match_threshold=0.8 ) assert entry["reason"] == "below threshold (0.600 < 0.8)" +def test_accepted_structured_child_reports_share_field_threshold_tolerance(): + class NearThresholdComparator(BaseComparator): + def _compare(self, left, right): + return 0.7 - 1e-12 + + class Item(StructuredModel): + match_threshold = 0.5 + code: list[str] = ComparableField( + comparator=NearThresholdComparator(), threshold=0.7 + ) + + class Parent(StructuredModel): + items: list[Item] + + result = report([Item(code=["a"])], [Item(code=["b"])], model=Parent) + + child = result["confusion_matrix"]["fields"]["items"]["fields"]["code"] + assert child["overall"]["tp"] == 1 + assert result["non_matches"] == [] + (row,) = result["field_comparisons"] + assert row["match"] is True + assert "within threshold tolerance" in row["reason"] + + +def test_structured_child_custom_compare_with_override_is_preserved(): + calls = [] + + class Item(StructuredModel): + code: str = ComparableField(comparator=ExactComparator()) + + def compare_with(self, other, **kwargs): + calls.append(kwargs) + result = super().compare_with(other, **kwargs) + result["field_scores"]["code"] = 0.9 + return result + + class Parent(StructuredModel): + items: list[Item] + + result = report([Item(code="a")], [Item(code="a")], model=Parent) + + assert len(calls) == 3 # Existing override fallback: scoring and two reports. + assert result["field_comparisons"][0]["score"] == 0.9 + assert result["non_matches"] == [] + + +def test_accepted_structured_child_scalar_threshold_is_still_exact(): + class NearThresholdComparator(BaseComparator): + def _compare(self, left, right): + return 0.7 - 1e-12 + + class Item(StructuredModel): + match_threshold = 0.5 + code: str = ComparableField( + comparator=NearThresholdComparator(), + threshold=0.7, + clip_under_threshold=False, + ) + + class Parent(StructuredModel): + items: list[Item] + + result = report([Item(code="a")], [Item(code="b")], model=Parent) + child = result["confusion_matrix"]["fields"]["items"]["fields"]["code"] + assert child["overall"]["fd"] == 1 + assert result["non_matches"][0]["field_path"] == "items[0].code" + assert result["field_comparisons"][0]["match"] is False + + +def test_nested_compare_recursive_override_keeps_its_original_signature(): + calls = [] + + class Child(StructuredModel): + code: str = ComparableField(comparator=ExactComparator()) + + def compare_recursive(self, other): + calls.append(other) + return super().compare_recursive(other) + + class Parent(StructuredModel): + child: Child + + prediction = Parent(child=Child(code="a")) + result = Parent(child=Child(code="a")).compare_with( + prediction, document_non_matches=True, document_field_comparisons=True + ) + assert calls == [prediction.child] + assert result["non_matches"] == [] + assert result["field_comparisons"][0]["match"] is True + + +def test_nested_recursive_override_keeps_structured_list_report_fallback(): + class Leaf(StructuredModel): + code: str = ComparableField(comparator=ExactComparator()) + + class Child(StructuredModel): + items: list[Leaf] + + def compare_recursive(self, other): + return super().compare_recursive(other) + + class Parent(StructuredModel): + child: Child + + result = Parent(child=Child(items=[Leaf(code="a")])).compare_with( + Parent(child=Child(items=[Leaf(code="a")])), + document_non_matches=True, + document_field_comparisons=True, + ) + assert result["non_matches"] == [] + (row,) = result["field_comparisons"] + assert row["expected_key"] == "child.items[0].code" + assert row["match"] is True + + def test_private_pairing_details_do_not_appear_in_public_results(): ground_truth = Document(items=["a"]) prediction = Document(items=["a"]) @@ -313,14 +604,24 @@ def test_private_pairing_details_do_not_appear_in_public_results(): reported_result = report(["a"], ["a"]) assert set(recursive_result["fields"]["items"]) == { - "overall", "fields", "raw_similarity_score", "similarity_score", - "threshold_applied_score", "weight", + "overall", + "fields", + "raw_similarity_score", + "similarity_score", + "threshold_applied_score", + "weight", } assert set(reported_result["confusion_matrix"]["fields"]["items"]) >= { - "overall", "fields", "raw_similarity_score", "similarity_score", - "threshold_applied_score", "weight", + "overall", + "fields", + "raw_similarity_score", + "similarity_score", + "threshold_applied_score", + "weight", } - assert "_list_matching" not in reported_result["confusion_matrix"]["fields"]["items"] + assert ( + "_list_matching" not in reported_result["confusion_matrix"]["fields"]["items"] + ) @pytest.mark.parametrize("override", ["comparator", "match_threshold"]) From 9fa562b2019c8f0f8f21909b2624ac07b9614bf4 Mon Sep 17 00:00:00 2001 From: hugosmoreira Date: Fri, 9 Oct 2026 19:19:59 -0700 Subject: [PATCH 4/5] fix: keep list reporting state outside public results --- .../models/README.md | 11 +- .../models/comparison_dispatcher.py | 18 +- .../models/comparison_engine.py | 63 ++-- .../models/comparison_helper.py | 30 +- .../models/comparison_helper_base.py | 44 ++- .../models/field_comparator.py | 15 +- .../models/field_comparison_collector.py | 29 +- .../models/field_comparison_helper.py | 46 +-- .../models/non_match_collector.py | 40 +- .../models/non_matches_helper.py | 39 +- .../models/primitive_list_comparator.py | 60 +-- .../models/reporting_context.py | 19 + .../models/structured_list_comparator.py | 65 ++-- .../models/structured_model.py | 2 - tests/test_list_reporting_review.py | 357 ++++++++++++++++++ 15 files changed, 646 insertions(+), 192 deletions(-) create mode 100644 src/stickler/structured_object_evaluator/models/reporting_context.py create mode 100644 tests/test_list_reporting_review.py diff --git a/src/stickler/structured_object_evaluator/models/README.md b/src/stickler/structured_object_evaluator/models/README.md index a64cf55a..f41cb7df 100644 --- a/src/stickler/structured_object_evaluator/models/README.md +++ b/src/stickler/structured_object_evaluator/models/README.md @@ -32,10 +32,13 @@ its `from_json()` ingestion and `compare_with()` comparison pipeline. - `comparison_engine.py` — `ComparisonEngine`, the orchestrator behind `compare_with()`. Runs a single recursive traversal, then layers on confusion matrix, non-matches, field comparisons, and optional metrics. Structured-list - reporting reuses child traversals from scoring for the standard `compare_with` - implementation; that cache is removed from public results. Custom overrides - of `compare_with`/`compare_recursive` and direct report-helper calls retain - their comparison fallback. + reporting reuses accepted child traversals from the standard `compare_with` + implementation. `reporting_context.py` keeps pairings and scorer verdicts in + operation-local side maps, separate from public results; child traversals are + retained only when a report needs them. Both collectors share the model's + fallback matching settings for direct calls and custom overrides, which keep + their existing call signatures. Nested field rows use the scored metrics to + classify matches instead of applying an element threshold to a list average. - `comparison_dispatcher.py`, `field_comparator.py`, `primitive_list_comparator.py`, `structured_list_comparator.py`, `hungarian_helper.py` — dispatch and per-type comparison, including Hungarian diff --git a/src/stickler/structured_object_evaluator/models/comparison_dispatcher.py b/src/stickler/structured_object_evaluator/models/comparison_dispatcher.py index 8a50b728..de11078e 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_dispatcher.py +++ b/src/stickler/structured_object_evaluator/models/comparison_dispatcher.py @@ -10,6 +10,7 @@ from .configuration_helper import ConfigurationHelper from .null_helper import NullHelper +from .reporting_context import ReportingContext from .result_helper import ResultHelper from .structured_model import StructuredModel @@ -26,13 +27,18 @@ class ComparisonDispatcher: It uses match-statement based dispatch for clear, traceable logic flow. """ - def __init__(self, model: "StructuredModel"): + def __init__( + self, + model: "StructuredModel", + report_context: Optional[ReportingContext] = None, + ): """Initialize dispatcher with the ground truth model. Args: model: The ground truth StructuredModel instance """ self.model = model + self.report_context = report_context # Initialize comparators lazily to avoid circular imports self._field_comparator = None @@ -45,7 +51,7 @@ def field_comparator(self): if self._field_comparator is None: from .field_comparator import FieldComparator - self._field_comparator = FieldComparator(self.model) + self._field_comparator = FieldComparator(self.model, self.report_context) return self._field_comparator @property @@ -54,7 +60,9 @@ def primitive_list_comparator(self): if self._primitive_list_comparator is None: from .primitive_list_comparator import PrimitiveListComparator - self._primitive_list_comparator = PrimitiveListComparator(self.model) + self._primitive_list_comparator = PrimitiveListComparator( + self.model, self.report_context + ) return self._primitive_list_comparator @property @@ -63,7 +71,9 @@ def structured_list_comparator(self): if self._structured_list_comparator is None: from .structured_list_comparator import StructuredListComparator - self._structured_list_comparator = StructuredListComparator(self.model) + self._structured_list_comparator = StructuredListComparator( + self.model, self.report_context + ) return self._structured_list_comparator def dispatch_field_comparison( diff --git a/src/stickler/structured_object_evaluator/models/comparison_engine.py b/src/stickler/structured_object_evaluator/models/comparison_engine.py index 09597a85..d0c6d417 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_engine.py +++ b/src/stickler/structured_object_evaluator/models/comparison_engine.py @@ -10,6 +10,8 @@ from stickler.structured_object_evaluator.models.bbox import MAPCalculator from stickler.utils.deprecation import warn_once +from .reporting_context import ReportingContext + if TYPE_CHECKING: from .confidence import ConfidenceMetric from .structured_model import StructuredModel @@ -81,16 +83,8 @@ def confusion_matrix_builder(self): self._confusion_matrix_builder = ConfusionMatrixBuilder(self.model) return self._confusion_matrix_builder - @staticmethod - def _drop_list_matching(result: Dict[str, Any]) -> None: - """Remove scoring-only pairing details from a public result tree.""" - for field_result in result.get("fields", {}).values(): - if isinstance(field_result, dict): - field_result.pop("_list_matching", None) - ComparisonEngine._drop_list_matching(field_result) - def compare_recursive( - self, other: "StructuredModel", *, _include_list_matching: bool = False + self, other: "StructuredModel", *, _report_context: Optional[ReportingContext] = None ) -> Dict[str, Any]: """The core recursive comparison function. @@ -152,6 +146,14 @@ def compare_recursive( "non_matches": [], } + # A fresh dispatcher owns this operation's side context. Reusing the + # engine cannot retain pairings from a prior call or a failed traversal. + if _report_context is None: + dispatcher = self.dispatcher + else: + from .comparison_dispatcher import ComparisonDispatcher + dispatcher = ComparisonDispatcher(self.model, _report_context) + # Score percolation variables total_score = 0.0 total_weight = 0.0 @@ -164,7 +166,7 @@ def compare_recursive( pred_val = getattr(other, field_name, None) # Enhanced dispatch returns both metrics AND scores - field_result = self.dispatcher.dispatch_field_comparison(field_name, gt_val, pred_val) + field_result = dispatcher.dispatch_field_comparison(field_name, gt_val, pred_val) result["fields"][field_name] = field_result @@ -187,8 +189,6 @@ def compare_recursive( if total_weight > 0: result["overall"]["similarity_score"] = total_score / total_weight - if not _include_list_matching: - self._drop_list_matching(result) return result def compare_with( @@ -204,7 +204,7 @@ def compare_with( confidence_metrics: Optional[List["ConfidenceMetric"]] = None, add_bbox_metrics: bool = False, bbox_iou_thresholds: Optional[Union[float, Iterable[float]]] = None, - _retain_recursive_result: bool = False, + _report_context: Optional[ReportingContext] = None, ) -> Dict[str, Any]: """Compare with another instance using single traversal. @@ -262,7 +262,15 @@ def compare_with( >>> print(result["confusion_matrix"]["overall"]["tp"]) """ # SINGLE TRAVERSAL: Get everything in one pass - recursive_result = self.compare_recursive(other, _include_list_matching=True) + report_context = _report_context + if report_context is None and ( + document_non_matches + or document_field_comparisons + or add_confidence_metrics + or add_bbox_metrics + ): + report_context = ReportingContext() + recursive_result = self.compare_recursive(other, _report_context=report_context) # Extract scoring information from recursive result field_scores = {} @@ -299,13 +307,17 @@ def compare_with( # Add optional non-match documentation if document_non_matches: # Use NonMatchCollector for enhanced object-level non-matches - non_matches = self.non_match_collector.collect_enhanced_non_matches(recursive_result, other) + non_matches = self.non_match_collector.collect_enhanced_non_matches( + recursive_result, other, report_context + ) result["non_matches"] = non_matches # Add optional field comparison documentation if document_field_comparisons: # Use FieldComparisonCollector for comprehensive field-level comparisons - field_comparisons = self.field_comparison_collector.collect_field_comparisons(recursive_result, other) + field_comparisons = self.field_comparison_collector.collect_field_comparisons( + recursive_result, other, report_context + ) result["field_comparisons"] = field_comparisons # If add_confidence_metrics is requested, add confidence metrics. @@ -325,7 +337,7 @@ def compare_with( if "field_comparisons" not in result: field_comparisons = ( self.field_comparison_collector.collect_field_comparisons( - recursive_result, other + recursive_result, other, report_context ) ) result["field_comparisons"] = field_comparisons @@ -379,7 +391,7 @@ def compare_with( if "field_comparisons" not in result: field_comparisons = ( self.field_comparison_collector.collect_field_comparisons( - recursive_result, other + recursive_result, other, report_context ) ) result["field_comparisons"] = field_comparisons @@ -454,16 +466,11 @@ def compare_with( if pred_bboxes: result["prediction_bboxes"] = pred_bboxes - # The collectors have consumed the scoring-only pairings. Keep the - # public recursive/confusion-matrix result shape unchanged. - if _retain_recursive_result: - # Internal structured-list scoring passes this same traversal to - # the report collectors instead of comparing a child again. - result["_recursive_result"] = recursive_result - else: - self._drop_list_matching(recursive_result) - if "confusion_matrix" in result: - self._drop_list_matching(result["confusion_matrix"]) + if _report_context is not None: + # An accepted structured-list pair needs this traversal for its + # parent's reports. It never becomes part of the returned result. + _report_context.recursive_result = recursive_result + _report_context.field_scores = field_scores # If evaluator_format is requested, transform the result if evaluator_format: diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper.py b/src/stickler/structured_object_evaluator/models/comparison_helper.py index f030a0c3..e2c07966 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper.py @@ -206,7 +206,7 @@ def compare_unordered_lists( clip_under_threshold: bool = True, model_cls=None, field_name: str = "", - pair_sink: List[tuple] | None = None, + matching_sink: Dict[str, Any] | None = None, ) -> Dict[str, Any]: """Compare two lists as unordered collections using Hungarian matching. @@ -223,8 +223,8 @@ def compare_unordered_lists( default to a falsy value so a caller with no field in hand still gets the gate -- it refuses the same pairs either way, and only the warning is less specific. - pair_sink: Optional list populated with the selected (ground-truth - index, prediction index, score) tuples from this scoring pass. + matching_sink: Optional side map populated with selected pairs and + the classification decisions made by this scoring pass. Returns: Dictionary with confusion matrix metrics including: @@ -323,15 +323,13 @@ def compare_unordered_lists( model_cls=model_cls, field_name=field_name, warn_selected=True, ) - if pair_sink is not None: - pair_sink.extend(matched_pairs) - return ComparisonHelper.unordered_list_metrics( matched_pairs=matched_pairs, clip_under_threshold=clip_under_threshold, gt_list=gt_list, pred_list=pred_list, classification_threshold=classification_threshold, + matching_sink=matching_sink, ) @staticmethod @@ -341,6 +339,7 @@ def unordered_list_metrics( pred_list: List[Any], classification_threshold: float, clip_under_threshold: bool = True, + matching_sink: Dict[str, Any] | None = None, ): """ Compare two lists as unordered collections using Hungarian matching. @@ -359,9 +358,17 @@ def unordered_list_metrics( tp = 0 # True positives (score >= threshold) fd = 0 # False discoveries (score < threshold, including 0) - for i, j, score in matched_pairs: - # Use ThresholdHelper for consistent threshold checking - if ThresholdHelper.is_above_threshold(score, classification_threshold): + verdicts = [ + ThresholdHelper.is_above_threshold(score, classification_threshold) + for _, _, score in matched_pairs + ] + if matching_sink is not None: + matching_sink.update( + pairs=matched_pairs, threshold=classification_threshold, verdicts=verdicts + ) + + for is_match in verdicts: + if is_match: tp += 1 else: # All matches below threshold are False Discoveries, including 0.0 scores @@ -409,9 +416,8 @@ def unordered_list_metrics( # is deliberately NOT affected: the counts above already ran, so a # sub-threshold pair stays one `fd` either way. Only the score moves. threshold_applied_similarities = [] - for _, _, score in matched_pairs: - # Use ThresholdHelper for consistent threshold checking - if ThresholdHelper.is_above_threshold(score, classification_threshold): + for (_, _, score), is_match in zip(matched_pairs, verdicts): + if is_match: threshold_applied_similarities.append(score) elif clip_under_threshold: # Below threshold gets 0.0 (same as individual comparison clipping) diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index 95474aa2..b193f1af 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -1,13 +1,15 @@ """Base class for comparison helpers in StructuredModel comparisons.""" +import inspect import math from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional from stickler.comparators.base import BaseComparator -from .comparison_helper import _match_non_structured_lists +from .comparison_helper import ComparisonHelper, _match_non_structured_lists from .hungarian_helper import HungarianHelper +from .reporting_context import ReportingContext DEFAULT_MATCH_THRESHOLD = 0.7 @@ -114,7 +116,7 @@ def process_matched_pairs( matched_pairs_with_scores: List[tuple], match_threshold: float, verdicts: Optional[List[bool]] = None, - pair_results: Optional[Dict[tuple, Dict[str, Any]]] = None, + pair_results: Optional[Dict[tuple, ReportingContext]] = None, ) -> List[Dict[str, Any]]: """Process matched pairs and create entries. @@ -153,6 +155,13 @@ def process_matched_pairs( pair_result = ( pair_results.get((gt_idx, pred_idx)) if pair_results else None ) + # Helpers implementing the pre-cache abstract signature remain + # valid extensions; only opt-in implementations receive context. + pair_kwargs = {} + if pair_result is not None and "pair_result" in inspect.signature( + self._extract_entries_from_objects + ).parameters: + pair_kwargs["pair_result"] = pair_result extracted_entries = self._extract_entries_from_objects( field_name, gt_item, @@ -162,7 +171,7 @@ def process_matched_pairs( is_match, similarity_score, reason, - **({"pair_result": pair_result} if pair_result is not None else {}), + **pair_kwargs, ) entries.extend(extracted_entries) @@ -302,7 +311,8 @@ def _extract_entries_from_objects( pred_index: Optional[int], is_match: bool, similarity_score: float, - reason: str + reason: str, + pair_result: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Extract entries from structured model objects. Must be implemented by subclasses. @@ -315,12 +325,29 @@ def _extract_entries_from_objects( is_match: Whether the overall objects match similarity_score: Overall similarity score reason: Overall comparison reason + pair_result: Optional accepted child traversal from scoring Returns: List of entries specific to the helper type """ pass + @staticmethod + def resolve_list_matching(model, field_name, gt_list, matching=None): + """Resolve one fallback contract for both collectors. + + Match the dispatcher's structured-list branch. Other lists use the + owning field's comparator and threshold, including its class gate. + """ + from .structured_model import StructuredModel + + if matching is not None: + return {"matching": matching} + if gt_list and isinstance(gt_list[0], StructuredModel): + return {} + info = model._get_comparison_info(field_name) + return {"comparator": info.comparator, "match_threshold": info.threshold} + def collect_list_entries( self, field_name: str, gt_list: List[Any], pred_list: List[Any], comparator: Optional[BaseComparator] = None, @@ -368,6 +395,15 @@ def collect_list_entries( if match_threshold is None: match_threshold = self.get_match_threshold(gt_list or pred_list) verdicts = None + if comparator is not None: + # A direct collector or legacy override has no side context. + # Reuse the primitive scorer's classification (and tolerance). + decisions = {} + ComparisonHelper.unordered_list_metrics( + matched_pairs_with_scores, gt_list, pred_list, + match_threshold, matching_sink=decisions, + ) + verdicts = decisions["verdicts"] entries.extend(self.process_matched_pairs( field_name, gt_list, pred_list, matched_pairs_with_scores, diff --git a/src/stickler/structured_object_evaluator/models/field_comparator.py b/src/stickler/structured_object_evaluator/models/field_comparator.py index 62e18df6..8824a825 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparator.py +++ b/src/stickler/structured_object_evaluator/models/field_comparator.py @@ -4,7 +4,9 @@ primitive and structured fields during structured object comparison. """ -from typing import TYPE_CHECKING, Any, Dict +from typing import TYPE_CHECKING, Any, Dict, Optional + +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -21,13 +23,16 @@ class FieldComparator: - Score calculation and metrics generation """ - def __init__(self, model: "StructuredModel"): + def __init__( + self, model: "StructuredModel", report_context: Optional[ReportingContext] = None + ): """Initialize comparator with the ground truth model. Args: model: The ground truth StructuredModel instance """ self.model = model + self.report_context = report_context def compare_primitive_with_scores( self, @@ -167,8 +172,12 @@ def compare_structured_field( from .structured_model import StructuredModel if type(gt_val).compare_recursive is StructuredModel.compare_recursive: + child_context = None + if self.report_context is not None: + child_context = ReportingContext() + self.report_context.children[field_name] = child_context nested_result = ComparisonEngine(gt_val).compare_recursive( - pred_val, _include_list_matching=True + pred_val, _report_context=child_context ) else: # Existing overrides need not accept internal metadata options. diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index f3253ff0..287b390b 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -5,9 +5,10 @@ structured object comparison. """ import math -from typing import TYPE_CHECKING, Any, Dict, List +from typing import TYPE_CHECKING, Any, Dict, List, Optional from .field_comparison_helper import FieldComparisonHelper +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -33,7 +34,8 @@ def __init__(self, model: "StructuredModel"): def collect_field_comparisons( self, recursive_result: dict, - other: "StructuredModel" + other: "StructuredModel", + report_context: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Collect all field comparisons with detailed metadata. @@ -93,22 +95,10 @@ def collect_field_comparisons( and isinstance(pred_val, list) ): # Use FieldComparisonHelper for primitive list collection - matching = field_result.get("_list_matching") - if matching is None: - from .structured_model import StructuredModel - - if gt_val and isinstance(gt_val[0], StructuredModel): - # A custom recursive result may lack cached pairings. - # Structured lists use their element model's settings. - matching_kwargs = {} - else: - info = self.model._get_comparison_info(field_name) - matching_kwargs = { - "comparator": info.comparator, - "match_threshold": info.threshold, - } - else: - matching_kwargs = {"matching": matching} + matching_kwargs = self.helper.resolve_list_matching( + self.model, field_name, gt_val, + report_context.lists.get(field_name) if report_context else None, + ) list_comparisons = self.helper.collect_list_entries( field_name, gt_val, pred_val, **matching_kwargs ) @@ -125,7 +115,8 @@ def collect_field_comparisons( # Recursively collect field comparisons from nested objects nested_collector = FieldComparisonCollector(gt_val) nested_comparisons = nested_collector.collect_field_comparisons( - field_result, pred_val + field_result, pred_val, + report_context.children.get(field_name) if report_context else None, ) # Prefix nested field paths with the parent field name for nested_comp in nested_comparisons: diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py index 9d572757..fb5acfb7 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py @@ -3,7 +3,7 @@ from typing import Any, Dict, List, Optional from .comparison_helper_base import ComparisonHelperBase -from .threshold_helper import ThresholdHelper +from .reporting_context import ReportingContext class FieldComparisonHelper(ComparisonHelperBase): @@ -93,7 +93,7 @@ def _extract_entries_from_objects( is_match: bool, similarity_score: float, reason: str, - pair_result: Optional[Dict[str, Any]] = None, + pair_result: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Extract field-level comparisons from structured model objects. @@ -120,36 +120,38 @@ def _extract_entries_from_objects( and isinstance(pred_object, StructuredModel) ): # Reuse the child scores already computed during list scoring. - comparison_result = ( - pair_result - if pair_result is not None - else gt_object.compare_with( - pred_object, - document_non_matches=False, - include_confusion_matrix=False, + if pair_result is not None: + field_scores = pair_result.field_scores + field_results = pair_result.recursive_result.get("fields", {}) + elif type(gt_object).compare_with is StructuredModel.compare_with: + from .comparison_engine import ComparisonEngine + + # Direct helper calls also need the scorer's field verdicts. + context = ReportingContext() + ComparisonEngine(gt_object).compare_with(pred_object, _report_context=context) + field_scores = context.field_scores + field_results = context.recursive_result.get("fields", {}) + else: + comparison_result = gt_object.compare_with( + pred_object, document_non_matches=False, include_confusion_matrix=False, ) - ) + field_scores = comparison_result.get("field_scores", {}) + field_results = {} field_comparisons = [] # Extract field scores and create comparison entries - for nested_field_name, field_score in comparison_result.get("field_scores", {}).items(): + for nested_field_name, field_score in field_scores.items(): gt_nested_val = getattr(gt_object, nested_field_name, None) pred_nested_val = getattr(pred_object, nested_field_name, None) # Get field configuration for threshold info = gt_object._get_comparison_info(nested_field_name) field_is_match = field_score >= info.threshold - if ( - isinstance(gt_nested_val, list) - and gt_nested_val - and not isinstance(gt_nested_val[0], StructuredModel) - ): - # Primitive-list scoring accepts values within tolerance; - # scalar and structured-object thresholds remain exact. - field_is_match = ThresholdHelper.is_above_threshold( - field_score, info.threshold - ) + field_result = field_results.get(nested_field_name) + if field_result is not None: + metrics = field_result.get("overall", field_result) + field_is_match = not any(metrics.get(key, 0) for key in ("fd", "fa", "fn")) # Create field paths with indices expected_key = f"{field_name}[{gt_index}].{nested_field_name}" if gt_index is not None else f"{field_name}[].{nested_field_name}" @@ -157,6 +159,8 @@ def _extract_entries_from_objects( # Create reason for this specific field field_reason = self.generate_comparison_reason(field_is_match, field_score, info.threshold) + if field_result is not None and "fields" in field_result and not field_is_match: + field_reason = "non-matching or unmatched items" # Handle missing fields if pred_nested_val is None and gt_nested_val is not None: diff --git a/src/stickler/structured_object_evaluator/models/non_match_collector.py b/src/stickler/structured_object_evaluator/models/non_match_collector.py index 9d85808f..80cb6a6c 100644 --- a/src/stickler/structured_object_evaluator/models/non_match_collector.py +++ b/src/stickler/structured_object_evaluator/models/non_match_collector.py @@ -4,10 +4,11 @@ and documentation of non-matching fields during structured object comparison. """ -from typing import TYPE_CHECKING, Any, Dict, List +from typing import TYPE_CHECKING, Any, Dict, List, Optional from .non_match_field import NonMatchType from .non_matches_helper import NonMatchesHelper +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -35,7 +36,8 @@ def __init__(self, model: "StructuredModel"): def collect_enhanced_non_matches( self, recursive_result: dict, - other: "StructuredModel" + other: "StructuredModel", + report_context: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Collect enhanced non-matches with object-level granularity. @@ -85,34 +87,11 @@ def collect_enhanced_non_matches( ) all_non_matches.extend(null_non_matches) - # Check if this is a list field that should use object-level collection - elif ( - isinstance(gt_val, list) - and isinstance(pred_val, list) - and gt_val - and isinstance(gt_val[0], StructuredModel) - ): - # Use NonMatchesHelper for object-level collection - object_non_matches = self.helper.collect_list_non_matches( - field_name, gt_val, pred_val, - matching=field_result.get("_list_matching"), + elif isinstance(gt_val, list) and isinstance(pred_val, list): + matching_kwargs = self.helper.resolve_list_matching( + self.model, field_name, gt_val, + report_context.lists.get(field_name) if report_context else None, ) - all_non_matches.extend(object_non_matches) - - elif ( - isinstance(gt_val, list) - and isinstance(pred_val, list) - ): - # Use NonMatchesHelper for object-level collection - matching = field_result.get("_list_matching") - if matching is None: - info = self.model._get_comparison_info(field_name) - matching_kwargs = { - "comparator": info.comparator, - "match_threshold": info.threshold, - } - else: - matching_kwargs = {"matching": matching} object_non_matches = self.helper.collect_list_non_matches( field_name, gt_val, pred_val, **matching_kwargs ) @@ -137,7 +116,8 @@ def collect_enhanced_non_matches( # Recursively collect non-matches from nested objects nested_collector = NonMatchCollector(gt_val) nested_non_matches = nested_collector.collect_enhanced_non_matches( - field_result, pred_val + field_result, pred_val, + report_context.children.get(field_name) if report_context else None, ) # Prefix nested field paths with the parent field name for nested_nm in nested_non_matches: diff --git a/src/stickler/structured_object_evaluator/models/non_matches_helper.py b/src/stickler/structured_object_evaluator/models/non_matches_helper.py index bc365e0c..bd071994 100644 --- a/src/stickler/structured_object_evaluator/models/non_matches_helper.py +++ b/src/stickler/structured_object_evaluator/models/non_matches_helper.py @@ -6,6 +6,7 @@ from .comparison_helper_base import ComparisonHelperBase from .non_match_field import NonMatchType +from .reporting_context import ReportingContext class NonMatchesHelper(ComparisonHelperBase): @@ -49,7 +50,6 @@ def create_non_match_entry( object_index: int = None, similarity_score: float = None, match_threshold: Optional[float] = None, - reason: Optional[str] = None, ) -> Dict[str, Any]: """Create a non-match entry for detailed analysis. @@ -61,11 +61,27 @@ def create_non_match_entry( object_index: Optional index of the object in the list for indexed field paths similarity_score: Similarity score for FD entries match_threshold: Threshold used to explain an FD when supplied - reason: Already-classified FD explanation from the scoring pass Returns: Dictionary with non-match information """ + reason = None + if non_match_type == "FD" and similarity_score is not None: + threshold = ( + match_threshold if match_threshold is not None + else self.get_match_threshold([gt_object] if gt_object else [pred_object]) + ) + reason = self.generate_comparison_reason(False, similarity_score, threshold) + return self._create_non_match_entry( + field_name, gt_object, pred_object, non_match_type, object_index, + similarity_score, reason, + ) + + def _create_non_match_entry( + self, field_name, gt_object, pred_object, non_match_type, + object_index=None, similarity_score=None, reason=None, + ): + """Format an entry using an already-classified reason, without a threshold.""" # Generate indexed field path if object_index provided indexed_field_path = ( f"{field_name}[{object_index}]" if object_index is not None else field_name @@ -89,16 +105,7 @@ def create_non_match_entry( if non_match_type == "FD": # False Discovery: matched but below threshold if similarity_score is not None: - if reason is None: - threshold = ( - match_threshold - if match_threshold is not None - else self.get_match_threshold( - [gt_object] if gt_object else [pred_object] - ) - ) - reason = f"below threshold ({similarity_score:.3f} < {threshold})" - entry["reason"] = reason + entry["reason"] = reason or "below threshold" entry["similarity"] = similarity_score entry["similarity_score"] = similarity_score else: @@ -156,7 +163,7 @@ def _extract_entries_from_objects( is_match: bool, similarity_score: float, reason: str, - pair_result: Optional[Dict[str, Any]] = None, + pair_result: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Extract non-match entries from structured model objects. @@ -196,7 +203,7 @@ def _extract_entries_from_objects( non_match_type = "FD" object_index = gt_index - entry = self.create_non_match_entry( + entry = self._create_non_match_entry( field_name, gt_object, pred_object, @@ -213,7 +220,7 @@ def _extract_field_level_non_matches( gt_object: Any, pred_object: Any, object_index: int, - pair_result: Optional[Dict[str, Any]] = None, + pair_result: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Extract field-level non-matches from a threshold-passing object pair. @@ -239,7 +246,7 @@ def _extract_field_level_non_matches( nested_non_matches = NonMatchCollector( gt_object ).collect_enhanced_non_matches( - pair_result["recursive_result"], pred_object + pair_result.recursive_result, pred_object, pair_result ) field_non_matches = [] diff --git a/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py b/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py index 48fa752c..e3d1ea01 100644 --- a/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py @@ -21,24 +21,30 @@ - Architecturally less pure than type-based structure (primitives flat, structured hierarchical) """ -from typing import TYPE_CHECKING, Any, List +from typing import TYPE_CHECKING, Any, List, Optional if TYPE_CHECKING: from .structured_model import StructuredModel -from .threshold_helper import ThresholdHelper +from .comparison_helper import ComparisonHelper +from .reporting_context import ReportingContext class PrimitiveListComparator: """Handles comparison of List[primitive] fields using Hungarian matching.""" - def __init__(self, parent_model: "StructuredModel"): + def __init__( + self, + parent_model: "StructuredModel", + report_context: Optional[ReportingContext] = None, + ): """Initialize the comparator with reference to parent model. Args: parent_model: The StructuredModel instance that owns the list field """ self.parent_model = parent_model + self.report_context = report_context def compare_primitive_list_with_scores( self, gt_list: List[Any], pred_list: List[Any], field_name: str @@ -105,16 +111,36 @@ def compare_primitive_list_with_scores( # the zeroing happens inside `unordered_list_metrics`, upstream of the # `threshold_applied_score = raw_similarity` line below, so that line # preserved a score that had already been thrown away. - matched_pairs = [] - match_result = self.parent_model._compare_unordered_lists( - gt_list, - pred_list, - comparator, - threshold, - info.clip_under_threshold, - field_name=field_name, - pair_sink=matched_pairs, - ) + from .structured_model import StructuredModel + + if ( + self.report_context is not None + and type(self.parent_model)._compare_unordered_lists + is StructuredModel._compare_unordered_lists + ): + matching = {} + match_result = ComparisonHelper.compare_unordered_lists( + gt_list, + pred_list, + comparator, + threshold, + info.clip_under_threshold, + model_cls=type(self.parent_model), + field_name=field_name, + matching_sink=matching, + ) + self.report_context.lists[field_name] = matching + else: + # Existing overrides receive only their original arguments. Without + # built-in scoring data, collectors use the shared fallback matcher. + match_result = self.parent_model._compare_unordered_lists( + gt_list, + pred_list, + comparator, + threshold, + info.clip_under_threshold, + field_name=field_name, + ) # Extract the counts from the match result tp = match_result.get("tp", 0) @@ -136,12 +162,4 @@ def compare_primitive_list_with_scores( "similarity_score": raw_similarity, "threshold_applied_score": threshold_applied_score, "weight": weight, - "_list_matching": { - "pairs": matched_pairs, - "threshold": threshold, - "verdicts": [ - ThresholdHelper.is_above_threshold(score, threshold) - for _, _, score in matched_pairs - ], - }, } diff --git a/src/stickler/structured_object_evaluator/models/reporting_context.py b/src/stickler/structured_object_evaluator/models/reporting_context.py new file mode 100644 index 00000000..6a317bc2 --- /dev/null +++ b/src/stickler/structured_object_evaluator/models/reporting_context.py @@ -0,0 +1,19 @@ +"""Operation-local scoring data shared with report collectors, never serialized.""" + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class ReportingContext: + """Side maps keyed by field name at each level of the model tree. + + List pair results hold child contexts only for accepted pairs. Keeping these + separate from metric dictionaries makes every comparison result safe to + return directly, including the deprecated field-dispatch entry point. + """ + + lists: dict[str, dict[str, Any]] = field(default_factory=dict) + children: dict[str, "ReportingContext"] = field(default_factory=dict) + recursive_result: dict[str, Any] = field(default_factory=dict) + field_scores: dict[str, float] = field(default_factory=dict) diff --git a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py index aa3b3a36..a3cd298a 100644 --- a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py @@ -13,6 +13,7 @@ from .comparison_helper import ComparisonHelper from .hungarian_helper import HungarianHelper from .metrics_helper import MetricsHelper +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -21,13 +22,16 @@ class StructuredListComparator: """Handles comparison of List[StructuredModel] fields using Hungarian matching.""" - def __init__(self, parent_model: "StructuredModel"): + def __init__( + self, parent_model: "StructuredModel", report_context: ReportingContext | None = None + ): """Initialize the comparator with reference to parent model. Args: parent_model: The StructuredModel instance that owns the list field """ self.parent_model = parent_model + self.report_context = report_context def compare_struct_list_with_scores( self, @@ -67,12 +71,21 @@ def compare_struct_list_with_scores( matched_pairs, _matched_gt_indices, _matched_pred_indices, + verdicts, ) = self._calculate_object_level_metrics(gt_list, pred_list, match_threshold) # Calculate raw similarity score using extracted method - pair_results = {} + matching = None + if self.report_context is not None: + matching = { + "pairs": matched_pairs, + "threshold": match_threshold, + "verdicts": verdicts, + "pair_results": {}, + } + self.report_context.lists[field_name] = matching raw_similarity = self._calculate_struct_list_similarity( - matched_pairs, gt_list, pred_list, info, pair_results + matched_pairs, gt_list, pred_list, info, matching ) # CRITICAL FIX: For structured lists, we NEVER clip under threshold - partial matches are important @@ -85,7 +98,7 @@ def compare_struct_list_with_scores( gt_list, pred_list, matched_pairs, - match_threshold, + verdicts, ) # Build final result structure @@ -96,14 +109,6 @@ def compare_struct_list_with_scores( "similarity_score": raw_similarity, "threshold_applied_score": threshold_applied_score, "weight": weight, - "_list_matching": { - "pairs": matched_pairs, - "threshold": match_threshold, - "verdicts": [ - score >= match_threshold for _, _, score in matched_pairs - ], - "pair_results": pair_results, - }, } return final_result @@ -122,7 +127,7 @@ def _calculate_object_level_metrics( match_threshold: Threshold for considering objects as matches Returns: - Tuple of (object_metrics_dict, matched_pairs, matched_gt_indices, matched_pred_indices) + Object metrics, pairs, matched GT/prediction indices, and pair verdicts. """ # Use Hungarian matching for OBJECT-LEVEL counts hungarian_helper = HungarianHelper() @@ -132,8 +137,9 @@ def _calculate_object_level_metrics( # Count OBJECTS, not individual fields tp_objects = 0 # Objects with similarity >= match_threshold fd_objects = 0 # Objects with similarity < match_threshold - for gt_idx, pred_idx, similarity in matched_pairs: - if similarity >= match_threshold: + verdicts = [score >= match_threshold for _, _, score in matched_pairs] + for is_match in verdicts: + if is_match: tp_objects += 1 else: fd_objects += 1 @@ -161,6 +167,7 @@ def _calculate_object_level_metrics( matched_pairs, matched_gt_indices, matched_pred_indices, + verdicts, ) def _calculate_struct_list_similarity( @@ -169,7 +176,7 @@ def _calculate_struct_list_similarity( gt_list: List["StructuredModel"], pred_list: List["StructuredModel"], info: "ComparableField", - pair_results: Dict[tuple, Dict[str, Any]], + matching: Dict[str, Any] | None = None, ) -> float: """Calculate raw similarity score for structured list. @@ -177,7 +184,7 @@ def _calculate_struct_list_similarity( gt_list: Ground truth list pred_list: Predicted list info: Field comparison info - pair_results: Receives child traversals for report-time reuse + matching: Side map receiving accepted child traversals when reporting Returns: Raw similarity score between 0.0 and 1.0 @@ -187,7 +194,7 @@ def _calculate_struct_list_similarity( # Updated code to not use helper that was calling Hungarian match again, and instead use already generated matched pairs threshold_corrected_pairs = [] - for gt_idx, pred_idx, raw_score in matched_pairs: + for pair_index, (gt_idx, pred_idx, raw_score) in enumerate(matched_pairs): if gt_idx < len(gt_list) and pred_idx < len(pred_list): gt_item = gt_list[gt_idx] pred_item = pred_list[pred_idx] @@ -201,14 +208,16 @@ def _calculate_struct_list_similarity( ) else: # Use individual comparison with threshold application (same as .compare_with()) - if type(gt_item).compare_with is StructuredModel.compare_with: + if ( + matching is not None + and matching["verdicts"][pair_index] + and type(gt_item).compare_with is StructuredModel.compare_with + ): + child_context = ReportingContext() individual_result = ComparisonEngine(gt_item).compare_with( - pred_item, _retain_recursive_result=True + pred_item, _report_context=child_context ) - pair_results[(gt_idx, pred_idx)] = { - "field_scores": individual_result["field_scores"], - "recursive_result": individual_result.pop("_recursive_result"), - } + matching["pair_results"][(gt_idx, pred_idx)] = child_context else: # Preserve custom compare_with overrides, which may not # expose an internal traversal for report reuse. @@ -237,7 +246,7 @@ def _calculate_nested_field_metrics( gt_list: List["StructuredModel"], pred_list: List["StructuredModel"], matched_pairs: List, - match_threshold: float, + verdicts: List[bool], ) -> Dict[str, Dict[str, Any]]: """Calculate field-level details for nested structure with threshold-gated recursion. @@ -250,7 +259,7 @@ def _calculate_nested_field_metrics( gt_list: Ground truth list pred_list: Predicted list matched_pairs: List of (gt_idx, pred_idx, similarity) tuples - match_threshold: Match threshold for threshold-gating (NOW PROPERLY USED!) + verdicts: Object-level acceptance decisions from scoring Returns: Dictionary mapping field names to their metrics @@ -269,8 +278,8 @@ def _calculate_nested_field_metrics( # Filter to good matches only - poor matches get no recursive analysis good_matched_pairs = [ (gt_idx, pred_idx, similarity) - for gt_idx, pred_idx, similarity in matched_pairs - if similarity >= match_threshold + for (gt_idx, pred_idx, similarity), is_match in zip(matched_pairs, verdicts) + if is_match ] if good_matched_pairs: diff --git a/src/stickler/structured_object_evaluator/models/structured_model.py b/src/stickler/structured_object_evaluator/models/structured_model.py index 4a40d10d..b4a14410 100644 --- a/src/stickler/structured_object_evaluator/models/structured_model.py +++ b/src/stickler/structured_object_evaluator/models/structured_model.py @@ -1341,7 +1341,6 @@ def _compare_unordered_lists( threshold: float, clip_under_threshold: bool = True, field_name: str = "", - pair_sink: List[tuple] | None = None, ) -> Dict[str, Any]: """Compare two lists as unordered collections using Hungarian matching. @@ -1368,7 +1367,6 @@ def _compare_unordered_lists( clip_under_threshold, model_cls=self.__class__, field_name=field_name, - pair_sink=pair_sink, ) def compare_field_raw(self, field_name: str, other_value: Any) -> float: diff --git a/tests/test_list_reporting_review.py b/tests/test_list_reporting_review.py new file mode 100644 index 00000000..aa4296d2 --- /dev/null +++ b/tests/test_list_reporting_review.py @@ -0,0 +1,357 @@ +"""Contracts from the October review of list reporting (#364).""" + +import inspect +import json +import weakref +from typing import Any + +import pytest + +from stickler import ComparableField, ExactComparator, StructuredModel +from stickler.comparators.base import BaseComparator +from stickler.structured_object_evaluator.models.comparison_dispatcher import ( + ComparisonDispatcher, +) +from stickler.structured_object_evaluator.models.comparison_engine import ( + ComparisonEngine, +) +from stickler.structured_object_evaluator.models.comparison_helper_base import ( + ComparisonHelperBase, +) +from stickler.structured_object_evaluator.models.field_comparison_collector import ( + FieldComparisonCollector, +) +from stickler.structured_object_evaluator.models.non_match_collector import ( + NonMatchCollector, +) +from stickler.structured_object_evaluator.models.structured_list_comparator import ( + StructuredListComparator, +) + + +class Item(StructuredModel): + code: str = ComparableField(comparator=ExactComparator()) + + +class Document(StructuredModel): + items: list[Item] + + +@pytest.mark.parametrize("structured", [False, True]) +def test_direct_dispatch_result_is_json_serializable_without_private_state(structured): + class AnyDocument(StructuredModel): + items: list[Any] = ComparableField(comparator=ExactComparator()) + + model = Document if structured else AnyDocument + items = [Item(code="a")] if structured else ["a"] + gt, pred = model(items=items), model(items=items) + result = gt._dispatch_field_comparison("items", gt.items, pred.items) + serialized = json.dumps(result, default=str) + assert "_list_matching" not in serialized + assert "pair_results" not in serialized + assert result["overall"]["tp"] == 1 + + +@pytest.mark.parametrize("accepts_kwargs", [False, True]) +@pytest.mark.parametrize("report", [False, True]) +def test_list_scoring_overrides_keep_their_existing_call_contract( + accepts_kwargs, report +): + class LegacyDocument(StructuredModel): + items: list[str] = ComparableField(comparator=ExactComparator()) + + def _compare_unordered_lists( + self, + gt_list, + pred_list, + comparator, + threshold, + clip_under_threshold=True, + field_name="", + ): + return super()._compare_unordered_lists( + gt_list, + pred_list, + comparator, + threshold, + clip_under_threshold, + field_name=field_name, + ) + + class KwargsDocument(LegacyDocument): + def _compare_unordered_lists(self, *args, **kwargs): + # Existing extensions may consume/ignore unknown options. + kwargs.pop("pair_sink", None) + return super()._compare_unordered_lists(*args, **kwargs) + + model = KwargsDocument if accepts_kwargs else LegacyDocument + result = model(items=["a"]).compare_with( + model(items=["a"]), + include_confusion_matrix=True, + document_non_matches=report, + document_field_comparisons=report, + ) + assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 1 + if report: + assert result["non_matches"] == [] + (row,) = result["field_comparisons"] + assert row["match"] is True + assert row["expected_key"] == row["actual_key"] == "items[0]" + + +@pytest.mark.parametrize( + "non_matches,comparisons,bulk", + [ + (False, False, False), + (True, False, False), + (False, True, False), + (True, True, False), + (False, True, True), + (True, True, True), + ], +) +def test_only_reported_accepted_pairs_retain_child_traversals( + monkeypatch, + tmp_path, + non_matches, + comparisons, + bulk, +): + class TrackedResult(dict): + pass + + references = [] + retained_counts = [] + dispatch = ComparisonDispatcher.dispatch_field_comparison + score = StructuredListComparator._calculate_struct_list_similarity + + def tracked_dispatch(self, *args, **kwargs): + result = dispatch(self, *args, **kwargs) + if isinstance(self.model, Item): + result = TrackedResult(result) + references.append(weakref.ref(result)) + return result + + def observed_score(self, *args, **kwargs): + result = score(self, *args, **kwargs) + if isinstance(self.parent_model, Document): + retained_counts.append(sum(ref() is not None for ref in references)) + return result + + monkeypatch.setattr( + ComparisonDispatcher, "dispatch_field_comparison", tracked_dispatch + ) + monkeypatch.setattr( + StructuredListComparator, "_calculate_struct_list_similarity", observed_score + ) + gt = Document(items=[Item(code="a"), Item(code="b")]) + pred = Document(items=[Item(code="a"), Item(code="x")]) + if bulk: + from stickler.structured_object_evaluator.bulk_structured_model_evaluator import ( + BulkStructuredModelEvaluator, + ) + + output = tmp_path / "results.jsonl" + evaluator = BulkStructuredModelEvaluator( + target_schema=Document, + document_non_matches=non_matches, + individual_results_jsonl=str(output), + ) + evaluator.update(gt, pred) + evaluator.compute() + result = json.loads(output.read_text(encoding="utf-8"))["comparison_result"] + else: + result = gt.compare_with( + pred, + document_non_matches=non_matches, + document_field_comparisons=comparisons, + ) + assert references, "The probe must observe actual child scoring." + assert retained_counts == [1 if non_matches or comparisons else 0] + assert all(ref() is None for ref in references) + assert result["overall_score"] == 0.5 + + +def test_nested_list_verdict_comes_from_element_metrics_not_aggregate_threshold(): + class Child(StructuredModel): + match_threshold = 0.4 + values: list[str] = ComparableField(comparator=ExactComparator(), threshold=0.3) + + class Parent(StructuredModel): + children: list[Child] + + result = Parent(children=[Child(values=["a", "b"])]).compare_with( + Parent(children=[Child(values=["a", "x"])]), + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + counts = result["confusion_matrix"]["fields"]["children"]["fields"]["values"][ + "overall" + ] + assert (counts["tp"], counts["fd"]) == (1, 1) + assert len(result["non_matches"]) == 1 + (row,) = result["field_comparisons"] + assert row["score"] == 0.5 + assert row["match"] is False + assert "non-matching" in row["reason"] + + +def test_extraction_contract_documents_cached_pair_data(): + signature = inspect.signature(ComparisonHelperBase._extract_entries_from_objects) + assert signature.parameters["pair_result"].default is None + + +def test_legacy_extraction_override_works_when_a_pair_result_is_available(): + class LegacyHelper(ComparisonHelperBase): + def create_entry(self, **kwargs): + return kwargs + + def _extract_entries_from_objects( + self, + field_name, + gt_object, + pred_object, + gt_index, + pred_index, + is_match, + similarity_score, + reason, + ): + return [{"match": is_match, "reason": reason}] + + rows = LegacyHelper().collect_list_entries( + "items", + [Item(code="a")], + [Item(code="a")], + matching={ + "pairs": [(0, 0, 1.0)], + "threshold": 0.7, + "verdicts": [True], + "pair_results": {(0, 0): {"field_scores": {}}}, + }, + ) + assert rows == [{"match": True, "reason": "exact match"}] + + +def test_direct_collectors_preserve_primitive_threshold_tolerance(): + class NearThreshold(BaseComparator): + def _compare(self, left, right): + return 0.7 - 1e-12 + + class Values(StructuredModel): + values: list[str] = ComparableField(comparator=NearThreshold(), threshold=0.7) + + gt, pred = Values(values=["a"]), Values(values=["b"]) + recursive = gt.compare_recursive(pred) + assert recursive["fields"]["values"]["overall"]["tp"] == 1 + assert NonMatchCollector(gt).collect_enhanced_non_matches(recursive, pred) == [] + (row,) = FieldComparisonCollector(gt).collect_field_comparisons(recursive, pred) + assert row["match"] is True + assert "within threshold tolerance" in row["reason"] + + +@pytest.mark.parametrize( + "extra_options", + [ + {}, + {"include_confusion_matrix": True}, + {"evaluator_format": True}, + {"add_confidence_metrics": True}, + {"add_bbox_metrics": True}, + ], +) +def test_reused_engine_reports_are_serializable_and_do_not_retain_prior_pairs( + extra_options, +): + gt = Document(items=[Item(code="a")]) + engine = ComparisonEngine(gt) + engine.compare_with( + Document(items=[Item(code="a")]), document_field_comparisons=True + ) + result = engine.compare_with( + Document(items=[Item(code="x")]), + document_non_matches=True, + document_field_comparisons=True, + **extra_options, + ) + fresh = gt.compare_with( + Document(items=[Item(code="x")]), + document_non_matches=True, + document_field_comparisons=True, + **extra_options, + ) + assert result == fresh + assert "_list_matching" not in json.dumps(result, default=str) + assert "pair_results" not in json.dumps(result, default=str) + + +def test_engine_recovery_after_scoring_error_does_not_reuse_partial_report_state(): + class Failable(BaseComparator): + def _compare(self, left, right): + if right == "error": + raise ValueError("comparison failed") + return float(left == right) + + class Values(StructuredModel): + first: list[str] = ComparableField(comparator=ExactComparator()) + second: str = ComparableField(comparator=Failable()) + + gt = Values(first=["a"], second="a") + engine = ComparisonEngine(gt) + with pytest.raises(ValueError, match="comparison failed"): + engine.compare_with( + Values(first=["a"], second="error"), document_non_matches=True + ) + pred = Values(first=["x"], second="a") + assert engine.compare_with(pred, document_non_matches=True) == gt.compare_with( + pred, + document_non_matches=True, + ) + + +@pytest.mark.parametrize("option", ["add_confidence_metrics", "add_bbox_metrics"]) +def test_implicit_field_reports_reuse_accepted_child_scoring(option): + class Changing(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return 1.0 if type(self).calls <= 3 else 0.0 + + class Child(StructuredModel): + value: str = ComparableField(comparator=Changing()) + + class Parent(StructuredModel): + children: list[Child] + + with pytest.warns(UserWarning, match="Single-document"): + result = Parent(children=[Child(value="a")]).compare_with( + Parent(children=[Child(value="a")]), **{option: True} + ) + assert Changing.calls == 3 + (row,) = result["field_comparisons"] + assert row["match"] is True + assert row["score"] == 1.0 + + +@pytest.mark.parametrize("none_first", [False, True]) +def test_direct_collectors_share_nullable_list_dispatch(none_first): + class Nullable(StructuredModel): + items: list[Item | None] + + items = [None, Item(code="a")] if none_first else [Item(code="a"), None] + gt, pred = Nullable(items=items), Nullable(items=list(reversed(items))) + recursive = gt.compare_recursive(pred) + result = gt.compare_with( + pred, document_non_matches=True, document_field_comparisons=True + ) + assert ( + NonMatchCollector(gt).collect_enhanced_non_matches(recursive, pred) + == result["non_matches"] + == [] + ) + rows = FieldComparisonCollector(gt).collect_field_comparisons(recursive, pred) + assert rows == result["field_comparisons"] + assert len(rows) == 2 + assert all(row["match"] for row in rows) From 44f68ce9159860d27f15ed86a472a59b56d88b07 Mon Sep 17 00:00:00 2001 From: hugosmoreira Date: Sun, 11 Oct 2026 12:16:49 -0700 Subject: [PATCH 5/5] fix: preserve legacy list reporting helper hooks Pass new report options only to explicitly named hook parameters and retain custom public non-match formatters. Cover old signatures, forwarding wrappers, nested extraction and exception propagation. --- .../models/README.md | 6 +- .../models/comparison_helper_base.py | 38 +++- .../models/field_comparison_collector.py | 4 +- .../models/non_match_collector.py | 4 +- .../models/non_matches_helper.py | 24 ++- tests/test_list_helper_compatibility.py | 195 ++++++++++++++++++ 6 files changed, 257 insertions(+), 14 deletions(-) create mode 100644 tests/test_list_helper_compatibility.py diff --git a/src/stickler/structured_object_evaluator/models/README.md b/src/stickler/structured_object_evaluator/models/README.md index f41cb7df..630ac403 100644 --- a/src/stickler/structured_object_evaluator/models/README.md +++ b/src/stickler/structured_object_evaluator/models/README.md @@ -37,7 +37,11 @@ its `from_json()` ingestion and `compare_with()` comparison pipeline. operation-local side maps, separate from public results; child traversals are retained only when a report needs them. Both collectors share the model's fallback matching settings for direct calls and custom overrides, which keep - their existing call signatures. Nested field rows use the scored metrics to + their existing call signatures. Helper hooks receive new optional metadata + only when they declare the parameter by name; a forwarding `**kwargs` wrapper + keeps its original arguments. Legacy hooks and custom non-match formatters + retain their own matching/formatting behavior rather than the built-in cache + guarantees. Nested field rows use the scored metrics to classify matches instead of applying an element threshold to a list average. - `comparison_dispatcher.py`, `field_comparator.py`, `primitive_list_comparator.py`, `structured_list_comparator.py`, diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index b193f1af..4edf9f7f 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -19,6 +19,24 @@ class ComparisonHelperBase(ABC): def __init__(self): self.hungarian_helper = HungarianHelper() + @staticmethod + def _supported_options(method, **options): + """Pass new options only to hooks that explicitly declare them. + + A **kwargs wrapper may forward to an old-signature implementation. + Preserve that call contract rather than treating the wrapper as opt-in. + """ + parameters = inspect.signature(method).parameters + return { + name: value + for name, value in options.items() + if name in parameters + and parameters[name].kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) + } + @abstractmethod def create_entry(self, *args, **kwargs) -> Dict[str, Any]: """Create an entry for the specific helper type. Must be implemented by subclasses.""" @@ -157,11 +175,9 @@ def process_matched_pairs( ) # Helpers implementing the pre-cache abstract signature remain # valid extensions; only opt-in implementations receive context. - pair_kwargs = {} - if pair_result is not None and "pair_result" in inspect.signature( - self._extract_entries_from_objects - ).parameters: - pair_kwargs["pair_result"] = pair_result + pair_kwargs = self._supported_options( + self._extract_entries_from_objects, pair_result=pair_result, + ) if pair_result is not None else {} extracted_entries = self._extract_entries_from_objects( field_name, gt_item, @@ -390,7 +406,9 @@ def collect_list_entries( ) match_threshold = None assignments, matched_pairs_with_scores = self.get_optimal_assignments( - gt_list, pred_list, comparator + gt_list, pred_list, **self._supported_options( + self.get_optimal_assignments, comparator=comparator, + ) ) if match_threshold is None: match_threshold = self.get_match_threshold(gt_list or pred_list) @@ -407,8 +425,12 @@ def collect_list_entries( entries.extend(self.process_matched_pairs( field_name, gt_list, pred_list, matched_pairs_with_scores, - match_threshold, verdicts, - matching.get("pair_results") if matching is not None else None, + match_threshold, **self._supported_options( + self.process_matched_pairs, verdicts=verdicts, + pair_results=( + matching.get("pair_results") if matching is not None else None + ), + ), )) # Process unmatched ground truth items (FN) diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index 287b390b..3b5b6eeb 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -100,7 +100,9 @@ def collect_field_comparisons( report_context.lists.get(field_name) if report_context else None, ) list_comparisons = self.helper.collect_list_entries( - field_name, gt_val, pred_val, **matching_kwargs + field_name, gt_val, pred_val, **self.helper._supported_options( + self.helper.collect_list_entries, **matching_kwargs, + ) ) all_field_comparisons.extend(list_comparisons) diff --git a/src/stickler/structured_object_evaluator/models/non_match_collector.py b/src/stickler/structured_object_evaluator/models/non_match_collector.py index 80cb6a6c..c6d61017 100644 --- a/src/stickler/structured_object_evaluator/models/non_match_collector.py +++ b/src/stickler/structured_object_evaluator/models/non_match_collector.py @@ -93,7 +93,9 @@ def collect_enhanced_non_matches( report_context.lists.get(field_name) if report_context else None, ) object_non_matches = self.helper.collect_list_non_matches( - field_name, gt_val, pred_val, **matching_kwargs + field_name, gt_val, pred_val, **self.helper._supported_options( + self.helper.collect_list_non_matches, **matching_kwargs, + ) ) all_non_matches.extend(object_non_matches) diff --git a/src/stickler/structured_object_evaluator/models/non_matches_helper.py b/src/stickler/structured_object_evaluator/models/non_matches_helper.py index bd071994..42ecde6c 100644 --- a/src/stickler/structured_object_evaluator/models/non_matches_helper.py +++ b/src/stickler/structured_object_evaluator/models/non_matches_helper.py @@ -38,7 +38,9 @@ def create_entry( """ return self.create_non_match_entry( field_name, gt_object, pred_object, non_match_type, object_index, - similarity_score, match_threshold=match_threshold, + similarity_score, **self._supported_options( + self.create_non_match_entry, match_threshold=match_threshold, + ), ) def create_non_match_entry( @@ -141,7 +143,10 @@ def collect_list_non_matches( """ # Use base class method but filter for non-matches only all_entries = self.collect_list_entries( - field_name, gt_list, pred_list, comparator, match_threshold, matching + field_name, gt_list, pred_list, **self._supported_options( + self.collect_list_entries, comparator=comparator, + match_threshold=match_threshold, matching=matching, + ) ) # Filter for non-matches only (entries where match is False or non_match_type exists) @@ -187,7 +192,10 @@ def _extract_entries_from_objects( pred_object, StructuredModel ): return self._extract_field_level_non_matches( - field_name, gt_object, pred_object, gt_index, pair_result + field_name, gt_object, pred_object, gt_index, + **self._supported_options( + self._extract_field_level_non_matches, pair_result=pair_result, + ), ) return [] @@ -203,6 +211,16 @@ def _extract_entries_from_objects( non_match_type = "FD" object_index = gt_index + # Preserve custom public formatters; the built-in formatter alone can + # consume the scorer's reason without reclassifying the pair. + if ( + getattr(self.create_non_match_entry, "__func__", None) + is not NonMatchesHelper.create_non_match_entry + ): + return [self.create_non_match_entry( + field_name, gt_object, pred_object, non_match_type, + object_index, similarity_score, + )] entry = self._create_non_match_entry( field_name, gt_object, diff --git a/tests/test_list_helper_compatibility.py b/tests/test_list_helper_compatibility.py new file mode 100644 index 00000000..72b39018 --- /dev/null +++ b/tests/test_list_helper_compatibility.py @@ -0,0 +1,195 @@ +"""Preserve pre-report-context helper extension contracts (#364).""" + +import pytest + +from stickler import ComparableField, ExactComparator, StructuredModel +from stickler.structured_object_evaluator.models.field_comparison_collector import ( + FieldComparisonCollector, +) +from stickler.structured_object_evaluator.models.field_comparison_helper import ( + FieldComparisonHelper, +) +from stickler.structured_object_evaluator.models.non_match_collector import ( + NonMatchCollector, +) +from stickler.structured_object_evaluator.models.non_matches_helper import ( + NonMatchesHelper, +) + + +class Item(StructuredModel): + code: str = ComparableField(comparator=ExactComparator()) + + +@pytest.mark.parametrize("helper_type", [FieldComparisonHelper, NonMatchesHelper]) +@pytest.mark.parametrize("hook", ["get_optimal_assignments", "process_matched_pairs"]) +@pytest.mark.parametrize("forwarding_wrapper", [False, True]) +def test_original_list_hooks_remain_callable(helper_type, hook, forwarding_wrapper): + calls = [] + + class Assignments(helper_type): + def get_optimal_assignments(self, gt_list, pred_list): + calls.append("assignments") + return super().get_optimal_assignments(gt_list, pred_list) + + class Pairs(helper_type): + def process_matched_pairs(self, field, gt, pred, pairs, threshold): + calls.append("pairs") + return super().process_matched_pairs(field, gt, pred, pairs, threshold) + + parent = Assignments if hook == "get_optimal_assignments" else Pairs + if forwarding_wrapper: + # A generic forwarding wrapper is not evidence that the wrapped old + # implementation accepts newly introduced options. + def forward(self, *args, **kwargs): + return getattr(super(type(self), self), hook)(*args, **kwargs) + + parent = type("ForwardingHelper", (parent,), {hook: forward}) + + rows = parent().collect_list_entries( + "items", [Item(code="a"), Item(code="b")], [Item(code="b"), Item(code="a")] + ) + assert len(calls) == 1 + if helper_type is NonMatchesHelper: + assert rows == [] + else: + assert [ + (row["expected_key"], row["actual_key"], row["match"]) for row in rows + ] == [ + ("items[0].code", "items[1].code", True), + ("items[1].code", "items[0].code", True), + ] + + +def test_non_match_wrapper_preserves_original_list_entry_override(): + class Legacy(NonMatchesHelper): + def collect_list_entries(self, field, gt, pred): + return [{"field_path": field, "match": False, "custom": (gt, pred)}] + + assert Legacy().collect_list_non_matches("items", ["a"], ["b"]) == [ + {"field_path": "items", "match": False, "custom": (["a"], ["b"])} + ] + + +@pytest.mark.parametrize("non_matches", [False, True]) +@pytest.mark.parametrize("with_context", [False, True], ids=["direct", "scored"]) +def test_collectors_preserve_original_helper_entry_override(non_matches, with_context): + class Values(StructuredModel): + items: list[str] = ComparableField(comparator=ExactComparator()) + + class Fields(FieldComparisonHelper): + def collect_list_entries(self, field, gt, pred): + return [{"field": field, "custom": (gt, pred)}] + + class NonMatches(NonMatchesHelper): + def collect_list_non_matches(self, field, gt, pred): + return [{"field": field, "custom": (gt, pred)}] + + gt, pred = Values(items=["a"]), Values(items=["b"]) + recursive = gt.compare_recursive(pred) + kwargs = {} + if with_context: + from stickler.structured_object_evaluator.models.reporting_context import ( + ReportingContext, + ) + + kwargs["report_context"] = ReportingContext(lists={"items": matching()}) + if non_matches: + collector = NonMatchCollector(gt) + collector.helper = NonMatches() + rows = collector.collect_enhanced_non_matches(recursive, pred, **kwargs) + else: + collector = FieldComparisonCollector(gt) + collector.helper = Fields() + rows = collector.collect_field_comparisons(recursive, pred, **kwargs) + assert rows == [{"field": "items", "custom": (["a"], ["b"])}] + + +@pytest.mark.parametrize("with_context", [False, True], ids=["direct", "scored"]) +def test_original_nested_non_match_extraction_override(with_context): + class Legacy(NonMatchesHelper): + def _extract_field_level_non_matches(self, field, gt, pred, index): + return [{"field_path": f"{field}[{index}].custom", "match": False}] + + kwargs = {"matching": matching(score=1.0)} if with_context else {} + rows = Legacy().collect_list_non_matches( + "items", [Item(code="a")], [Item(code="a")], **kwargs + ) + assert rows == [{"field_path": "items[0].custom", "match": False}] + + +@pytest.mark.parametrize("entry_point", ["create_entry", "collect_list_non_matches"]) +def test_original_non_match_formatter_override_is_used(entry_point): + class Legacy(NonMatchesHelper): + def create_non_match_entry(self, field, gt, pred, kind, index=None, score=None): + row = super().create_non_match_entry(field, gt, pred, kind, index, score) + row["custom"] = True + return row + + helper = Legacy() + if entry_point == "create_entry": + rows = [helper.create_entry("items", "a", "b", "FD", 0, 0.0)] + else: + rows = helper.collect_list_non_matches( + "items", [Item(code="a")], [Item(code="b")] + ) + assert len(rows) == 1 + assert rows[0]["custom"] is True + assert rows[0]["field_path"] == "items[0]" + + +def matching(score=0.7 - 1e-12): + from stickler.structured_object_evaluator.models.reporting_context import ( + ReportingContext, + ) + + return { + "pairs": [(0, 0, score)], + "threshold": 0.7, + "verdicts": [True], + "pair_results": {(0, 0): ReportingContext()}, + } + + +def test_explicit_optional_hook_parameters_receive_scoring_options(): + observed = {} + comparator = ExactComparator() + + class OptIn(FieldComparisonHelper): + def get_optimal_assignments(self, gt, pred, *, comparator=None): + observed["comparator"] = comparator + return super().get_optimal_assignments(gt, pred, comparator) + + def process_matched_pairs( + self, field, gt, pred, pairs, threshold, *, verdicts=None, pair_results=None + ): + observed["verdicts"] = verdicts + observed["pair_results"] = pair_results + return super().process_matched_pairs( + field, gt, pred, pairs, threshold, verdicts, pair_results + ) + + helper = OptIn() + helper.collect_list_entries("items", ["a"], ["a"], comparator=comparator) + assert observed["comparator"] is comparator + cached = matching() + (row,) = helper.collect_list_entries("items", ["a"], ["b"], matching=cached) + assert row["match"] is True + assert "within threshold tolerance" in row["reason"] + assert observed["verdicts"] is cached["verdicts"] + assert observed["pair_results"] is cached["pair_results"] + assert cached["pairs"] == [(0, 0, 0.7 - 1e-12)] + + +@pytest.mark.parametrize("hook", ["get_optimal_assignments", "process_matched_pairs"]) +def test_hook_type_errors_propagate_without_retry(hook): + calls = [] + + def fail(self, *args, **kwargs): + calls.append((args, kwargs)) + raise TypeError("extension failed inside its body") + + helper_type = type("FailingHelper", (FieldComparisonHelper,), {hook: fail}) + with pytest.raises(TypeError, match="extension failed inside its body"): + helper_type().collect_list_entries("items", ["a"], ["b"]) + assert len(calls) == 1