Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,37 @@ Each release links to full notes on the

### Changed

- **Breaking:** a `StructuredModel` field typed `date`, `datetime`, `time`,
`timedelta`, `Decimal`, `UUID` or `Enum` now reaches its comparator, and a
declared comparator is always called. The dispatcher treated only `str`,
`int` and `float` as scalars, so these fell through to the mismatched-types
case: an identical value scored `0.0` and counted as a false discovery, and
the declared comparator (including `DateComparator`) was never called. The
zero-config path (`stickler.evaluate()` on a plain pydantic model) was
unaffected, because its shadow models convert these values first.

`compare_with()` and `compare()` now share one rule, so the two no longer
disagree on such a pair. Results move for existing callers:
- **A declared comparator is called for any non-structured pair**, including
`bytes`, a custom class, a tuple or set, or a `date` against its ISO string
under `DateComparator`. In `compare_with()` these scored `0.0` without the
comparator being called.
- **An inferred comparator sees only `str`/`int`/`float`, numbers (`Decimal`
included), and related `date`/`time`/`timedelta`/`UUID`/`Enum` values.**
Anything else is a mismatch in both readers. `compare()`, which feeds list
matching, used to call the comparator for such a pair, so a `date` against
its ISO string, `bytes`, or an arbitrary object now score `0.0` there.
- **Enum members match only members of a related `Enum` class.** With an
inferred comparator, two different `IntEnum` or `StrEnum` classes, or a
member against a bare value, are now a mismatch where they used to compare
as `int`/`str`.
- **A `Decimal` is compared with an `int` or `float` as a number.**

