Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: preserve legacy list reporting helper hooks
Pass new report options only to explicitly named hook parameters and
retain custom public non-match formatters. Cover old signatures,
forwarding wrappers, nested extraction and exception propagation.
  • Loading branch information
hugosmoreira committed Oct 11, 2026
commit 44f68ce9159860d27f15ed86a472a59b56d88b07
6 changes: 5 additions & 1 deletion src/stickler/structured_object_evaluator/models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ its `from_json()` ingestion and `compare_with()` comparison pipeline.
operation-local side maps, separate from public results; child traversals are
retained only when a report needs them. Both collectors share the model's
fallback matching settings for direct calls and custom overrides, which keep
their existing call signatures. Nested field rows use the scored metrics to
their existing call signatures. Helper hooks receive new optional metadata
only when they declare the parameter by name; a forwarding `**kwargs` wrapper
keeps its original arguments. Legacy hooks and custom non-match formatters
retain their own matching/formatting behavior rather than the built-in cache
guarantees. Nested field rows use the scored metrics to
classify matches instead of applying an element threshold to a list average.
- `comparison_dispatcher.py`, `field_comparator.py`,
`primitive_list_comparator.py`, `structured_list_comparator.py`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@ class ComparisonHelperBase(ABC):
def __init__(self):
self.hungarian_helper = HungarianHelper()

@staticmethod
def _supported_options(method, **options):
"""Pass new options only to hooks that explicitly declare them.

A **kwargs wrapper may forward to an old-signature implementation.
Preserve that call contract rather than treating the wrapper as opt-in.
"""
parameters = inspect.signature(method).parameters
return {
name: value
for name, value in options.items()
if name in parameters
and parameters[name].kind in (
inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.KEYWORD_ONLY,
)
}

@abstractmethod
def create_entry(self, *args, **kwargs) -> Dict[str, Any]:
"""Create an entry for the specific helper type. Must be implemented by subclasses."""
Expand Down Expand Up @@ -157,11 +175,9 @@ def process_matched_pairs(
)
# Helpers implementing the pre-cache abstract signature remain
# valid extensions; only opt-in implementations receive context.
pair_kwargs = {}
if pair_result is not None and "pair_result" in inspect.signature(
self._extract_entries_from_objects
).parameters:
pair_kwargs["pair_result"] = pair_result
pair_kwargs = self._supported_options(
self._extract_entries_from_objects, pair_result=pair_result,
) if pair_result is not None else {}
extracted_entries = self._extract_entries_from_objects(
field_name,
gt_item,
Expand Down Expand Up @@ -390,7 +406,9 @@ def collect_list_entries(
)
match_threshold = None
assignments, matched_pairs_with_scores = self.get_optimal_assignments(
gt_list, pred_list, comparator
gt_list, pred_list, **self._supported_options(
self.get_optimal_assignments, comparator=comparator,
)
)
if match_threshold is None:
match_threshold = self.get_match_threshold(gt_list or pred_list)
Expand All @@ -407,8 +425,12 @@ def collect_list_entries(

entries.extend(self.process_matched_pairs(
field_name, gt_list, pred_list, matched_pairs_with_scores,
match_threshold, verdicts,
matching.get("pair_results") if matching is not None else None,
match_threshold, **self._supported_options(
self.process_matched_pairs, verdicts=verdicts,
pair_results=(
matching.get("pair_results") if matching is not None else None
),
),
))

# Process unmatched ground truth items (FN)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ def collect_field_comparisons(
report_context.lists.get(field_name) if report_context else None,
)
list_comparisons = self.helper.collect_list_entries(
field_name, gt_val, pred_val, **matching_kwargs
field_name, gt_val, pred_val, **self.helper._supported_options(
self.helper.collect_list_entries, **matching_kwargs,
)
)
all_field_comparisons.extend(list_comparisons)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ def collect_enhanced_non_matches(
report_context.lists.get(field_name) if report_context else None,
)
object_non_matches = self.helper.collect_list_non_matches(
field_name, gt_val, pred_val, **matching_kwargs
field_name, gt_val, pred_val, **self.helper._supported_options(
self.helper.collect_list_non_matches, **matching_kwargs,
)
)
all_non_matches.extend(object_non_matches)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ def create_entry(
"""
return self.create_non_match_entry(
field_name, gt_object, pred_object, non_match_type, object_index,
similarity_score, match_threshold=match_threshold,
similarity_score, **self._supported_options(
self.create_non_match_entry, match_threshold=match_threshold,
),
)

def create_non_match_entry(
Expand Down Expand Up @@ -141,7 +143,10 @@ def collect_list_non_matches(
"""
# Use base class method but filter for non-matches only
all_entries = self.collect_list_entries(
field_name, gt_list, pred_list, comparator, match_threshold, matching
field_name, gt_list, pred_list, **self._supported_options(
self.collect_list_entries, comparator=comparator,
match_threshold=match_threshold, matching=matching,
)
)

# Filter for non-matches only (entries where match is False or non_match_type exists)
Expand Down Expand Up @@ -187,7 +192,10 @@ def _extract_entries_from_objects(
pred_object, StructuredModel
):
return self._extract_field_level_non_matches(
field_name, gt_object, pred_object, gt_index, pair_result
field_name, gt_object, pred_object, gt_index,
**self._supported_options(
self._extract_field_level_non_matches, pair_result=pair_result,
),
)
return []

Expand All @@ -203,6 +211,16 @@ def _extract_entries_from_objects(
non_match_type = "FD"
object_index = gt_index

# Preserve custom public formatters; the built-in formatter alone can
# consume the scorer's reason without reclassifying the pair.
if (
getattr(self.create_non_match_entry, "__func__", None)
is not NonMatchesHelper.create_non_match_entry
):
return [self.create_non_match_entry(
field_name, gt_object, pred_object, non_match_type,
object_index, similarity_score,
)]
entry = self._create_non_match_entry(
field_name,
gt_object,
Expand Down
195 changes: 195 additions & 0 deletions tests/test_list_helper_compatibility.py
Original file line number Diff line number Diff line change
@@ -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