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
fix: preserve list report indices and node reasons on current dev
  • Loading branch information
hugosmoreira committed Oct 19, 2026
commit cc2bd106c7faf8986f0c33eebe70e64c5cd1f9a1
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ Each release links to full notes on the
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add one sentence here: nested list and nested object rows in field_comparisons now report match=False when scoring recorded any non-match beneath them, even if their score meets the threshold. Users who filter on match will see those rows change.

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ def _match_non_structured_lists(
"""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(
Expand All @@ -179,7 +183,7 @@ def _match_non_structured_lists(
pairs = matcher.calculate_metrics(gt_list, pred_list)["matched_pairs"]
if warn_selected and isinstance(element_comparator, _ClassGatedComparator):
element_comparator.warn_for_selected(gt_list, pred_list, pairs)
return pairs
return [(gt_indices[i], pred_indices[j], score) for i, j, score in pairs]


def _maybe_absent(val: Any) -> bool:
Expand Down Expand Up @@ -335,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)

Expand Down Expand Up @@ -412,14 +419,20 @@ def compare_unordered_lists(
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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

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
Expand Down Expand Up @@ -372,7 +373,7 @@ def resolve_list_matching(model, field_name, gt_list, matching=None):

if matching is not None:
return {"matching": matching}
if gt_list and isinstance(gt_list[0], StructuredModel):
if isinstance(NullHelper.first_present(gt_list), StructuredModel):
return {}
info = model._get_comparison_info(field_name)
return {"comparator": info.comparator, "match_threshold": info.threshold}
Expand Down Expand Up @@ -411,7 +412,7 @@ def collect_list_entries(
verdicts = matching["verdicts"]
else:
# Direct helper callers still compute their own assignments.
if gt_list and isinstance(gt_list[0], StructuredModel):
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 "
Expand All @@ -424,7 +425,9 @@ def collect_list_entries(
)
)
if match_threshold is None:
match_threshold = self.get_match_threshold(gt_list or pred_list)
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,23 @@ def _extract_entries_from_objects(
if (
field_result is not None
and "fields" in field_result
and not field_is_match
and field_score >= info.threshold
and field_is_match != (field_score >= info.threshold)
):
field_reason = (
f"score {field_score:.3f} >= {info.threshold}, but nested "
"comparison has non-matching or unmatched values"
)
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"
)

# 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .comparison_helper import ComparisonHelper
from .hungarian_helper import HungarianHelper
from .metrics_helper import MetricsHelper
from .null_helper import NullHelper
from .reporting_context import ReportingContext

if TYPE_CHECKING:
Expand Down Expand Up @@ -54,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)

Expand Down Expand Up @@ -91,10 +94,19 @@ def compare_struct_list_with_scores(
"verdicts": verdicts,
"pair_results": {},
}
self.report_context.lists[field_name] = matching
raw_similarity = self._calculate_struct_list_similarity(
matched_pairs, gt_list, pred_list, info, 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
Expand Down Expand Up @@ -207,30 +219,22 @@ def _calculate_struct_list_similarity(
gt_item = gt_list[gt_idx]
pred_item = pred_list[pred_idx]

if gt_item is None or pred_item is None:
# Nullable object elements (List[Optional[Model]]) can pair a
# None against a model; compare_with would crash on None, so
# score it directly: both-None is a match, one-None is not.
threshold_applied_score = (
1.0 if gt_item is None and pred_item is None else 0.0
# Use individual comparison with threshold application (same as .compare_with())
if (
matching is not None
and matching["verdicts"][pair_index]
and type(gt_item).compare_with is StructuredModel.compare_with
):
child_context = ReportingContext()
individual_result = ComparisonEngine(gt_item).compare_with(
pred_item, _report_context=child_context
)
matching["pair_results"][(gt_idx, pred_idx)] = child_context
else:
# Use individual comparison with threshold application (same as .compare_with())
if (
matching is not None
and matching["verdicts"][pair_index]
and type(gt_item).compare_with is StructuredModel.compare_with
):
child_context = ReportingContext()
individual_result = ComparisonEngine(gt_item).compare_with(
pred_item, _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"]
# 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(
(gt_idx, pred_idx, threshold_applied_score)
Expand Down
3 changes: 2 additions & 1 deletion tests/test_list_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,8 @@ class Parent(StructuredModel):
assert result["non_matches"] == []
(row,) = result["field_comparisons"]
assert row["match"] is True
assert "within threshold tolerance" in row["reason"]
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():
Expand Down
Loading
Loading
You are viewing a condensed version of this merge commit. You can view the full changes here.