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
Next Next commit
fix(383): let date, Decimal, UUID, Enum, tuple and set fields reach t…
…heir comparator

On an explicit StructuredModel the dispatcher treated only str, int and
float as scalars, so a field typed date, datetime, time, timedelta,
Decimal, UUID or Enum fell through to the mismatched-types case: an
identical value scored 0.0 and counted as a false discovery, and the
declared comparator was never called. Tuple and Set fields hit the same
case, because only list takes the list path.

- Route a pair of related scalars (an explicit type list) to the field's
  comparator. Unrelated types and arbitrary objects stay a mismatch.
- Score two tuples, or two sets, as one value, as stickler.evaluate()
  does, sorting a set first; compare_field_raw does the same so
  compare() agrees with compare_with().
- Treat an empty tuple or set as absent, like an empty list.

Closes #383
  • Loading branch information
sromoam committed Oct 13, 2026
commit 115b3500ca7ccd73a56ff1bc92ed9133f2110f10
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ Each release links to full notes on the

### Fixed

- **`StructuredModel` fields typed `date`, `datetime`, `time`, `timedelta`,
`Decimal`, `UUID` or `Enum` now reach their comparator.** 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. `stickler.evaluate()` was unaffected, because its shadow models turn
these values into strings first. Values of unrelated types (a `date` against a
`str`, two different `Enum` classes) are still a mismatch. `Tuple` and `Set`
fields had the same bug and are now scored as one value by the field's
comparator, as `stickler.evaluate()` scores them, with a set's elements put
in a fixed order first. An empty tuple or set now counts as absent, like an
empty list ([#383](https://github.com/awslabs/stickler/issues/383))

- **An unrecognized key in a model config is now reported instead of dropped.**
`model_from_json` read a closed set of keys and ignored everything else, so
`"threshhold": 0.99` built at the fallback 0.5 with no exception and no warning,
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Advanced/classification-logic.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ These are computed at every node of the result tree, from that node's own counts

## Edge Cases

**Null vs. empty equivalence** -- Empty strings (`""`), empty lists (`[]`), and empty objects (`{}`) are treated as null. Comparing any of these with `null` yields TN.
**Null vs. empty equivalence** -- Empty strings (`""`), empty lists (`[]`), empty tuples and sets, and empty objects (`{}`) are treated as null. Comparing any of these with `null` yields TN.

**TN in object matching** -- A TN is absence of evidence, not evidence of a match. Fields absent on both sides are excluded from the weighted object similarity used by Hungarian matching. If every field is absent, the similarity is defined as `1.0`.

Expand Down
7 changes: 6 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,17 @@ 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
# (scalar, scalar) of related type: date/datetime, time, timedelta,
# Decimal, UUID, Enum → FieldComparator (#383)
# (tuple, tuple) and (set, set) → FieldComparator, as one value; a set
# is sorted first (#383)
# (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 @@ -4,15 +4,50 @@
to appropriate handlers based on field type and null states.
"""

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

from pydantic import BaseModel

from .comparison_helper import canonical_collection
from .configuration_helper import ConfigurationHelper
from .null_helper import NullHelper
from .result_helper import ResultHelper
from .structured_model import StructuredModel

# Scalar types beyond str/int/float that a model field commonly declares.
# `datetime.date` covers `datetime.datetime`, its subclass. Deliberately a list
# rather than "anything that is not a container": an arbitrary object reaches
# a string comparator as its repr, and two distinct `<Foo object at 0x...>`
# reprs are near-identical strings, so they would score as a match.
_SCALAR_TYPES = (
datetime.date,
datetime.time,
datetime.timedelta,
decimal.Decimal,
uuid.UUID,
enum.Enum,
)


def _is_comparable_scalar_pair(gt_val: Any, pred_val: Any) -> bool:
"""Whether two values are scalars of the same kind, for the comparator to score.

Without this, a field typed ``date``, ``Decimal``, ``UUID`` or ``Enum``
fell through to the mismatched-types case and scored 0.0 against an
identical value, without its comparator ever being called (#383). The pair
must be related by type (``date`` and ``datetime`` are), so a
``Union[date, str]`` field holding one of each is still a mismatch.
"""
return (
isinstance(gt_val, _SCALAR_TYPES)
and isinstance(pred_val, _SCALAR_TYPES)
and (isinstance(gt_val, type(pred_val)) or isinstance(pred_val, type(gt_val)))
)


class ComparisonDispatcher:
"""Dispatches field comparisons to appropriate handlers based on field type.
Expand Down Expand Up @@ -190,15 +225,33 @@ 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: Primitive types (str, int, float), and the other scalar types
# pydantic models commonly declare (see _is_comparable_scalar_pair).
# Delegate to FieldComparator, which calls the field's comparator.
if (
isinstance(gt_val, (str, int, float))
and isinstance(pred_val, (str, int, float))
) or _is_comparable_scalar_pair(gt_val, pred_val):
return self.field_comparator.compare_primitive_with_scores(
gt_val, pred_val, field_name
)

# CASE 1b: Two tuples, or two sets. Scored as one value by the field's
# comparator, as stickler.evaluate() scores them, rather than element by
# element: only `list` takes the list path, and every reader of a list
# field (reports, the Hungarian cost matrix) assumes a `list`. A set is
# put in a fixed order first. Before this they fell through to CASE 6
# and scored 0.0 against an identical value (#383).
elif (isinstance(gt_val, tuple) and isinstance(pred_val, tuple)) or (
isinstance(gt_val, (set, frozenset))
and isinstance(pred_val, (set, frozenset))
):
return self.field_comparator.compare_primitive_with_scores(
canonical_collection(gt_val),
canonical_collection(pred_val),
field_name,
)

# CASE 2: Both are lists (non-empty, null/empty cases already handled in STEP 3)
# Determine if this is a structured list or primitive list by inspecting elements
elif isinstance(gt_val, list) and isinstance(pred_val, list):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,26 @@ def _maybe_absent(val: Any) -> bool:
``test_maybe_absent_is_a_superset_of_both_null_rules`` pins that property so
adding a case to either predicate without widening this one fails loudly.
"""
return val is None or (isinstance(val, (str, list, dict)) and len(val) == 0)
return val is None or (
isinstance(val, (str, list, dict, tuple, set, frozenset)) and len(val) == 0
)


def canonical_collection(value: Any) -> Any:
"""``value`` with a set's elements in a fixed order, for its comparator.

A ``Tuple`` or ``Set`` field is scored as one value by the field's
comparator, as ``stickler.evaluate()`` scores it (#383). A set has no order,
and a comparator that reads ``str(value)`` would score two equal sets apart
if they iterate differently, so a set becomes a sorted tuple. Anything else
is returned unchanged.
"""
if not isinstance(value, (set, frozenset)):
return value
try:
return tuple(sorted(value))
except TypeError: # mixed element types
return tuple(sorted(value, key=repr))


class ComparisonHelper:
Expand Down Expand Up @@ -541,4 +560,6 @@ def compare_field_raw(
return 0.0

# Use the comparator to calculate raw similarity (no threshold)
return comparator.compare(self_value, other_value)
return comparator.compare(
canonical_collection(self_value), canonical_collection(other_value)
)
11 changes: 9 additions & 2 deletions src/stickler/structured_object_evaluator/models/null_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,17 @@ def is_effectively_null_for_primitives(val: Any) -> bool:
empty/null combinations a true negative and turns the fourth
(``{}`` against populated) into a false alarm rather than a crash.

An empty tuple or set is absent for the same reason an empty list is:
it holds no items. ``Tuple`` and ``Set`` fields are scored as one value
rather than through the list path, so this rule, not the list one, is
the one they reach (#383).

Args:
val: Value to check

Returns:
True if the value is None, an empty string or an empty dict
True if the value is None, or an empty string, dict, tuple or set
"""
return val is None or (isinstance(val, (str, dict)) and len(val) == 0)
return val is None or (
isinstance(val, (str, dict, tuple, set, frozenset)) and len(val) == 0
)
Loading
Loading