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(391): score tuple and set values by one rule in both readers
- send a tuple or set pair under an inferred comparator through
  scalar_pair_comparator in compare(), as compare_with() does
- with an inferred comparator, two tuples or two sets go to
  ExactComparator, so an Any or Sequence[int] field scores them as a
  Tuple or Set field does, at the top level, on a nested model and in
  a list-of-models item
- a dict view is not a set here, so it keeps its rule from before
- with an inferred comparator, compare() now scores a tuple against a
  list or a set as 0.0, as compare_with() does
- a declared comparator is called on the same pairs as before in both
  readers, a tuple against a list in compare() included
  • Loading branch information
digalaviz committed Dec 1, 2026
commit 4ce86ff1998c8fd1dbf83e603a2821fb8b3c355b
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,14 @@ Each release links to full notes on the
positive, against `None` a false negative. `to_stickler_config()` and
`to_json_schema()` name `ExactComparator`. A comparator named with
`comparator=` is never replaced; declare one, such as
`PointDistanceComparator`, for partial credit
`PointDistanceComparator`, for partial credit. A field typed `Any` or
`Sequence[int]` with no comparator named compares two tuples, or two sets, the
same way, at the top level, on a nested model and in a list-of-models item:
two identical tuples there scored `0.0` in `compare_with()` and `1.0` in
`compare()`. A tuple or set inside a `List[Any]` still uses the list's
comparator. With an inferred comparator, `compare()` now scores a tuple
against a list or a set as `0.0`, as `compare_with()` does. A declared
comparator gives the same scores as before in both readers
([#391](https://github.com/awslabs/stickler/issues/391)).

### Performance
Expand Down
3 changes: 2 additions & 1 deletion docs/docs/Getting-Started/Contributing/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ The dispatcher routes each field comparison through a 5-step decision tree:
# (value, value), neither a list, dict or model → FieldComparator when
# the field declared its comparator; an inferred one also needs numbers
# incl. Decimal, or related date/time/timedelta/UUID/Enum values (#383).
# The rule is comparison_helper.scalar_pair_reaches_comparator, shared
# Two tuples or two sets under an inferred one → ExactComparator (#391).
# The rule is comparison_helper.scalar_pair_comparator, shared
# with compare_field_raw so compare() and compare_with() agree.
# (list, list) where list[0] is StructuredModel → StructuredListComparator
# (list, list) otherwise → PrimitiveListComparator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from .comparison_helper import (
list_pair_is_one_value,
scalar_pair_reaches_comparator,
scalar_pair_comparator,
)
from .configuration_helper import ConfigurationHelper
from .null_helper import NullHelper
Expand Down Expand Up @@ -208,17 +208,22 @@ def dispatch_field_comparison(
# of the ground truth and prediction values. This is the core dispatch logic.

# CASE 1: A pair of non-structured values, for the field's comparator.
# `scalar_pair_reaches_comparator` is the rule, shared with
# `scalar_pair_comparator` is the rule, shared with
# compare_field_raw so compare() and compare_with() agree: a declared
# comparator is always called, and an inferred one sees str/int/float,
# numbers incl. Decimal, and related date/time/UUID/Enum values. Before
# #383 only str/int/float got here; everything else fell through to
# CASE 6 and scored 0.0 without the comparator being called.
if scalar_pair_reaches_comparator(
gt_val, pred_val, comparator_explicit=info.comparator_explicit
):
# numbers incl. Decimal, and related date/time/UUID/Enum values, or
# gives way to ExactComparator for two tuples or two sets (#391).
# Before #383 only str/int/float got here; everything else fell
# through to CASE 6 and scored 0.0 without the comparator being called.
pair_comparator = scalar_pair_comparator(
info.comparator,
gt_val,
pred_val,
comparator_explicit=info.comparator_explicit,
)
if pair_comparator is not None:
return self.field_comparator.compare_primitive_with_scores(
gt_val, pred_val, field_name
gt_val, pred_val, field_name, comparator=pair_comparator
)

# CASE 2: Both are lists (non-empty, null/empty cases already handled in STEP 3)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pydantic import BaseModel

from stickler.comparators.base import BaseComparator
from stickler.comparators.exact import ExactComparator

from .hungarian_helper import HungarianHelper
from .null_helper import NullHelper
Expand Down Expand Up @@ -237,8 +238,8 @@ def _maybe_absent(val: Any) -> bool:
_NUMBERS = (int, float, decimal.Decimal)
# Values with their own branch in both readers; never decided here.
_STRUCTURED = (list, dict, BaseModel)
# Not decided here yet: tuples and sets keep their pre-#383 behaviour in each
# reader until collection comparison has its own contract (#391).
# Scores a tuple or set pair under an inferred comparator (#391).
_ONE_VALUE = ExactComparator()
_COLLECTIONS = (tuple, set, frozenset)

# PEP 695 `type X = ...` aliases exist from Python 3.12.
Expand Down Expand Up @@ -327,12 +328,12 @@ def _element_is_scalar(element: Any) -> Optional[bool]:
)


def scalar_pair_reaches_comparator(
gt_val: Any, pred_val: Any, *, comparator_explicit: bool
) -> bool:
"""Whether a field's comparator scores this pair, rather than it mismatching.
def scalar_pair_comparator(
comparator: BaseComparator, gt_val: Any, pred_val: Any, *, comparator_explicit: bool
) -> Optional[BaseComparator]:
"""The comparator that scores a pair of non-structured values, or None.

The one rule for a pair of non-structured values, read by both
None means the pair mismatches. The one rule for such a pair, read by both
``ComparisonDispatcher`` (``compare_with``) and
:meth:`ComparisonHelper.compare_field_raw` (``compare`` and the Hungarian
cost matrix). Spelling it in each let the two disagree, the contradiction
Expand All @@ -358,29 +359,51 @@ def scalar_pair_reaches_comparator(
different such classes, or a member against a bare value, are a
mismatch.

Two tuples, or two sets, are one value each and go to ``ExactComparator``
instead (#391), as a tuple or set annotation already infers. The value
decides here, so an ``Any`` or ``Sequence[int]`` field holding them scores
the same as a ``Tuple`` or ``Set`` field.

Before #383 the dispatcher accepted only the first bullet, and a declared
comparator for anything else was never called.
"""
if isinstance(gt_val, _STRUCTURED) or isinstance(pred_val, _STRUCTURED):
return False
return None
if comparator_explicit:
return True
return comparator
if _same_kind_of_collection(gt_val, pred_val):
return _ONE_VALUE
if isinstance(gt_val, enum.Enum) or isinstance(pred_val, enum.Enum):
return (
related = (
isinstance(gt_val, enum.Enum)
and isinstance(pred_val, enum.Enum)
and _related(gt_val, pred_val)
)
return comparator if related else None
if isinstance(gt_val, (str, int, float)) and isinstance(
pred_val, (str, int, float)
):
return True
return comparator
if isinstance(gt_val, _NUMBERS) and isinstance(pred_val, _NUMBERS):
return True
return (
return comparator
if (
isinstance(gt_val, _SCALAR_TYPES)
and isinstance(pred_val, _SCALAR_TYPES)
and _related(gt_val, pred_val)
):
return comparator
return None


def _same_kind_of_collection(a: Any, b: Any) -> bool:
"""Both tuples, or both sets; a tuple against a set or list is neither.

A set means ``set`` or ``frozenset``: a dict view is an abstract set too,
but its members need not be hashable, so it keeps its rule from before.
"""
sets = (set, frozenset)
return (isinstance(a, tuple) and isinstance(b, tuple)) or (
isinstance(a, sets) and isinstance(b, sets)
)


Expand Down Expand Up @@ -785,18 +808,25 @@ def compare_field_raw(
if isinstance(self_value, BaseModel) and isinstance(other_value, BaseModel):
return comparator.compare(self_value, other_value)

# Tuples and sets keep their pre-#383 behaviour here (#391).
if isinstance(self_value, _COLLECTIONS) or isinstance(
other_value, _COLLECTIONS
# A declared comparator scores any pair holding a tuple or set here, as
# before #391, even a tuple against a list that compare_with() calls a
# mismatch.
if info.comparator_explicit and (
isinstance(self_value, _COLLECTIONS)
or isinstance(other_value, _COLLECTIONS)
):
return comparator.compare(self_value, other_value)

# Every other pair goes through the dispatcher's own rule, so a pair
# `compare_with` calls a mismatch scores 0.0 here too (#233, #383).
if not scalar_pair_reaches_comparator(
self_value, other_value, comparator_explicit=info.comparator_explicit
):
pair_comparator = scalar_pair_comparator(
comparator,
self_value,
other_value,
comparator_explicit=info.comparator_explicit,
)
if pair_comparator is None:
return 0.0

# Use the comparator to calculate raw similarity (no threshold)
return comparator.compare(self_value, other_value)
return pair_comparator.compare(self_value, other_value)
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from .threshold_helper import ThresholdHelper

if TYPE_CHECKING:
from stickler.comparators.base import BaseComparator

from .structured_model import StructuredModel


Expand Down Expand Up @@ -49,7 +51,8 @@ def compare_primitive_with_scores(
self,
gt_val: Any,
pred_val: Any,
field_name: str
field_name: str,
comparator: Optional["BaseComparator"] = None,
) -> Dict[str, Any]:
"""Compare primitive fields and return metrics + scores.

Expand All @@ -61,6 +64,8 @@ def compare_primitive_with_scores(
gt_val: Ground truth value (primitive type)
pred_val: Predicted value (primitive type)
field_name: Name of the field being compared
comparator: Scores this pair in place of the configured one, when
the dispatcher's pair rule picked another (#391)

Returns:
Dictionary with structure:
Expand All @@ -76,7 +81,7 @@ def compare_primitive_with_scores(
}
"""
info = self.model.__class__._get_comparison_info(field_name)
raw_similarity = info.comparator.compare(gt_val, pred_val)
raw_similarity = (comparator or info.comparator).compare(gt_val, pred_val)
weight = info.weight
threshold = info.threshold

Expand Down
Loading