Skip to content
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ Each release links to full notes on the
the threshold (`0.7996 < 0.8`, not `0.800 < 0.8`). Every row with the same
verdict gets its reason from `ThresholdHelper.match_reason`
([#462](https://github.com/awslabs/stickler/issues/462)).
- **A list of values scores the same in any order when pairings tie.** Upgrade
note: counts and scores can move for a primitive, dict or plain-model list
whose pairings tie. The solver picked among equally good pairings by
position, so reordering a `List[str]` could move it from 2 TP and 1 FD
(`0.5`) to 1 TP and 2 FD (`0.25`). A tie now goes to the pairing with more
pairs meeting the field's threshold, then to the one where those pairs score
more. `List[StructuredModel]` is unchanged
([#658](https://github.com/awslabs/stickler/issues/658)).

## [1.1.0] - 2026-12-04

Expand Down
4 changes: 2 additions & 2 deletions docs/docs/Advanced/classification-logic.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ This table is the single statement of how Stickler treats a list field. Other pa

| Aspect | Rule |
|---|---|
| Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). A list the field's comparator reads as one value is not paired: under `BBoxIoUComparator`, a box `[x1, y1, x2, y2]` or `[[x1, y1], [x2, y2]]` in a field whose elements are scalars (`List[float]`, `Sequence[float]`) is scored whole, with one count and one report row, so it is one FN or FA against a null list (`None`, `[]`, all `None` or NaN) and one FD against a malformed value. A field whose elements are sequences (`List[List[float]]`, or a union or alias with a sequence arm) stays paired; a bare `list` or `List[Any]` is decided by the ground-truth value. A pair that a `required_match` field vetoes is never paired, and the assignment pairs as many allowed pairs as it can before it maximises similarity. |
| Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. When pairings tie on total similarity, a primitive, dict or plain-model list takes the one with more pairs meeting the bar, then the one where those pairs score more. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). A list the field's comparator reads as one value is not paired: under `BBoxIoUComparator`, a box `[x1, y1, x2, y2]` or `[[x1, y1], [x2, y2]]` in a field whose elements are scalars (`List[float]`, `Sequence[float]`) is scored whole, with one count and one report row, so it is one FN or FA against a null list (`None`, `[]`, all `None` or NaN) and one FD against a malformed value. A field whose elements are sequences (`List[List[float]]`, or a union or alias with a sequence arm) stays paired; a bare `list` or `List[Any]` is decided by the ground-truth value. A pair that a `required_match` field vetoes is never paired, and the assignment pairs as many allowed pairs as it can before it maximises similarity. |
| Bar | `List[StructuredModel]`: the element class's `match_threshold`; a runtime `match_threshold` does not change it. A field `threshold` there raises `ValueError` in Python, and JSON Schema ignores it. Primitive, dict and plain-model lists on a `StructuredModel` declared in Python: the field's `threshold`, else a threshold named on the comparator, else `0.5` when declared with `ComparableField()`, or the class `match_threshold` (`0.7` unless set) when declared without it (`tags: List[str]`). JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../Getting-Started/thresholds-and-metrics.md#4-runtime-match-threshold)). A pair that [meets](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold) the bar is a TP. |
| Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. A vetoed pair is never paired, so an element left with no allowed partner is unpaired: an FN or an FA, never an FD. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). |
| Recursion | Only TP pairs of `StructuredModel` items are descended into. FD, FN and FA items are atomic. `aggregate` holds the leaves of TP items only, so FD, FN and FA items are left out of it when any sibling was accepted. With no accepted item it falls back to the list node's own counts ([why](aggregate-metrics.md#aggregate-counts-objects-for-an-all-rejected-list)). |
| Score | `sum(pair scores) / max(n_gt, n_pred)`, never clipped as a whole against a field threshold. For primitive, dict and plain-model lists the pair score is the element similarity, zeroed below the bar when `clip_under_threshold` is on. On a `StructuredModel` declared in Python it defaults to on for primitive lists and off for dict and plain-model lists. JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../API-Reference/auto.md#inference)). For `List[StructuredModel]` the pair score is `GT[i].compare_with(Pred[j])["overall_score"]`, which applies each field's own threshold and can differ from the pairing similarity. With `clip_under_threshold` on, an FD pair contributes `0.0`; it defaults to off there, as on dict and plain-model lists, so an FD pair keeps its score unless the field sets it. That holds however the list of models is spelled, including `List[Union[A, B]]`, `List[Any]` and `Sequence[A]`. [Worked example](hungarian-matching.md#step-4-list-score). |
| Reports | `field_comparisons`: one row per element of a primitive, dict or plain-model list, whatever its classification (a dict or plain-model element is not expanded into its keys or fields); for `List[StructuredModel]`, one row per leaf of a TP item and one object row per FD, FN or FA item. `non_matches` has the same rows, but only the FD, FN and FA ones. A `field_comparisons` row's `match` is true when its own classification is TP or TN: a value or object row met its bar; a list row had every element paired as a TP, with no FD, FA or FN at the element level. Failures deeper down get their own rows. |

**Known gaps.** Four behaviours are defects, not the contract: `explain()` reporting an unset `clip_under_threshold` as `True` on a list of models it does not recognise from the annotation (`List[Union[A, B]]`, `Sequence[A]`, `List[Any]` holding models, a `List[Optional[A]]` or `List[Annotated[A, ...]]` declared without `ComparableField`, or a zero-config `List[BaseModel]`), while the list scores with it off; inside a list item, a `field_comparisons` row reporting the clipped `score`, and a nested list or object getting one row; a `None` list being reported differently from `[]` in `field_comparisons` (one row for the whole field against a non-empty list, and one row against another `None`, where every other pair of null lists, such as `[]` vs `[]`, gets none); and inside a list item, the cases listed under **Nested lists** below counting differently than at top level.
**Known gaps.** Five behaviours are defects, not the contract: `explain()` reporting an unset `clip_under_threshold` as `True` on a list of models it does not recognise from the annotation (`List[Union[A, B]]`, `Sequence[A]`, `List[Any]` holding models, a `List[Optional[A]]` or `List[Annotated[A, ...]]` declared without `ComparableField`, or a zero-config `List[BaseModel]`), while the list scores with it off; inside a list item, a `field_comparisons` row reporting the clipped `score`, and a nested list or object getting one row; a `None` list being reported differently from `[]` in `field_comparisons` (one row for the whole field against a non-empty list, and one row against another `None`, where every other pair of null lists, such as `[]` vs `[]`, gets none); inside a list item, the cases listed under **Nested lists** below counting differently than at top level; and `List[StructuredModel]` still breaking a tie on total similarity by element position.

#### `None` elements in a list {: #none-elements-in-a-list }

Expand Down
28 changes: 27 additions & 1 deletion src/stickler/algorithms/hungarian.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
# Memory threshold for warning in MB
HUNGARIAN_SIZE_WARNING_THRESHOLD = 10000 # Matrix size (product of dimensions)

# Total weight of the tie-break, small enough not to outrank a real difference
# between two assignments' similarity totals.
_TIE_BREAK_WEIGHT = 1e-9

# Global Munkres instance for optimization
_MUNKRES = Munkres()

Expand Down Expand Up @@ -77,6 +81,7 @@ def __init__(
self.size_threshold = size_threshold
self.normalize_values = normalize_values
self.match_threshold = match_threshold
self._tie_break_threshold: Optional[float] = None
self.is_pair_excluded = is_pair_excluded

def _normalize_value(self, value: Any) -> Any:
Expand Down Expand Up @@ -193,6 +198,25 @@ def _score(self, item1: Any, item2: Any) -> float:
raise
return compare(self._comparable_form(item1), self._comparable_form(item2))

def _ranking_matrix(self, similarity_matrix: np.ndarray) -> np.ndarray:
"""Similarities as the solver should rank them, ties broken."""
if self._tie_break_threshold is None:
return similarity_matrix

# Imported here for the same reason as in calculate_metrics.
from stickler.structured_object_evaluator.models.threshold_helper import (
ThresholdHelper,
)

pairs = min(similarity_matrix.shape)
above = np.vectorize(ThresholdHelper.is_above_threshold)(
similarity_matrix, self._tie_break_threshold
)
# One more pair above the threshold outweighs any sum of similarities,
# which the division by ``pairs + 1`` keeps below one.
bonus = above * (1 + similarity_matrix / (pairs + 1))
return similarity_matrix + bonus * (_TIE_BREAK_WEIGHT / pairs)

def match(self, list1: Any, list2: Any) -> Tuple[List[Tuple[int, int]], np.ndarray]:
"""Find optimal assignments between two lists.

Expand Down Expand Up @@ -238,7 +262,9 @@ def match(self, list1: Any, list2: Any) -> Tuple[List[Tuple[int, int]], np.ndarr

# Convert to cost matrix for the Hungarian algorithm
# Cost is 1 - similarity (because Hungarian minimizes cost)
cost_matrix = make_cost_matrix(similarity_matrix, lambda x: 1 - x)
cost_matrix = make_cost_matrix(
self._ranking_matrix(similarity_matrix), lambda x: 1 - x
)

# an excluded pair costs more than every allowed assignment can sum
# to, so the solver picks one only when no allowed pairing is left,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ def _match_non_structured_lists(
model_cls=None,
field_name: str = "",
warn_selected: bool = False,
threshold: Optional[float] = None,
) -> List[tuple]:
"""Use the same raw-value matcher and class gate for scoring and direct reports."""
from stickler.algorithms.hungarian import HungarianMatcher
Expand All @@ -192,8 +193,11 @@ def _match_non_structured_lists(
comparator, model_cls=model_cls, field_name=field_name
)
matcher = HungarianMatcher(
element_comparator, match_threshold=0.0, normalize_values=False
element_comparator,
match_threshold=0.0,
normalize_values=False,
)
matcher._tie_break_threshold = threshold
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)
Expand Down Expand Up @@ -539,6 +543,7 @@ def compare_unordered_lists(
matched_pairs = _match_non_structured_lists(
gt_list, pred_list, comparator,
model_cls=model_cls, field_name=field_name, warn_selected=True,
threshold=threshold,
)

result = ComparisonHelper.unordered_list_metrics(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@ def get_match_threshold(self, obj_list: List[Any]) -> float:
def get_optimal_assignments(
self, gt_list: List[Any], pred_list: List[Any],
comparator: Optional[BaseComparator] = None,
match_threshold: Optional[float] = 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.
match_threshold: Field threshold, used to break assignment ties.

Returns:
Tuple of (assignments, matched_pairs_with_scores)
Expand All @@ -80,7 +82,7 @@ def get_optimal_assignments(
# 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
gt_list, pred_list, comparator, threshold=match_threshold
)
assignments = [(i, j) for i, j, _ in matched_pairs_with_scores]

Expand Down Expand Up @@ -384,15 +386,20 @@ def collect_list_entries(
"threshold; field comparator/threshold overrides are not supported"
)
match_threshold = None
# Resolve the fallback before matching. A direct collector that
# passes only a comparator otherwise hands the matcher None, so a
# tie is still broken by position and the pairs are classified
# against the default afterwards.
if match_threshold is None:
match_threshold = self.get_match_threshold(
NullHelper.present(gt_list) or NullHelper.present(pred_list)
)
assignments, matched_pairs_with_scores = self.get_optimal_assignments(
gt_list, pred_list, **self._supported_options(
self.get_optimal_assignments, comparator=comparator,
match_threshold=match_threshold,
)
)
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.
Expand Down
110 changes: 110 additions & 0 deletions tests/structured_object_evaluator/test_list_assignment_ties.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""Tied optimal assignments must not make list scores depend on element order."""

from itertools import permutations
from typing import List

import pytest

from stickler import ComparableField, StructuredModel
from stickler.algorithms.hungarian import HungarianMatcher
from stickler.comparators.base import BaseComparator
from stickler.comparators.levenshtein import LevenshteinComparator
from stickler.structured_object_evaluator.models.non_matches_helper import (
NonMatchesHelper,
)


class _Model(StructuredModel):
values: List[str] = ComparableField(threshold=0.7)


@pytest.mark.parametrize("clip", [True, False])
def test_tied_assignments_score_independently_of_element_order(clip):
class Model(StructuredModel):
values: List[str] = ComparableField(threshold=0.7, clip_under_threshold=clip)

gt = ["bcc", "caaa", "cbac"]
results = []
for gt_order in permutations(gt):
for pred_order in permutations(["baaa", "bbaa", "bbac"]):
result = Model(values=list(gt_order)).compare_with(
Model(values=list(pred_order)), include_confusion_matrix=True
)
overall = result["confusion_matrix"]["fields"]["values"]["overall"]
results.append((result["overall_score"], overall["tp"], overall["fd"]))

assert {(tp, fd) for _, tp, fd in results} == {(2, 1)}
assert [score for score, _, _ in results] == pytest.approx(
[results[0][0]] * len(results)
)


def test_tie_break_reports_the_pairs_that_were_counted():
result = _Model(values=["bcc", "caaa", "cbac"]).compare_with(
_Model(values=["baaa", "bbac", "bbaa"]), document_non_matches=True
)

assert len(result["non_matches"]) == 1


def test_direct_collector_breaks_ties_without_an_explicit_threshold():
"""A collector that receives only a comparator still pairs by the default bar."""
gt = ["bcc", "caaa", "cbac"]
helper = NonMatchesHelper()
comparator = LevenshteinComparator()
for pred in permutations(["baaa", "bbaa", "bbac"]):
implied = helper.collect_list_non_matches(
"values", gt, list(pred), comparator=comparator
)
explicit = helper.collect_list_non_matches(
"values", gt, list(pred), comparator=comparator, match_threshold=0.7
)
assert len(implied) == 1
assert len(implied) == len(explicit)


class _SecondKeyTableComparator(BaseComparator):
_SCORES = {
("g0", "p0"): 0.875,
("g1", "p1"): 0.75,
("g2", "p2"): 0.125,
("g0", "p1"): 0.75,
("g1", "p2"): 0.75,
("g2", "p0"): 0.25,
}

def _compare(self, str1, str2) -> float:
return self._SCORES.get((str1, str2), 0.0)


def test_tie_break_second_key_prefers_higher_above_threshold_sum():
"""When tied pairings have the same count at the bar, prefer the higher sum."""

class Model(StructuredModel):
values: List[str] = ComparableField(
comparator=_SecondKeyTableComparator(),
threshold=0.7,
clip_under_threshold=True,
)

expected = (0.875 + 0.75) / 3
for gt_order in permutations(["g0", "g1", "g2"]):
for pred_order in permutations(["p0", "p1", "p2"]):
result = Model(values=list(gt_order)).compare_with(
Model(values=list(pred_order)), include_confusion_matrix=True
)
overall = result["confusion_matrix"]["fields"]["values"]["overall"]
assert (overall["tp"], overall["fd"]) == (2, 1)
assert result["overall_score"] == pytest.approx(expected)


def test_hungarian_matcher_keeps_1_1_0_positional_signature():
"""is_pair_excluded remains the fifth positional parameter."""

def excluded(a, b):
return a == "a" and b == "a"

matcher = HungarianMatcher(None, 10000, True, 0.7, excluded)
assert matcher.is_pair_excluded is excluded
pairs, _ = matcher.match(["a", "b"], ["a", "b"])
assert (0, 0) not in pairs