diff --git a/CHANGELOG.md b/CHANGELOG.md index d99d2be1..424050f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,18 @@ Each release links to full notes on the ### Fixed +- 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. 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. + Field-comparison rows treat float `NaN` as missing, consistently with scoring, + both for top-level fields and fields in accepted structured-list pairs. + A nested list row inside a list element reports `match=False` when an element + was a false discovery, false alarm or false negative, so `field_comparisons` + agrees with `non_matches`. + - **A `RootModel` is now refused when the evaluator is built, instead of failing once per document or scoring a wrong value `1.0`.** `eval_for()` accepted one and returned a spec. What happened next depended on the root type: 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/algorithms/README.md b/src/stickler/algorithms/README.md index dd4aeceb..03c44fbf 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 @@ -77,19 +77,20 @@ 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/README.md b/src/stickler/structured_object_evaluator/models/README.md index 06e9e045..f049d313 100644 --- a/src/stickler/structured_object_evaluator/models/README.md +++ b/src/stickler/structured_object_evaluator/models/README.md @@ -31,7 +31,18 @@ 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 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. 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`, `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 aae3028c..24a2bb9e 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_dispatcher.py +++ b/src/stickler/structured_object_evaluator/models/comparison_dispatcher.py @@ -11,6 +11,7 @@ from .comparison_helper import scalar_pair_reaches_comparator 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 @@ -27,13 +28,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 @@ -46,7 +52,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 @@ -55,7 +61,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 @@ -64,7 +72,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 820b73db..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,7 +83,9 @@ 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]: + def compare_recursive( + self, other: "StructuredModel", *, _report_context: Optional[ReportingContext] = None + ) -> Dict[str, Any]: """The core recursive comparison function. This method performs a single-traversal comparison of two StructuredModel @@ -142,6 +146,14 @@ def compare_recursive(self, other: "StructuredModel") -> Dict[str, Any]: "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 @@ -154,7 +166,7 @@ def compare_recursive(self, other: "StructuredModel") -> Dict[str, Any]: 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 @@ -192,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, + _report_context: Optional[ReportingContext] = None, ) -> Dict[str, Any]: """Compare with another instance using single traversal. @@ -249,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) + 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 = {} @@ -286,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. @@ -312,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 @@ -366,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 @@ -441,6 +466,12 @@ def compare_with( if pred_bboxes: result["prediction_bboxes"] = pred_bboxes + 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: 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 6c971929..48a3af77 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper.py @@ -156,6 +156,36 @@ 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 + + gt_indices = NullHelper.present_indices(gt_list) + pred_indices = NullHelper.present_indices(pred_list) + gt_list = [gt_list[i] for i in gt_indices] + pred_list = [pred_list[i] for i in pred_indices] + 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 [(gt_indices[i], pred_indices[j], score) for i, j, score in pairs] + + def _maybe_absent(val: Any) -> bool: """Whether ``val`` could be absent under *either* of ``NullHelper``'s rules. @@ -272,6 +302,7 @@ def compare_unordered_lists( clip_under_threshold: bool = True, model_cls=None, field_name: str = "", + matching_sink: Dict[str, Any] | None = None, ) -> Dict[str, Any]: """Compare two lists as unordered collections using Hungarian matching. @@ -288,6 +319,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. + 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: @@ -306,7 +339,10 @@ def compare_unordered_lists( # A None element is absent: it is not matched, counted or scored, and a # list of only None is empty (#386). Every count and score below is - # over what remains; this path reports no indices, so none are remapped. + # over what remains. Saved reporting pairs must use original indices. + if matching_sink is not None: + gt_indices = NullHelper.present_indices(gt_list) + pred_indices = NullHelper.present_indices(pred_list) gt_list = NullHelper.present(gt_list) pred_list = NullHelper.present(pred_list) @@ -353,8 +389,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. # @@ -378,37 +412,27 @@ 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, + ) - return ComparisonHelper.unordered_list_metrics( + result = 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, ) + if matching_sink is not None: + matching_sink["pairs"] = [ + (gt_indices[i], pred_indices[j], score) + for i, j, score in matched_pairs + ] + return result @staticmethod def unordered_list_metrics( @@ -417,6 +441,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. @@ -435,9 +460,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 @@ -485,9 +518,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 b70626b4..6821f24b 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -1,11 +1,16 @@ """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 ComparisonHelper, _match_non_structured_lists from .hungarian_helper import HungarianHelper from .null_helper import NullHelper +from .reporting_context import ReportingContext DEFAULT_MATCH_THRESHOLD = 0.7 @@ -15,6 +20,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.""" @@ -35,12 +58,16 @@ def get_match_threshold(self, obj_list: List[Any]) -> float: return element.__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) @@ -49,10 +76,17 @@ 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 - ) - matched_pairs_with_scores = hungarian_info["matched_pairs"] + if comparator is None: + hungarian_info = self.hungarian_helper.get_complete_matching_info( + gt_list, pred_list + ) + matched_pairs_with_scores = hungarian_info["matched_pairs"] + else: + # 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 + ) assignments = [(i, j) for i, j, _ in matched_pairs_with_scores] return assignments, matched_pairs_with_scores @@ -69,7 +103,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})" @@ -95,7 +131,9 @@ 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, + pair_results: Optional[Dict[tuple, ReportingContext]] = None, ) -> List[Dict[str, Any]]: """Process matched pairs and create entries. @@ -105,24 +143,40 @@ 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 + pair_results: Optional already-scored child results for structured lists 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) # Extract entries from structured model objects + 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 = 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, @@ -132,6 +186,7 @@ def process_matched_pairs( is_match, similarity_score, reason, + **pair_kwargs, ) entries.extend(extracted_entries) @@ -286,7 +341,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. @@ -299,14 +355,34 @@ 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 isinstance(NullHelper.first_present(gt_list), 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] + 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. @@ -314,6 +390,10 @@ 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. + matching: Pairings and decisions already produced by scoring. When + supplied, its list assignments and verdicts are reused. Returns: List of entries with individual information @@ -323,16 +403,50 @@ def collect_list_entries( if not NullHelper.present(gt_list) and not NullHelper.present(pred_list): return entries - # Get optimal assignments with scores. They index the original lists; - # None elements are left out of them (#386). - assignments, matched_pairs_with_scores = self.get_optimal_assignments(gt_list, pred_list) + from .structured_model import StructuredModel - match_threshold = self.get_match_threshold( - NullHelper.present(gt_list) or NullHelper.present(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 isinstance(NullHelper.first_present(gt_list), 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, **self._supported_options( + self.get_optimal_assignments, comparator=comparator, + ) + ) + if match_threshold is None: + match_threshold = self.get_match_threshold( + NullHelper.present(gt_list) or NullHelper.present(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, match_threshold + field_name, gt_list, pred_list, matched_pairs_with_scores, + 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_comparator.py b/src/stickler/structured_object_evaluator/models/field_comparator.py index 25502f52..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, @@ -163,7 +168,21 @@ 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"] + from .comparison_engine import ComparisonEngine + 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, _report_context=child_context + ) + 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 e2acfeff..22f82e4f 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -5,10 +5,11 @@ 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 .null_helper import NullHelper +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -34,7 +35,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. @@ -99,8 +101,14 @@ def collect_field_comparisons( and isinstance(pred_val, list) ): # Use FieldComparisonHelper for primitive list collection + 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 + field_name, gt_val, pred_val, **self.helper._supported_options( + self.helper.collect_list_entries, **matching_kwargs, + ) ) all_field_comparisons.extend(list_comparisons) @@ -115,7 +123,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: @@ -148,13 +157,15 @@ def collect_field_comparisons( else: reason = f"below threshold ({raw_score:.3f} < {info.threshold})" - # Handle missing fields - if pred_val is None and gt_val is not None: + # Use scoring's float-NaN-as-missing rule without changing the displayed values. + gt_missing = gt_val is None or NullHelper.is_nan(gt_val) + pred_missing = pred_val is None or NullHelper.is_nan(pred_val) + if pred_missing and not gt_missing: reason = "false negative (unmatched ground truth)" is_match = False raw_score = 0.0 weighted_score = 0.0 - elif gt_val is None and pred_val is not None: + elif gt_missing and not pred_missing: reason = "false alarm (unmatched prediction)" is_match = False raw_score = 0.0 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..adb935b8 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,8 @@ from typing import Any, Dict, List, Optional from .comparison_helper_base import ComparisonHelperBase +from .null_helper import NullHelper +from .reporting_context import ReportingContext class FieldComparisonHelper(ComparisonHelperBase): @@ -91,7 +93,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 field-level comparisons from structured model objects. @@ -117,23 +120,39 @@ 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. + 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 + 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}" @@ -141,13 +160,35 @@ 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 field_is_match != (field_score >= info.threshold) + ): + if field_is_match: + score_text = f"{field_score:.3f}" + # Do not round a below-threshold score up to the bar. + if float(score_text) >= info.threshold: + score_text = repr(field_score) + field_reason = ( + f"all elements matched (score {score_text} < {info.threshold})" + ) + else: + non_matches = sum(metrics.get(key, 0) for key in ("fd", "fa", "fn")) + noun = "item" if non_matches == 1 else "items" + field_reason = ( + f"score {field_score:.3f} >= {info.threshold}, but " + f"{non_matches} {noun} did not match" + ) - # Handle missing fields - if pred_nested_val is None and gt_nested_val is not None: + # Keep the scored NaN-as-missing decision when formatting child fields. + gt_missing = gt_nested_val is None or NullHelper.is_nan(gt_nested_val) + pred_missing = pred_nested_val is None or NullHelper.is_nan(pred_nested_val) + if pred_missing and not gt_missing: field_reason = "false negative (unmatched ground truth)" field_is_match = False field_score = 0.0 - elif gt_nested_val is None and pred_nested_val is not None: + elif gt_missing and not pred_missing: field_reason = "false alarm (unmatched prediction)" field_is_match = False field_score = 0.0 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 81a7606f..c6d61017 100644 --- a/src/stickler/structured_object_evaluator/models/non_match_collector.py +++ b/src/stickler/structured_object_evaluator/models/non_match_collector.py @@ -4,11 +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 .null_helper import NullHelper +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -36,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. @@ -86,27 +87,15 @@ 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 isinstance( - NullHelper.first_present(gt_val, pred_val), StructuredModel + 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, ) - ): - # Use NonMatchesHelper for object-level collection object_non_matches = self.helper.collect_list_non_matches( - field_name, gt_val, pred_val - ) - all_non_matches.extend(object_non_matches) - - elif ( - isinstance(gt_val, list) - and isinstance(pred_val, list) - ): - # 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, **self.helper._supported_options( + self.helper.collect_list_non_matches, **matching_kwargs, + ) ) all_non_matches.extend(object_non_matches) @@ -129,7 +118,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 8ec1ccd1..42ecde6c 100644 --- a/src/stickler/structured_object_evaluator/models/non_matches_helper.py +++ b/src/stickler/structured_object_evaluator/models/non_matches_helper.py @@ -2,8 +2,11 @@ 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 +from .reporting_context import ReportingContext class NonMatchesHelper(ComparisonHelperBase): @@ -17,6 +20,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. @@ -27,12 +31,16 @@ 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, **self._supported_options( + self.create_non_match_entry, match_threshold=match_threshold, + ), ) def create_non_match_entry( @@ -43,6 +51,7 @@ def create_non_match_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. @@ -53,10 +62,28 @@ 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 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 @@ -80,11 +107,7 @@ 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})" - ) + entry["reason"] = reason or "below threshold" entry["similarity"] = similarity_score entry["similarity_score"] = similarity_score else: @@ -101,7 +124,10 @@ 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, + matching: Optional[Dict[str, Any]] = None, ) -> List[Dict[str, Any]]: """Collect individual object-level non-matches from a list field. @@ -109,12 +135,19 @@ 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, **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) non_matches = [] @@ -134,7 +167,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 non-match entries from structured model objects. @@ -158,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 + field_name, gt_object, pred_object, gt_index, + **self._supported_options( + self._extract_field_level_non_matches, pair_result=pair_result, + ), ) return [] @@ -174,16 +211,26 @@ 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, - ) - ] + # 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, + pred_object, + non_match_type, + object_index, + similarity_score, + reason=reason if non_match_type == "FD" else None, + ) + return [entry] def _extract_field_level_non_matches( self, @@ -191,6 +238,7 @@ def _extract_field_level_non_matches( gt_object: Any, pred_object: Any, object_index: int, + pair_result: Optional[ReportingContext] = None, ) -> List[Dict[str, Any]]: """Extract field-level non-matches from a threshold-passing object pair. @@ -203,15 +251,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, pair_result + ) 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/primitive_list_comparator.py b/src/stickler/structured_object_evaluator/models/primitive_list_comparator.py index 37808adb..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,22 +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 .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 @@ -103,14 +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. - match_result = self.parent_model._compare_unordered_lists( - gt_list, - pred_list, - comparator, - threshold, - info.clip_under_threshold, - field_name=field_name, - ) + 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) 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 b50dd0d8..2dd58998 100644 --- a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py @@ -14,6 +14,7 @@ from .hungarian_helper import HungarianHelper from .metrics_helper import MetricsHelper from .null_helper import NullHelper +from .reporting_context import ReportingContext if TYPE_CHECKING: from .structured_model import StructuredModel @@ -22,13 +23,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, @@ -51,8 +55,10 @@ def compare_struct_list_with_scores( weight = info.weight # A None element is absent: it is not matched, counted or scored (#386). - # Every count and score below is over what remains; this path reports - # no indices, so none are remapped. + # Counts and scores use compact lists; reports read the original lists. + if self.report_context is not None: + gt_indices = NullHelper.present_indices(gt_list) + pred_indices = NullHelper.present_indices(pred_list) gt_list = NullHelper.present(gt_list) pred_list = NullHelper.present(pred_list) @@ -76,12 +82,31 @@ 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 + matching = None + if self.report_context is not None: + matching = { + "pairs": matched_pairs, + "threshold": match_threshold, + "verdicts": verdicts, + "pair_results": {}, + } raw_similarity = self._calculate_struct_list_similarity( - matched_pairs, gt_list, pred_list, info + matched_pairs, gt_list, pred_list, info, matching ) + if matching is not None: + matching["pairs"] = [ + (gt_indices[i], pred_indices[j], score) + for i, j, score in matched_pairs + ] + matching["pair_results"] = { + (gt_indices[i], pred_indices[j]): child + for (i, j), child in matching["pair_results"].items() + } + self.report_context.lists[field_name] = matching # CRITICAL FIX: For structured lists, we NEVER clip under threshold - partial matches are important threshold_applied_score = raw_similarity # Always use raw score for lists @@ -93,7 +118,7 @@ def compare_struct_list_with_scores( gt_list, pred_list, matched_pairs, - match_threshold, + verdicts, ) # Build final result structure @@ -122,7 +147,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 +157,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 +187,7 @@ def _calculate_object_level_metrics( matched_pairs, matched_gt_indices, matched_pred_indices, + verdicts, ) def _calculate_struct_list_similarity( @@ -169,6 +196,7 @@ def _calculate_struct_list_similarity( gt_list: List["StructuredModel"], pred_list: List["StructuredModel"], info: "ComparableField", + matching: Dict[str, Any] | None = None, ) -> float: """Calculate raw similarity score for structured list. @@ -176,19 +204,36 @@ def _calculate_struct_list_similarity( gt_list: Ground truth list pred_list: Predicted list info: Field comparison info + matching: Side map receiving accepted child traversals when reporting 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: + 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] # Use individual comparison with threshold application (same as .compare_with()) - individual_result = gt_item.compare_with(pred_item) + 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, _report_context=child_context + ) + 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. + individual_result = gt_item.compare_with(pred_item) threshold_applied_score = individual_result["overall_score"] threshold_corrected_pairs.append( @@ -213,7 +258,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. @@ -226,7 +271,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 @@ -243,8 +288,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/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_nan_as_absent.py b/tests/structured_object_evaluator/test_nan_as_absent.py index 1ee3b558..6c417ad5 100644 --- a/tests/structured_object_evaluator/test_nan_as_absent.py +++ b/tests/structured_object_evaluator/test_nan_as_absent.py @@ -95,3 +95,49 @@ def test_null_predicates_agree_on_nan(): assert not NullHelper.is_nan("nan") assert NullHelper.is_effectively_null_for_primitives(NAN) assert FieldHelper.is_null_value(NAN) + + +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize( + "gt, pred, score, count, reason", + [ + (NAN, NAN, 1.0, "tn", "exact match"), + (NAN, None, 1.0, "tn", "exact match"), + (None, NAN, 1.0, "tn", "exact match"), + (NAN, 5.0, 0.0, "fa", "false alarm (unmatched prediction)"), + (5.0, NAN, 0.0, "fn", "false negative (unmatched ground truth)"), + (0.0, 0.0, 1.0, "tp", "exact match"), + (0.0, 5.0, 0.0, "fd", "below threshold (0.000 < 0.5)"), + ], +) +def test_field_reports_agree_with_missing_value_counts( + nested, gt, pred, score, count, reason +): + class ReportItem(Item): + # The matching sku must keep the pair accepted when value is missing. + match_threshold = 0.4 + + class ReportOrder(StructuredModel): + items: List[ReportItem] = ComparableField() + + if nested: + expected = ReportOrder(items=[ReportItem(value=gt)]) + actual = ReportOrder(items=[ReportItem(value=pred)]) + path = "items[0].value" + else: + expected, actual = Reading(value=gt), Reading(value=pred) + path = "value" + + result = expected.compare_with( + actual, include_confusion_matrix=True, document_field_comparisons=True + ) + fields = result["confusion_matrix"]["fields"] + if nested: + assert fields["items"]["overall"]["tp"] == 1 + fields = fields["items"]["fields"] + assert fields["value"]["overall"][count] == 1 + row = next(r for r in result["field_comparisons"] if r["expected_key"] == path) + assert row["actual_key"] == path + assert row["match"] is (count in ("tp", "tn")) + assert row["score"] == score + assert row["reason"] == reason 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_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 diff --git a/tests/test_list_reporting.py b/tests/test_list_reporting.py new file mode 100644 index 00000000..bd101c64 --- /dev/null +++ b/tests/test_list_reporting.py @@ -0,0 +1,637 @@ +"""Regression coverage for reporting the list comparisons scored by #332.""" + +import json +from typing import Any, Optional + +import pytest +from pydantic import BaseModel + +from stickler import ( + ANLSStarComparator, + ComparableField, + ExactComparator, + StructuredModel, +) +from stickler.comparators.base import BaseComparator +from stickler.structured_object_evaluator.models.non_matches_helper import ( + NonMatchesHelper, +) + + +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) + ] + + +@pytest.mark.parametrize("bulk", [False, True]) +def test_reports_reuse_the_scoring_cost_matrix(bulk, tmp_path): + 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"] + 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"] == [] + 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 + + +@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 row["score"] == 0.7 - 1e-12 + assert row["reason"] == f"all elements matched (score {row['score']!r} < 0.7)" + + +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"]) + 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 + ) diff --git a/tests/test_list_reporting_review.py b/tests/test_list_reporting_review.py new file mode 100644 index 00000000..1d4454cf --- /dev/null +++ b/tests/test_list_reporting_review.py @@ -0,0 +1,657 @@ +"""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 row["reason"] == "score 0.500 >= 0.3, but 1 item did not match" + + +@pytest.mark.parametrize("direct_collector", [False, True]) +@pytest.mark.parametrize( + "prediction,score,non_match_type,reason", + [ + ( + ["red", "green"], + 2 / 3, + "false_negative", + "score 0.667 >= 0.5, but 1 item did not match", + ), + ( + ["red", "green", "blue", "yellow"], + 0.75, + "false_alarm", + "score 0.750 >= 0.5, but 1 item did not match", + ), + ( + ["red", "green", "yellow"], + 2 / 3, + "false_discovery", + "score 0.667 >= 0.5, but 1 item did not match", + ), + ( + ["red", "green", "blue", "yellow", "orange", "purple"], + 0.5, + "false_alarm", + "score 0.500 >= 0.5, but 3 items did not match", + ), + (["red"], 1 / 3, "false_negative", "below threshold (0.333 < 0.5)"), + ([], 0.0, "false_negative", "below threshold (0.000 < 0.5)"), + (["red", "green", "blue"], 1.0, None, "exact match"), + ], +) +def test_nested_list_reason_keeps_score_and_threshold( + direct_collector, prediction, score, non_match_type, reason +): + class Child(StructuredModel): + # Even the below-threshold controls must enter accepted-child reporting. + match_threshold = 0.0 + tags: list[str] = ComparableField(comparator=ExactComparator(), threshold=0.5) + + class Parent(StructuredModel): + items: list[Child] + + gt = Parent(items=[Child(tags=["red", "green", "blue"])]) + pred = Parent(items=[Child(tags=prediction)]) + result = gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 1 + rows = ( + FieldComparisonCollector(gt).collect_field_comparisons( + gt.compare_recursive(pred), pred + ) + if direct_collector + else result["field_comparisons"] + ) + (row,) = rows + assert row["expected_key"] == row["actual_key"] == "items[0].tags" + assert row["score"] == pytest.approx(score) + assert row["match"] is (non_match_type is None) + if non_match_type: + assert {entry["non_match_type"] for entry in result["non_matches"]} == { + non_match_type + } + if prediction == ["red", "green"]: + assert result["non_matches"][0]["field_path"] == "items[0].tags[2]" + else: + assert result["non_matches"] == [] + assert row["reason"] == reason + + +@pytest.mark.parametrize("direct_collector", [False, True]) +@pytest.mark.parametrize( + "prediction,score,match,reason", + [ + (("x", "y", "z"), 0.0, False, "below threshold (0.000 < 0.5)"), + (("a", "b", "z"), 2 / 3, True, "above threshold (0.667 >= 0.5)"), + (("a", "b", "c"), 1.0, True, "exact match"), + ], +) +def test_nested_object_reason_preserves_its_scored_verdict( + direct_collector, prediction, score, match, reason +): + class Address(StructuredModel): + city: str = ComparableField(comparator=ExactComparator()) + country: str = ComparableField(comparator=ExactComparator()) + postcode: str = ComparableField(comparator=ExactComparator()) + + class Child(StructuredModel): + match_threshold = 0.0 + addr: Address = ComparableField(threshold=0.5) + + class Parent(StructuredModel): + items: list[Child] + + gt = Parent(items=[Child(addr=Address(city="a", country="b", postcode="c"))]) + pred = Parent( + items=[ + Child( + addr=Address( + city=prediction[0], country=prediction[1], postcode=prediction[2] + ) + ) + ] + ) + result = gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + assert result["confusion_matrix"]["fields"]["items"]["overall"]["tp"] == 1 + rows = ( + FieldComparisonCollector(gt).collect_field_comparisons( + gt.compare_recursive(pred), pred + ) + if direct_collector + else result["field_comparisons"] + ) + (row,) = rows + assert row["expected_key"] == row["actual_key"] == "items[0].addr" + assert row["score"] == pytest.approx(score) + assert row["match"] is match + if prediction == ("a", "b", "z"): + # A partial object can match at object level while its leaf is reported. + assert result["non_matches"][0]["field_path"] == "items[0].addr.postcode" + assert result["non_matches"][0]["non_match_type"] == "false_discovery" + elif match: + assert result["non_matches"] == [] + assert row["reason"] == 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) + + +@pytest.mark.parametrize("kind", ["string", "zero", "plain-model"]) +@pytest.mark.parametrize("direct_collector", [False, True]) +def test_sparse_primitive_and_plain_model_lists_keep_original_indices( + kind, direct_collector +): + from pydantic import BaseModel + + class Plain(BaseModel): + code: str + + class Values(StructuredModel): + values: list[Any] = ComparableField(comparator=ExactComparator()) + + a, b = { + "string": ("", "b"), + "zero": (0, 2), + "plain-model": (Plain(code="a"), Plain(code="b")), + }[kind] + gt = Values(values=[None, a, float("nan"), b]) + pred = Values(values=[b, None, a, float("nan")]) + result = gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + assert result["confusion_matrix"]["fields"]["values"]["overall"]["tp"] == 2 + recursive = gt.compare_recursive(pred) + non_matches = ( + NonMatchCollector(gt).collect_enhanced_non_matches(recursive, pred) + if direct_collector + else result["non_matches"] + ) + rows = ( + FieldComparisonCollector(gt).collect_field_comparisons(recursive, pred) + if direct_collector + else result["field_comparisons"] + ) + assert non_matches == [] + assert [(row["expected_key"], row["actual_key"], row["match"]) for row in rows] == [ + ("values[1]", "values[2]", True), + ("values[3]", "values[0]", True), + ] + + +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"] + # Since #399, absent elements do not contribute a row. + assert len(rows) == 1 + assert all(row["match"] for row in rows) + + +@pytest.mark.parametrize("direct_collector", [False, True]) +def test_accepted_inner_list_reason_describes_element_matches(direct_collector): + class Leaf(StructuredModel): + match_threshold = 0.3 + first: str = ComparableField(comparator=ExactComparator()) + second: str = ComparableField(comparator=ExactComparator()) + third: str = ComparableField(comparator=ExactComparator()) + + class Group(StructuredModel): + match_threshold = 0.3 + leaves: list[Leaf] = ComparableField() + + class Root(StructuredModel): + groups: list[Group] + + gt = Root(groups=[Group(leaves=[Leaf(first="a", second="b", third="c")])]) + pred = Root(groups=[Group(leaves=[Leaf(first="a", second="x", third="y")])]) + result = gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + counts = result["confusion_matrix"]["fields"]["groups"]["fields"]["leaves"][ + "overall" + ] + assert (counts["tp"], counts["fd"], counts["fa"], counts["fn"]) == (1, 0, 0, 0) + rows = ( + FieldComparisonCollector(gt).collect_field_comparisons( + gt.compare_recursive(pred), pred + ) + if direct_collector + else result["field_comparisons"] + ) + (row,) = rows + assert row["expected_key"] == row["actual_key"] == "groups[0].leaves" + assert row["match"] is True + assert row["score"] == pytest.approx(1 / 3) + assert {entry["field_path"] for entry in result["non_matches"]} == { + "groups[0].leaves[0].second", + "groups[0].leaves[0].third", + } + assert row["reason"] == "all elements matched (score 0.333 < 0.5)" + + +@pytest.mark.parametrize("absent", [None, float("nan")], ids=["none", "nan"]) +@pytest.mark.parametrize("nested", [False, True]) +def test_sparse_reordered_lists_reuse_the_correct_child_results(absent, nested): + class CountingExact(BaseComparator): + calls = 0 + + def _compare(self, left, right): + type(self).calls += 1 + return float(left == right) + + class Row(StructuredModel): + match_threshold = 0.4 + code: str = ComparableField(comparator=CountingExact()) + detail: str = ComparableField(comparator=CountingExact()) + + class Rows(StructuredModel): + match_threshold = 0.4 + rows: list[Any] + + class Root(StructuredModel): + groups: list[Any] + + gt = Rows( + rows=[absent, Row(code="a", detail="aa"), absent, Row(code="b", detail="bb")] + ) + pred = Rows( + rows=[Row(code="b", detail="bb"), absent, absent, Row(code="a", detail="xx")] + ) + prefix = "" + if nested: + gt, pred = Root(groups=[absent, gt]), Root(groups=[pred, absent]) + prefix = "groups[1]." + baseline = gt.compare_with(pred, include_confusion_matrix=True) + calls = CountingExact.calls + CountingExact.calls = 0 + result = gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + assert result["overall_score"] == baseline["overall_score"] + assert result["confusion_matrix"] == baseline["confusion_matrix"] + assert [entry["field_path"] for entry in result["non_matches"]] == [ + prefix + "rows[1].detail" + ] + if nested: + (row,) = result["field_comparisons"] + assert (row["expected_key"], row["actual_key"], row["match"]) == ( + "groups[1].rows", + "groups[0].rows", + True, + ) + else: + assert [ + ( + row["expected_key"], + row["actual_key"], + row["expected_value"], + row["actual_value"], + row["match"], + ) + for row in result["field_comparisons"] + ] == [ + ("rows[1].code", "rows[3].code", "a", "a", True), + ("rows[1].detail", "rows[3].detail", "aa", "xx", False), + ("rows[3].code", "rows[0].code", "b", "b", True), + ("rows[3].detail", "rows[0].detail", "bb", "bb", True), + ] + assert CountingExact.calls == calls + assert "pair_results" not in json.dumps(result, default=str)