`Tuple` and `Set` fields with an inferred comparator are unchanged
([#391](https://github.com/awslabs/stickler/issues/391)), and #392 tracks
merging the two readers into one implementation
([#383](https://github.com/awslabs/stickler/issues/383))

- **Breaking:** `match_threshold` on a **primitive** field now raises
`ValueError`. It is the object-level threshold; nothing read it on a leaf, so
`"match_threshold": 0.99` beside a `float` left that field at `threshold` 0.5
Expand Down
8 changes: 7 additions & 1 deletion docs/docs/Getting-Started/Contributing/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,18 @@ The dispatcher routes each field comparison through a 5-step decision tree:
| 5. **Type-based dispatch** | Route by runtime types to specialized comparator | Terminal |

```python
# See: comparison_dispatcher.py:65-225
# See: comparison_dispatcher.py, dispatch_field_comparison
# Step 5 type routing:
# (str|int|float, str|int|float) → FieldComparator
# (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
# with compare_field_raw so compare() and compare_with() agree.
# (list, list) where list[0] is StructuredModel → StructuredListComparator
# (list, list) otherwise → PrimitiveListComparator
# (StructuredModel, StructuredModel) → FieldComparator
# (dict, dict) and (plain BaseModel, plain BaseModel) → FieldComparator
# Mismatched types → FD result (score=0.0)
```

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Getting-Started/thresholds-and-metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ When multiple thresholds could apply, here's which one wins:

| Situation | Which threshold applies |
|-----------|------------------------|
| **Primitive field comparison** (str, int, float) | Field threshold (`ComparableField(threshold=...)`), else a threshold named on the comparator |
| **Primitive field comparison** (str, int, float, and date, datetime, time, timedelta, Decimal, UUID, Enum) | Field threshold (`ComparableField(threshold=...)`), else a threshold named on the comparator |
| **Nested object comparison** | Recurses into fields; each field uses its own field threshold |
| **List element pairing** (`List[StructuredModel]`) | Runtime match threshold if provided, else Model match threshold |
| **Score clipping** | Field threshold (when `clip_under_threshold=True`) |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from pydantic import BaseModel

from .comparison_helper import scalar_pair_reaches_comparator
from .configuration_helper import ConfigurationHelper
from .null_helper import NullHelper
from .result_helper import ResultHelper
Expand Down Expand Up @@ -190,10 +191,15 @@ def dispatch_field_comparison(
# 3. Make the list vs singleton distinction the primary branch
# See pseudocode in refactoring discussions for proposed structure.

# CASE 1: Primitive types (str, int, float)
# Delegate to FieldComparator for primitive field comparison
if isinstance(gt_val, (str, int, float)) and isinstance(
pred_val, (str, int, float)
# CASE 1: A pair of non-structured values, for the field's comparator.
# `scalar_pair_reaches_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
):
return self.field_comparator.compare_primitive_with_scores(
gt_val, pred_val, field_name
Expand Down
100 changes: 100 additions & 0 deletions src/stickler/structured_object_evaluator/models/comparison_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@
within StructuredModel instances.
"""

import datetime
import decimal
import enum
import uuid
from typing import Any, Dict, List

from pydantic import BaseModel

from stickler.comparators.base import BaseComparator

from .hungarian_helper import HungarianHelper
Expand Down Expand Up @@ -172,6 +178,84 @@ def _maybe_absent(val: Any) -> bool:
)


# Scalar types beyond str/int/float that a model field commonly declares.
# `datetime.date` covers `datetime.datetime`, its subclass.
_SCALAR_TYPES = (
datetime.date,
datetime.time,
datetime.timedelta,
decimal.Decimal,
uuid.UUID,
)
_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).
_COLLECTIONS = (tuple, set, frozenset)


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.

The one rule for a pair of non-structured values, 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
#233 rules out.

A comparator the field **declared** is always called: the caller chose it
for this field's values, and it decides what it can score, as it already
does for a dict or a plain model. That covers ``bytes``, a custom class,
or a ``date`` against its ISO string under ``DateComparator``.

A comparator that was **inferred** sees only values it can be trusted
with, since it was never chosen for them. An arbitrary object would reach
``LevenshteinComparator`` as its repr, and two distinct
``<Foo object at 0x...>`` reprs are near-identical strings. So the pair
must be:

- ``str``/``int``/``float``, as before;
- two numbers, ``Decimal`` included;
- ``date``/``time``/``timedelta``/``UUID`` values of related type (``date``
and ``datetime`` are);
- members of related ``Enum`` classes. Checked first, because an
``IntEnum``/``StrEnum`` member is also an ``int``/``str``, and two
different such classes, or a member against a bare value, are a
mismatch.

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
if comparator_explicit:
return True
if isinstance(gt_val, enum.Enum) or isinstance(pred_val, enum.Enum):
return (
isinstance(gt_val, enum.Enum)
and isinstance(pred_val, enum.Enum)
and _related(gt_val, pred_val)
)
if isinstance(gt_val, (str, int, float)) and isinstance(
pred_val, (str, int, float)
):
return True
if isinstance(gt_val, _NUMBERS) and isinstance(pred_val, _NUMBERS):
return True
return (
isinstance(gt_val, _SCALAR_TYPES)
and isinstance(pred_val, _SCALAR_TYPES)
and _related(gt_val, pred_val)
)


def _related(a: Any, b: Any) -> bool:
return isinstance(a, type(b)) or isinstance(b, type(a))


class ComparisonHelper:
"""Helper class for StructuredModel field comparison operations."""

Expand Down Expand Up @@ -544,5 +628,21 @@ def compare_field_raw(
):
return 0.0

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
):
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
):
return 0.0

# Use the comparator to calculate raw similarity (no threshold)
return comparator.compare(self_value, other_value)
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ def __init__(
threshold: float = 0.5,
weight: float = 1.0,
clip_under_threshold: bool = True,
comparator_explicit: bool = False,
):
"""Initialize comparison configuration.

Expand All @@ -101,8 +102,12 @@ def __init__(
threshold: Minimum similarity score to consider a match (default: 0.5)
weight: Weight of this field in the overall score (default: 1.0)
clip_under_threshold: Whether to zero out scores below threshold (default: True)
comparator_explicit: Whether the field declared ``comparator``, rather
than it being inferred. A declared comparator is called for any
pair of non-structured values (#383).
"""
self.comparator = comparator or LevenshteinComparator()
self.comparator_explicit = comparator_explicit
self.threshold = threshold
self.weight = weight
self.clip_under_threshold = clip_under_threshold
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -777,6 +777,10 @@ def get_comparison_info(cls, field_name: str) -> "ComparableFieldConfig":
threshold=threshold,
weight=weight,
clip_under_threshold=clip_under_threshold,
# Read exactly as the substitution above reads it.
comparator_explicit=getattr(
json_func, "_comparator_explicit", True
),
)

# FALLBACK: Legacy JSON schema approach for backward compatibility
Expand Down Expand Up @@ -818,6 +822,7 @@ def get_comparison_info(cls, field_name: str) -> "ComparableFieldConfig":
threshold=threshold,
weight=weight,
clip_under_threshold=clip_under_threshold,
comparator_explicit="comparator_type" in comparison_config,
)

# Check if this is a structured field type that needs special handling
Expand Down
Loading
Loading