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(417)!: use one threshold tolerance at every classification gate
A primitive list element was classified with
ThresholdHelper.is_above_threshold, which accepts a score up to 1e-10
under the threshold. The field and nested-model gates in
FieldComparator, the List[StructuredModel] pair count and recursion
gate, the non_matches and field_comparisons collectors, the list item
sub-field classifier, EvalResult.matched,
HungarianMatcher.calculate_metrics and the evaluator_format fallback
metrics all used a bare >=. A score of 0.7 + 0.1 (0.7999999999999999)
against 0.8, such as the Laptop pair in threshold-gated-evaluation.md,
was an FD at those gates and a TP on a List[str] element.

Route every gate through ThresholdHelper.is_above_threshold. A score
inside the tolerance now counts as a TP, keeps its score instead of
being clipped to 0.0, and opens a list pair for field-by-field
evaluation. Scores further under the threshold are unchanged.

HungarianMatcher imports the helper inside calculate_metrics, so
stickler.algorithms does not load the evaluator package at import time.

Fixes #417
  • Loading branch information
Thanatos9404 committed Oct 18, 2026
commit 89e176d3dba64e724191700aeeb4242a27e34d83
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,28 @@ Each release links to full notes on the
([#322](https://github.com/awslabs/stickler/issues/322)). See
[`None` elements in a list](https://awslabs.github.io/stickler/Advanced/classification-logic/#none-elements-in-a-list)

- **Breaking:** a score that floating-point arithmetic leaves just under its
threshold now gets the same verdict at every gate. A primitive list element
allowed a `1e-10` tolerance, but a field, a nested model, a
`List[StructuredModel]` pair and `EvalResult.matched` used a bare `>=`. The
Laptop pair in the threshold-gating docs scores `0.7999999999999999` against
`match_threshold = 0.8`, so it was an FD and was not descended into, while the
same score on a `List[str]` element was a TP. Every gate now uses
`ThresholdHelper.is_above_threshold`. A score up to `1e-10` under its
threshold:
- counts as a TP instead of an FD, in the confusion matrix, `non_matches` and
`field_comparisons`, for a field, a nested model, a list item's sub-field and
a list pair;
- keeps its score instead of being clipped to `0.0`, so `field_scores` and
`overall_score` can rise;
- opens a list pair for field-by-field evaluation;
- sets `EvalResult.matched`, and counts as a TP in
`HungarianMatcher.calculate_metrics` and the `evaluator_format=True`
fallback metrics.

A score further under the threshold is unchanged, and so is a primitive list
element ([#417](https://github.com/awslabs/stickler/issues/417))

### Fixed

- **A `RootModel` is now refused when the evaluator is built, instead of failing
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 @@ -194,7 +194,7 @@ These are computed at every node of the result tree, from that node's own counts

**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`.

**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP).
**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP). So does a score up to `1e-10` under it, at every gate, so a rounding error such as `0.7 + 0.1` (`0.7999999999999999`) against `0.8` does not turn a TP into an FD.

**List order** -- Order does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position.

Expand Down
2 changes: 1 addition & 1 deletion docs/docs/Advanced/threshold-gated-evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ For the raw object similarity used by Hungarian matching, fields absent on both

**Empty lists** -- `[] vs []` is TN. `[] vs [items]` generates one FA per item. `[items] vs []` generates one FN per item.

**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches.
**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches, and so are values up to `1e-10` under it, so a rounding error does not flip the verdict.

**Different thresholds per model** -- Each `StructuredModel` subclass can define its own `match_threshold`. A `Product` with `match_threshold = 0.8` and an `Address` with `match_threshold = 0.6` are each evaluated independently.

Expand Down
23 changes: 12 additions & 11 deletions src/stickler/algorithms/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,18 @@ the method was returning that same pair inside `matched_pairs`. The fix reaches
only this class, so it says nothing about how `anls_score` treats a low score
pair; that runs through `trees/list_tree.py`.

## Two traps worth knowing before reading `tp`

**`match_threshold=0.0` is a capture all sentinel, not a threshold.** The test
is a bare `>=`, so every score satisfies zero and `tp` counts pairs rather than
true positives. `ComparisonHelper.compare_unordered_lists` builds a matcher
this way on purpose and reads only `matched_pairs`. Nothing should read `tp`
from a matcher built with `0.0`.

**The threshold test here is exact.** `ThresholdHelper` and `ComparisonHelper`
accept a score up to `1e-10` under the threshold, so a score inside that window
is a TP there and an FD here.
## Before reading `tp`

**`match_threshold=0.0` is a capture all sentinel, not a threshold.** Every
score satisfies zero, so `tp` counts pairs rather than true positives.
`ComparisonHelper.compare_unordered_lists` builds a matcher this way on
purpose and reads only `matched_pairs`. Nothing should read `tp` from a
matcher built with `0.0`.

**The threshold test is `ThresholdHelper.is_above_threshold`**, the one every
evaluator gate uses. It accepts a score up to `1e-10` under the threshold, so a
float rounding error does not turn a TP into an FD
([#417](https://github.com/awslabs/stickler/issues/417)).

## How the evaluator uses it

Expand Down
19 changes: 14 additions & 5 deletions src/stickler/algorithms/hungarian.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,15 +289,20 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict:
other convention, so the same counts read lower here than they do
as ``cm_recall`` there.

The threshold test here is a bare ``>=``. ``ThresholdHelper`` and
``ComparisonHelper`` use a tolerant test that accepts a score up
to ``1e-10`` under the threshold, so a score inside that window is
a TP there and an FD here.
The threshold test is ``ThresholdHelper.is_above_threshold``, the
one every evaluator gate uses. It accepts a score up to ``1e-10``
under the threshold, so ``0.7 + 0.1`` against ``0.8`` is a TP.

``match_threshold=0.0`` is used elsewhere as a capture all
sentinel. Every score satisfies ``>= 0.0``, so ``tp`` then counts
pairs rather than true positives and must not be read.
"""
# Imported here so stickler.algorithms does not load the evaluator
# package at import time; the evaluator imports this module.
from stickler.structured_object_evaluator.models.threshold_helper import (
ThresholdHelper,
)

prepared_list1, prepared_list2 = self._prepare_lists(list1, list2)
m, n = len(prepared_list1), len(prepared_list2)

Expand All @@ -322,7 +327,11 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict:
# cover max(m, n) items once each. The threshold splits the pairs into
# tp and fd. It does not un-match them, which is why a paired item
# never reaches fn or fa.
tp = sum(1 for _, _, score in matched_pairs if score >= self.match_threshold)
tp = sum(
1
for _, _, score in matched_pairs
if ThresholdHelper.is_above_threshold(score, self.match_threshold)
)
k = len(matched_pairs)
fd, fn, fa = k - tp, m - k, n - k
fp = fd + fa
Expand Down
10 changes: 8 additions & 2 deletions src/stickler/auto/facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from pydantic import BaseModel

from ..structured_object_evaluator.models.structured_model import StructuredModel
from ..structured_object_evaluator.models.threshold_helper import ThresholdHelper
from .builder import specs_for, structured_model_for

#: Object-level match threshold applied when neither the caller nor the model
Expand Down Expand Up @@ -76,8 +77,13 @@ def __init__(
# it against `match_threshold` gives one definition that cannot disagree
# with the score sitting beside it. The threshold is whatever the spec
# resolved: the caller's argument, else a StructuredModel's own declared
# `match_threshold`, else DEFAULT_MATCH_THRESHOLD. See `eval_for`.
self.matched: bool = bool(self.overall_score >= spec._match_threshold)
# `match_threshold`, else DEFAULT_MATCH_THRESHOLD. See `eval_for`. The
# test is the one list pairing uses for the same threshold (#417).
self.matched: bool = bool(
ThresholdHelper.is_above_threshold(
self.overall_score, spec._match_threshold
)
)

@property
def non_matches(self) -> List[Dict[str, Any]]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from .hungarian_helper import HungarianHelper
from .null_helper import NullHelper
from .threshold_helper import ThresholdHelper

DEFAULT_MATCH_THRESHOLD = 0.7

Expand Down Expand Up @@ -117,7 +118,11 @@ def process_matched_pairs(
pred_item = pred_list[pred_idx]

# Determine if this is a match
is_match = bool(similarity_score >= match_threshold)
is_match = bool(
ThresholdHelper.is_above_threshold(
similarity_score, match_threshold
)
)

# Create reason
reason = self.generate_comparison_reason(is_match, similarity_score, match_threshold)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from .field_helper import FieldHelper
from .metrics_helper import MetricsHelper
from .null_helper import NullHelper
from .threshold_helper import ThresholdHelper

if TYPE_CHECKING:
from .structured_model import StructuredModel
Expand Down Expand Up @@ -95,7 +96,7 @@ def classify_field_for_confusion_matrix(
pred_value = NullHelper.present(pred_value)
# Use the field's configured comparator for primitive comparison
similarity = comparator.compare(gt_value, pred_value)
values_match = similarity >= threshold
values_match = ThresholdHelper.is_above_threshold(similarity, threshold)
else:
values_match = False

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from typing import TYPE_CHECKING, Any, Dict

from .threshold_helper import ThresholdHelper

if TYPE_CHECKING:
from .structured_model import StructuredModel

Expand Down Expand Up @@ -65,7 +67,7 @@ def compare_primitive_with_scores(
threshold = info.threshold

# For binary classification metrics, always use threshold
if raw_similarity >= threshold:
if ThresholdHelper.is_above_threshold(raw_similarity, threshold):
metrics = {"tp": 1, "fa": 0, "fd": 0, "fp": 0, "tn": 0, "fn": 0}
threshold_applied_score = raw_similarity
else:
Expand Down Expand Up @@ -131,7 +133,7 @@ def compare_structured_field(
raw_score = gt_val.compare(pred_val) # Overall object similarity

# Apply object-level binary classification based on threshold
if raw_score >= threshold:
if ThresholdHelper.is_above_threshold(raw_score, threshold):
# Object matches threshold -> True Positive
object_metrics = {"tp": 1, "fa": 0, "fd": 0, "fp": 0, "tn": 0, "fn": 0}
threshold_applied_score = raw_score
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from .field_comparison_helper import FieldComparisonHelper
from .null_helper import NullHelper
from .threshold_helper import ThresholdHelper

if TYPE_CHECKING:
from .structured_model import StructuredModel
Expand Down Expand Up @@ -137,7 +138,9 @@ def collect_field_comparisons(

# Determine if this is a match based on threshold
info = self.model._get_comparison_info(field_name)
is_match = bool(raw_score >= info.threshold)
is_match = bool(
ThresholdHelper.is_above_threshold(raw_score, info.threshold)
)

# Determine reason
if is_match:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Dict, List, Optional

from .comparison_helper_base import ComparisonHelperBase
from .threshold_helper import ThresholdHelper


class FieldComparisonHelper(ComparisonHelperBase):
Expand Down Expand Up @@ -133,7 +134,9 @@ def _extract_entries_from_objects(

# Get field configuration for threshold
info = gt_object._get_comparison_info(nested_field_name)
field_is_match = field_score >= info.threshold
field_is_match = ThresholdHelper.is_above_threshold(
field_score, info.threshold
)

# Create field paths with indices
expected_key = f"{field_name}[{gt_index}].{nested_field_name}" if gt_index is not None else f"{field_name}[].{nested_field_name}"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from collections import OrderedDict
from typing import Any, Dict

from .threshold_helper import ThresholdHelper


class MetricsHelper:
"""Helper class for calculating and aggregating confusion matrix metrics."""
Expand Down Expand Up @@ -142,7 +144,7 @@ def convert_score_to_binary_metrics(
Dictionary with TP, FP, FN, TN counts converted to metrics
"""
# For single field comparison: if score >= threshold, it's TP, otherwise FP/FN
if score >= threshold:
if ThresholdHelper.is_above_threshold(score, threshold):
tp = score # Proportional TP credit
fp = 1 - score if score < 1.0 else 0 # Small FP for imperfect matches
fn = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from .hungarian_helper import HungarianHelper
from .metrics_helper import MetricsHelper
from .null_helper import NullHelper
from .threshold_helper import ThresholdHelper

if TYPE_CHECKING:
from .structured_model import StructuredModel
Expand Down Expand Up @@ -133,7 +134,7 @@ def _calculate_object_level_metrics(
tp_objects = 0 # Objects with similarity >= match_threshold
fd_objects = 0 # Objects with similarity < match_threshold
for gt_idx, pred_idx, similarity in matched_pairs:
if similarity >= match_threshold:
if ThresholdHelper.is_above_threshold(similarity, match_threshold):
tp_objects += 1
else:
fd_objects += 1
Expand Down Expand Up @@ -244,7 +245,7 @@ def _calculate_nested_field_metrics(
good_matched_pairs = [
(gt_idx, pred_idx, similarity)
for gt_idx, pred_idx, similarity in matched_pairs
if similarity >= match_threshold
if ThresholdHelper.is_above_threshold(similarity, match_threshold)
]

if good_matched_pairs:
Expand Down
Loading